diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..a586a94d3 --- /dev/null +++ b/.clang-format @@ -0,0 +1,41 @@ +--- +Language: Cpp +Standard: Cpp03 +AccessModifierOffset: -4 +AlignAfterOpenBracket: BlockIndent +AllowShortBlocksOnASingleLine: Empty +AllowShortEnumsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Empty +AlwaysBreakBeforeMultilineStrings: true +BinPackParameters: false +BreakBeforeBraces: Custom +BraceWrapping: + AfterClass: true + AfterControlStatement: Never + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterStruct: true + AfterUnion: true + AfterExternBlock: false + BeforeCatch: true + BeforeElse: false + BeforeWhile: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakConstructorInitializers: AfterColon +ColumnLimit: 120 +NamespaceIndentation: All +NamespaceMacros: + - TEST_GROUP +FixNamespaceComments: false +IndentPPDirectives: BeforeHash +IndentWidth: 4 +IndentExternBlock: NoIndent +PackConstructorInitializers: CurrentLine +PointerAlignment: Left +SortIncludes: Never +SpaceBeforeParens: Custom +SpaceBeforeParensOptions: + AfterForeachMacros: false diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 000000000..6a48af4f9 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,11 @@ +--- +Checks: + - clang-diagnostic-* + - clang-analyzer-* + - bugprone-* + - -bugprone-easily-swappable-parameters + - -bugprone-casting-through-void # No C++ casts allowed +WarningsAsErrors: "*" +FormatStyle: file +UseColor: true +HeaderFilterRegex: .* diff --git a/.cproject b/.cproject deleted file mode 100644 index 1249a9da3..000000000 --- a/.cproject +++ /dev/null @@ -1,141 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - make - extensions - true - true - true - - - make - - examples - true - true - true - - - make - - cleanExamples - true - true - true - - - - - diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..30c51b94f --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,7 @@ +# Enable via `git config blame.ignoreRevsFile .git-blame-ignore-revs` + +# Fix line endings +e674cfe759b20c6b78becbc50d8f9f644d32ea8a + +# clang-format +2a4942eb93b823c9723d4797222d6d3315f3bef2 diff --git a/.gitattributes b/.gitattributes index 089225dce..2bdb94418 100644 --- a/.gitattributes +++ b/.gitattributes @@ -13,3 +13,8 @@ *.mak text eol=crlf *.vcproj text eol=crlf *.vcxproj text eol=crlf + + +*.sh text +*.ac text +*.am text diff --git a/.github/workflows/basic.yml b/.github/workflows/basic.yml new file mode 100644 index 000000000..f89f04cb8 --- /dev/null +++ b/.github/workflows/basic.yml @@ -0,0 +1,432 @@ +--- +name: Basic builds + +"on": + push: + pull_request: + +jobs: + clang-format: + name: Clang Format + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@main + - uses: DoozyX/clang-format-lint-action@v0.14 + with: + clangFormatVersion: 14 + source: examples + + codeql: + runs-on: ubuntu-latest + name: "CodeQL" + steps: + - name: Checkout + uses: actions/checkout@main + - name: CodeQL Initialization + uses: github/codeql-action/init@v3 + with: + languages: cpp + queries: +security-and-quality + - name: Build + run: | + mkdir _build && cd _build + cmake -DCMAKE_CXX_STANDARD=17 .. + make -j2 + - name: CodeQL Analysis + uses: github/codeql-action/analyze@v3 + + autotools: + strategy: + matrix: + include: + - name: Mac GNU + os: macos-latest + cc: gcc + cxx: g++ + make_args: tdd + - name: Mac Clang + os: macos-latest + cc: clang + cxx: clang++ + make_args: tdd + - name: Linux GNU + os: ubuntu-latest + cc: gcc + cxx: g++ + make_args: tdd + - name: Linux Clang + os: ubuntu-latest + cc: clang + cxx: clang++ + make_args: tdd + - name: Disable long long + os: ubuntu-latest + configure_args: --disable-longlong + make_args: tdd + - name: Distribution + os: ubuntu-latest + make_args: dist dist-zip VERSION=latest + - name: Install + os: ubuntu-latest + make_args: DESTDIR=install_autotools install + runs-on: ${{ matrix.os }} + name: Autotools ${{ matrix.name }} + steps: + - name: Checkout + uses: actions/checkout@main + - run: brew install automake libtool + if: ${{ startswith(matrix.os, 'macos') }} + - if: ${{ matrix.cxx }} + run: echo "CXX=${{ matrix.cxx }}" >> $GITHUB_ENV + - if: ${{ matrix.cc }} + run: echo "CC=${{ matrix.cc }}" >> $GITHUB_ENV + - name: Configure + run: | + autoreconf -i . + ./configure ${{ matrix.configure_args }} + - name: Build and test + run: make ${{ matrix.make_args }} + + cmake: + strategy: + matrix: + include: + - name: MSVC install + os: windows-latest + preset: MSVC + install: true + ctest_args: -C Debug + - name: MSVC 20 + os: windows-latest + cmake_args: -DCMAKE_CXX_STANDARD=20 + preset: MSVC + ctest_args: -C Debug + - name: ClangCL + os: windows-latest + cmake_args: -DCMAKE_CXX_STANDARD=17 + preset: ClangCL + ctest_args: -C Debug + - name: Clang-Tidy + os: ubuntu-latest + preset: clang-tidy + - name: Linux Clang 98 + os: ubuntu-latest + cmake_args: -DCMAKE_CXX_STANDARD=98 + preset: Clang + - name: Linux Clang 11 + os: ubuntu-latest + cmake_args: -DCMAKE_CXX_STANDARD=11 + preset: Clang + - name: Linux Clang 14 + os: ubuntu-latest + cmake_args: -DCMAKE_CXX_STANDARD=14 + preset: Clang + - name: Linux Clang 17 + os: ubuntu-latest + cmake_args: -DCMAKE_CXX_STANDARD=17 + preset: Clang + - name: Linux Clang 20 + os: ubuntu-latest + cmake_args: -DCMAKE_CXX_STANDARD=20 + preset: Clang + - name: Linux GNU 98 + os: ubuntu-latest + cmake_args: -DCMAKE_CXX_STANDARD=98 + preset: GNU + - name: No long long + os: ubuntu-latest + preset: no-long-long + - name: Detailed + os: ubuntu-latest + preset: detailed + - name: Linux GNU Install + os: ubuntu-latest + cmake_args: -DCMAKE_CXX_STANDARD=11 + preset: GNU + install: true + - name: Linux GNU 14 + os: ubuntu-latest + cmake_args: -DCMAKE_CXX_STANDARD=14 + preset: GNU + - name: Linux GNU 17 + os: ubuntu-latest + cmake_args: -DCMAKE_CXX_STANDARD=17 + preset: GNU + - name: Linux GNU 20 + os: ubuntu-latest + cmake_args: -DCMAKE_CXX_STANDARD=20 + preset: GNU + - name: MinGW + os: ubuntu-latest + preset: MinGW + apt_packages: mingw-w64 wine64 + - name: No C++ Standard Library + os: ubuntu-latest + preset: no-std-cpp + - name: No RTTI + os: ubuntu-latest + preset: no-rtti + - name: No Exceptions + os: ubuntu-latest + preset: no-exceptions + - name: No C Standard Library + os: ubuntu-latest + preset: no-std-c + - name: Coverage + os: ubuntu-latest + preset: coverage + apt_packages: lcov + - name: Address Sanitizer + os: ubuntu-latest + preset: asan + - name: GCC ARM embedded + os: ubuntu-latest + preset: arm-embedded + - name: Mac install + os: macos-latest + preset: defaults + install: true + - name: Apple Clang 14 + os: macos-latest + cmake_args: -DCMAKE_CXX_STANDARD=14 + preset: Clang + - name: Apple Clang 17 + os: macos-latest + cmake_args: -DCMAKE_CXX_STANDARD=17 + preset: Clang + - name: Apple Clang 20 + os: macos-latest + cmake_args: -DCMAKE_CXX_STANDARD=20 + preset: Clang + - name: Mac GNU 14 + os: macos-latest + cmake_args: -DCMAKE_CXX_STANDARD=14 + preset: GNU + - name: OpenWatcom DOS + os: ubuntu-latest + preset: DOS + apt_packages: dosbox + - name: Cygwin + os: windows-latest + preset: GNU + name: CMake ${{ matrix.name }} + runs-on: ${{ matrix.os }} + steps: + ### SETUP + + - name: Install packages + run: | + sudo apt-get update + sudo apt-get install -y ${{ matrix.apt_packages }} + if: ${{ matrix.apt_packages }} + + - uses: carlosperate/arm-none-eabi-gcc-action@v1 + if: ${{ matrix.name == 'GCC ARM embedded' }} + + - name: Install OpenWatcom + uses: open-watcom/setup-watcom@v0 + with: + version: "2.0" + if: ${{ matrix.name == 'OpenWatcom DOS' }} + + - run: git config --global core.autocrlf input + if: ${{ matrix.name == 'Cygwin' }} + - name: Checkout + uses: actions/checkout@main + + - name: Install Cygwin + uses: cygwin/cygwin-install-action@master + with: + platform: x86 + packages: > + cmake + gcc-core + gcc-g++ + make + if: ${{ matrix.name == 'Cygwin' }} + + ## BUILD AND TEST + + - name: Configure + run: cmake --preset ${{ matrix.preset }} ${{ matrix.cmake_args }} + - name: Build + run: cmake --build cpputest_build --verbose -j + - name: Save map files + uses: actions/upload-artifact@v4 + with: + name: "${{ matrix.name }} map files" + path: cpputest_build/**/*.map + - name: Test + run: > + ctest + --test-dir cpputest_build + ${{ matrix.ctest_args }} + --output-on-failure + + # POST PROCESSING + + - name: Install (*nix) + run: | + sudo cmake --install cpputest_build/ + pkg-config --print-provides cpputest + if: ${{ matrix.install && !startswith(matrix.os, 'windows')}} + - name: Install (Windows) + run: cmake --install cpputest_build/ --config=Debug + if: ${{ matrix.install && startswith(matrix.os, 'windows')}} + - name: Use install + run: | + cmake -B build -S examples + cmake --build build -j + ctest --test-dir build + if: ${{ matrix.install }} + + - name: Coverage + run: | + lcov --ignore-errors mismatch --capture --directory . --no-external --output-file lcov.info + lcov --remove lcov.info --output-file lcov.info '*/tests/*' + if: ${{ matrix.name == 'Coverage' }} + - name: Coveralls + uses: coverallsapp/github-action@master + with: + path-to-lcov: lcov.info + github-token: ${{ secrets.GITHUB_TOKEN }} + if: ${{ matrix.name == 'Coverage' }} + + test_report: + name: JUnit Test Report + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@main + - run: cmake --preset=defaults -DCPPUTEST_JUNIT_REPORT=TRUE + - run: cmake --build cpputest_build -j + - run: ctest --test-dir cpputest_build + - uses: actions/upload-artifact@v4 + if: success() || failure() + with: + name: test-results + path: "cpputest_build/**/cpputest_*.xml" + + make: + strategy: + matrix: + include: + - name: Defaults + make_target: test_defaults + - name: STDC++ disabled + make_target: test_disable_std_cpp + - name: Memory Leak Detection disabled + make_target: test_disable_memory_leak_detection + - name: Disable Leak Detection and STD C++ + make_target: test_disable_std_cpp_and_leak_detection + - name: debug disabled + make_target: test_disable_debug + - name: overridden CXXFLAGS and CFLAGS and CPPFLAGS + make_target: test_override_flags + - name: without Standard C library includes + make_target: test_disable_std_c + - name: different TARGET_PLATFORM + make_target: test_target_platform + - name: override flags and disable memory leak and STDC++ + make_target: test_override_and_disable + - name: Examples + make_target: test_examples + - name: JUnit Output + make_target: test_junit_output + # - name: gcov + # make_target: test_gcov + - name: VPATH usage + make_target: test_vpath + - name: VPATH Install + make_target: test_vpath_install + name: Make ${{ matrix.name }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@main + - name: Build + run: make -f Makefile_using_MakefileWorker ${{ matrix.make_target }} + + make_dos: + name: Make OpenWatcom DOS + runs-on: ubuntu-latest + env: + TERM: linux + steps: + - name: Checkout + uses: actions/checkout@main + - name: Install tools + run: | + sudo apt-get update + sudo apt-get install -y dosbox + - name: Build & Test + run: ./scripts/dos_build_test.sh + + cmake_msys: + name: CMake MSYS + runs-on: windows-latest + defaults: + run: + shell: msys2 {0} + env: + LDFLAGS: -static + steps: + - name: Checkout + uses: actions/checkout@main + - uses: msys2/setup-msys2@v2 + with: + msystem: MINGW64 + update: true + install: > + git + mingw-w64-x86_64-cc + mingw-w64-x86_64-cmake + mingw-w64-x86_64-make + - name: Configure + run: cmake --preset=GNU + - name: Build + run: cmake --build cpputest_build -j + - name: Test + run: ctest --test-dir cpputest_build --output-on-failure + + autotools_msys: + name: Autotools MSYS + runs-on: windows-latest + defaults: + run: + shell: msys2 {0} + env: + LDFLAGS: -static + steps: + - uses: actions/checkout@v3 + - uses: msys2/setup-msys2@v2 + with: + msystem: MINGW64 + update: true + install: > + git + mingw-w64-x86_64-autotools + mingw-w64-x86_64-cc + mingw-w64-x86_64-make + - name: Configure + run: | + autoreconf -i . + ./configure + - name: Build and test + run: make tdd + + Docker: + strategy: + matrix: + image: ["ubuntu", "dos"] + runs-on: ubuntu-latest + name: Docker ${{ matrix.image }} + steps: + - name: Build + uses: docker/build-push-action@v3 + with: + file: docker/Dockerfile.${{ matrix.image }} + tags: cpputest/${{ matrix.image }}:latest + push: false + - name: Test + run: | + docker run --rm cpputest/${{ matrix.image }}:latest diff --git a/.github/workflows/test-report.yml b/.github/workflows/test-report.yml new file mode 100644 index 000000000..d44746601 --- /dev/null +++ b/.github/workflows/test-report.yml @@ -0,0 +1,17 @@ +--- +name: 'Test Report' +"on": + workflow_run: + workflows: ['Basic builds'] + types: + - completed +jobs: + report: + runs-on: ubuntu-latest + steps: + - uses: dorny/test-reporter@v1 + with: + artifact: test-results + name: JUnit Tests + path: "**/cpputest_*.xml" + reporter: java-junit diff --git a/.gitignore b/.gitignore index d344aef87..fa41116a8 100644 --- a/.gitignore +++ b/.gitignore @@ -50,6 +50,10 @@ Release _build_ _build builds/*gcc* +cpputest_build/Makefile +cpputest_build/generated +cpputest_build/src +cpputest_build/tests /.deps CppUTestExtTests CppUTestTests @@ -80,3 +84,23 @@ missing test-driver platforms/iar/settings cpputest_*.xml +generated/ +*.deps/ +*.dirstamp +*.trs +lcov.info + +#IAR automatically generated files +*.dep +*.ewt + +# Watcom +*.LIB +*.LST +*.EXE +*.LOG +/console_output +/exit + +# Builds +/cpputest_build/ diff --git a/.project b/.project deleted file mode 100644 index 978d661d1..000000000 --- a/.project +++ /dev/null @@ -1,78 +0,0 @@ - - - CppUTest - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - true - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - diff --git a/.settings/org.eclipse.cdt.core.prefs b/.settings/org.eclipse.cdt.core.prefs deleted file mode 100644 index 7bc75596d..000000000 --- a/.settings/org.eclipse.cdt.core.prefs +++ /dev/null @@ -1,152 +0,0 @@ -#Mon Jun 07 17:30:05 SGT 2010 -eclipse.preferences.version=1 -org.eclipse.cdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.cdt.core.formatter.alignment_for_base_clause_in_type_declaration=80 -org.eclipse.cdt.core.formatter.alignment_for_compact_if=0 -org.eclipse.cdt.core.formatter.alignment_for_conditional_expression=80 -org.eclipse.cdt.core.formatter.alignment_for_declarator_list=16 -org.eclipse.cdt.core.formatter.alignment_for_enumerator_list=48 -org.eclipse.cdt.core.formatter.alignment_for_expression_list=0 -org.eclipse.cdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.cdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.cdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.cdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.cdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.cdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.cdt.core.formatter.brace_position_for_method_declaration=next_line -org.eclipse.cdt.core.formatter.brace_position_for_namespace_declaration=next_line -org.eclipse.cdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.cdt.core.formatter.brace_position_for_type_declaration=next_line -org.eclipse.cdt.core.formatter.compact_else_if=true -org.eclipse.cdt.core.formatter.continuation_indentation=2 -org.eclipse.cdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.cdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.cdt.core.formatter.indent_access_specifier_compare_to_type_header=false -org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_access_specifier=true -org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_namespace_header=false -org.eclipse.cdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.cdt.core.formatter.indent_declaration_compare_to_template_header=false -org.eclipse.cdt.core.formatter.indent_empty_lines=false -org.eclipse.cdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.cdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_switch=false -org.eclipse.cdt.core.formatter.indentation.size=4 -org.eclipse.cdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.cdt.core.formatter.insert_new_line_after_template_declaration=do not insert -org.eclipse.cdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.cdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert -org.eclipse.cdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.cdt.core.formatter.insert_new_line_before_else_in_if_statement=insert -org.eclipse.cdt.core.formatter.insert_new_line_before_identifier_in_function_declaration=do not insert -org.eclipse.cdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert -org.eclipse.cdt.core.formatter.insert_new_line_in_empty_block=insert -org.eclipse.cdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.cdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.cdt.core.formatter.insert_space_after_closing_angle_bracket_in_template_arguments=insert -org.eclipse.cdt.core.formatter.insert_space_after_closing_angle_bracket_in_template_parameters=insert -org.eclipse.cdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.cdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.cdt.core.formatter.insert_space_after_colon_in_base_clause=insert -org.eclipse.cdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.cdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.cdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.cdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.cdt.core.formatter.insert_space_after_comma_in_base_types=insert -org.eclipse.cdt.core.formatter.insert_space_after_comma_in_declarator_list=insert -org.eclipse.cdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.cdt.core.formatter.insert_space_after_comma_in_expression_list=insert -org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.cdt.core.formatter.insert_space_after_comma_in_template_arguments=insert -org.eclipse.cdt.core.formatter.insert_space_after_comma_in_template_parameters=insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_angle_bracket_in_template_arguments=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_angle_bracket_in_template_parameters=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_bracket=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_exception_specification=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.cdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.cdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.cdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.cdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_angle_bracket_in_template_arguments=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_angle_bracket_in_template_parameters=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_bracket=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_exception_specification=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_colon_in_base_clause=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_colon_in_case=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.cdt.core.formatter.insert_space_before_colon_in_default=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_comma_in_base_types=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_comma_in_declarator_list=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_comma_in_expression_list=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_comma_in_template_arguments=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_comma_in_template_parameters=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_angle_bracket_in_template_arguments=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_angle_bracket_in_template_parameters=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_namespace_declaration=insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_bracket=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_exception_specification=insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_while=insert -org.eclipse.cdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.cdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.cdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.cdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.cdt.core.formatter.insert_space_between_empty_brackets=do not insert -org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_exception_specification=do not insert -org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.cdt.core.formatter.keep_else_statement_on_same_line=true -org.eclipse.cdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.cdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.cdt.core.formatter.keep_then_statement_on_same_line=true -org.eclipse.cdt.core.formatter.lineSplit=200 -org.eclipse.cdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.cdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.cdt.core.formatter.tabulation.char=tab -org.eclipse.cdt.core.formatter.tabulation.size=4 -org.eclipse.cdt.core.formatter.use_tabs_only_for_leading_indentations=false diff --git a/.settings/org.eclipse.cdt.ui.prefs b/.settings/org.eclipse.cdt.ui.prefs deleted file mode 100644 index b684b38df..000000000 --- a/.settings/org.eclipse.cdt.ui.prefs +++ /dev/null @@ -1,4 +0,0 @@ -#Tue Dec 29 09:23:19 SGT 2009 -eclipse.preferences.version=1 -formatter_profile=_CppUTest Coding Style -formatter_settings_version=1 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index c483ff027..000000000 --- a/.travis.yml +++ /dev/null @@ -1,54 +0,0 @@ -language: cpp -sudo: false -matrix: - include: - - compiler: clang - env: BUILD=autotools - addons: - apt: - packages: - - valgrind - - compiler: clang - env: BUILD=cmake - - compiler: clang - env: BUILD=autotools_gtest - - compiler: clang - env: BUILD=cmake_gtest - - compiler: gcc - env: BUILD=autotools - addons: - apt: - packages: - - valgrind - - compiler: gcc - env: BUILD=cmake - - compiler: gcc - env: BUILD=autotools_gtest - - compiler: gcc - env: BUILD=cmake_gtest - - compiler: gcc - env: BUILD=cmake_coverage - - compiler: gcc - env: BUILD=test_report - - compiler: wcl - env: BUILD=make_dos - addons: - apt: - packages: - - dosbox -global: -- os: linux -- rvm: '1.9.3' -- secure: |- - P05xUfJVw5YM4hF7hzQLjyMzDD4Q1/fyWP9Uk5aK5VrSWNY99EuxldXI5QK/ - vA1NkcW49tQW1wQvBlRtdlLNOmUfDP/oiJFXPwNn4dqwOIOEet2P7JO/5hnH - MNHlZmGu2WpoZREhOFBfsIhK0IP8mloqLDq2XemBdga/LWygrLU= -- secure: |- - Y/8iNkf6uEbE3qltnM+7mGlCvFWzyttwwRGgVGw1m9xOiUJcobvOImQRU8XZ - 91dgO+Fz0A3mljqs1sK1OPjpXmFGE1jP/NlotMw0WlDOuSIDjQ4ubwdTNGAw - NY53R9ygbIjEmqxHAJm9mOZqxW2hNaoI7TcX6oX248/hLibyx8M= -before_script: -- export CPPUTEST_BUILD_DIR=$TRAVIS_BUILD_DIR/cpputest_build -- mkdir -p $CPPUTEST_BUILD_DIR && cd $CPPUTEST_BUILD_DIR -script: -- "../scripts/travis_ci_build.sh" diff --git a/.travis_github_deployer.yml b/.travis_github_deployer.yml deleted file mode 100644 index 08e782d2f..000000000 --- a/.travis_github_deployer.yml +++ /dev/null @@ -1,10 +0,0 @@ -destination_repository: https://github.com/cpputest/cpputest.github.io.git - -files_to_deploy: - cpputest_build/unit_test_report/*: unit_test_report - cpputest_build/cpputest-3.7dev.tar.gz: - destination: releases - purge: yes - cpputest_build/cpputest-3.7dev.zip: - destination: releases - purge: yes diff --git a/CMakeLists.txt b/CMakeLists.txt index b1900bb37..0b6a4eeaf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,160 +1,154 @@ -project(CppUTest) - -set(CppUTest_version_major 3) -set(CppUTest_version_minor 8) - # 2.6.3 is needed for ctest support -cmake_minimum_required(VERSION 2.8.7) - -# Check for functions before setting a lot of stuff -include(CheckFunctionExists) -set (CMAKE_REQUIRED_INCLUDES "unistd.h") -check_function_exists(fork HAVE_FORK) -if(HAVE_FORK) - add_definitions(-DCPPUTEST_HAVE_FORK) -endif(HAVE_FORK) - -# Apply workaround for MinGW timespec redefinition (pthread.h / time.h) -if (MINGW) - include(CheckStructHasMember) - check_struct_has_member("struct timespec" tv_sec time.h HAVE_STRUCT_TIMESPEC) - if (HAVE_STRUCT_TIMESPEC) - add_definitions(-D_TIMESPEC_DEFINED=1) - endif() +# 3.1 is needed for target_sources +# 3.8 is needed for try_compile improvements (CMP0067) +cmake_minimum_required(VERSION 3.8...3.31) + +project(CppUTest + VERSION 4.0 +) + +if (CMAKE_VERSION VERSION_GREATER_EQUAL "3.21") + # PROJECT_IS_TOP_LEVEL is defined automatically +elseif (CMAKE_CURRENT_BINARY_DIR STREQUAL CMAKE_BINARY_DIR) + set(PROJECT_IS_TOP_LEVEL TRUE) +else() + set(PROJECT_IS_TOP_LEVEL FALSE) endif() -option(STD_C "Use the standard C library" ON) -option(STD_CPP "Use the standard C++ library" ON) -option(CPPUTEST_FLAGS "Use the CFLAGS/CXXFLAGS/LDFLAGS set by CppUTest" ON) -option(MEMORY_LEAK_DETECTION "Enable memory leak detection" ON) -option(EXTENSIONS "Use the CppUTest extenstion library" ON) -option(LONGLONG "Support long long" OFF) -option(MAP_FILE "Enable the creation of a map file" OFF) -option(COVERAGE "Enable running with coverage" OFF) -option(C++11 "Compile with C++11 support" OFF) - -option(TESTS "Compile and make tests for the code?" ON) -option(TESTS_DETAILED "Run each test separately instead of grouped?" OFF) +############### +# Conan support +############### +if (EXISTS "${CMAKE_BINARY_DIR}/conanbuildinfo.cmake") + include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) + message(STATUS "conan_basic_setup()") + conan_basic_setup() +endif() -if(NOT CMAKE_BUILD_TYPE) - set(CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING "What kind of build this is" FORCE) -endif(NOT CMAKE_BUILD_TYPE) +include(CTest) -# Pkg-config file -include(FindPkgConfig) -set(CppUTest_PKGCONFIG_FILE cpputest.pc) +include(CMakeDependentOption) +option(CPPUTEST_STD_C_LIB_DISABLED "Disable the standard C library") + +cmake_dependent_option(CPPUTEST_STD_CPP_LIB_DISABLED "Use the standard C++ library" + OFF "NOT CPPUTEST_STD_C_LIB_DISABLED" ON) +cmake_dependent_option(CPPUTEST_MEM_LEAK_DETECTION_DISABLED "Enable memory leak detection" + OFF "NOT BORLAND;NOT CPPUTEST_STD_C_LIB_DISABLED" ON) +option(CPPUTEST_EXTENSIONS "Use the CppUTest extension library" ON) +include(CheckTypeSize) +check_type_size("long long" SIZEOF_LONGLONG) +cmake_dependent_option(CPPUTEST_USE_LONG_LONG "Support long long" + YES "HAVE_SIZEOF_LONGLONG" OFF) + +cmake_dependent_option(CPPUTEST_BUILD_TESTING "Compile and make tests for CppUTest" + ${PROJECT_IS_TOP_LEVEL} "BUILD_TESTING" OFF) +cmake_dependent_option(CPPUTEST_SPLIT_TESTS "Split tests into small executables" + OFF "CPPUTEST_BUILD_TESTING" OFF) +cmake_dependent_option(CPPUTEST_TEST_GTEST "Test GoogleTest integration" + OFF "CPPUTEST_BUILD_TESTING" OFF) +cmake_dependent_option(CPPUTEST_EXAMPLES "Compile and make examples?" + ${PROJECT_IS_TOP_LEVEL} "CPPUTEST_EXTENSIONS;NOT CPPUTEST_STD_CPP_LIB_DISABLED" OFF) + +if(NOT DEFINED CPPUTEST_PLATFORM) + if(DEFINED CPP_PLATFORM) + message(DEPRECATION + "The CPP_PLATFORM variable has been deprecated. " + "Use CPPUTEST_PLATFORM instead." + ) + set(CPPUTEST_PLATFORM ${CPP_PLATFORM}) + else() + if(CPPUTEST_STD_C_LIB_DISABLED) + set(CPPUTEST_PLATFORM OFF) + elseif(MSVC) + set(CPPUTEST_PLATFORM VisualCpp) + elseif(CMAKE_CXX_COMPILER_ID STREQUAL "IAR") + set(CPPUTEST_PLATFORM Iar) + elseif(CMAKE_CXX_COMPILER_ID STREQUAL "ARMCC") + set(CPPUTEST_PLATFORM armcc) + elseif(DOS) + set(CPPUTEST_PLATFORM Dos) + elseif(BORLAND) + set(CPPUTEST_PLATFORM Borland) + else() + set(CPPUTEST_PLATFORM Gcc) + endif() + endif() + message(STATUS "Setting CPPUTEST_PLATFORM: ${CPPUTEST_PLATFORM}") +endif() +set(CPPUTEST_PLATFORM "${CPPUTEST_PLATFORM}" CACHE STRING "Platform implementation") +set_property( + CACHE CPPUTEST_PLATFORM + PROPERTY STRINGS + armcc Borland C2000 Dos Gcc Iar Keil Symbian VisualCpp OFF +) + +include(CheckCXXSymbolExists) +check_cxx_symbol_exists(fopen_s "stdio.h" CPPUTEST_HAVE_SECURE_STDLIB) +cmake_dependent_option(CPPUTEST_USE_SECURE_STDLIB "Use MSVC safe functions" + ON "WIN32;CPPUTEST_HAVE_SECURE_STDLIB" OFF) + +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules") +if(NOT PROJECT_IS_TOP_LEVEL) + set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}" PARENT_SCOPE) +endif() -set(CppUTestRootDirectory ${PROJECT_SOURCE_DIR}) -set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CppUTestRootDirectory}/cmake/Modules) +if( + (NOT CPPUTEST_MEM_LEAK_DETECTION_DISABLED) + AND (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL "15.1") +) + # Leak detection macros are not sane. + message(NOTICE "Disabling -fassume-sane-operators-new-delete which breaks leak detection") + add_compile_options($<$:-fno-assume-sane-operators-new-delete>) +endif() -include("${CppUTestRootDirectory}/cmake/Modules/CppUTestConfigurationOptions.cmake") -include(CTest) -#include("${CppUTestRootDirectory}/cmake/Modules/CheckFunctionExists.cmake") -include("${CppUTestRootDirectory}/cmake/Modules/CppUTestBuildTimeDiscoverTests.cmake") -include("${CppUTestRootDirectory}/cmake/Modules/CppUTestNormalizeTestOutputLocation.cmake") +if(PROJECT_IS_TOP_LEVEL) + include(cmake/warnings.cmake) +endif() +include(GNUInstallDirs) + +# Check for symbols before setting a lot of stuff +include(CheckTypeSize) +include(CheckStructHasMember) +set(CMAKE_REQUIRED_FLAGS ${CMAKE_CXX_FLAGS}) +check_cxx_symbol_exists(kill "signal.h" CPPUTEST_HAVE_KILL) +check_cxx_symbol_exists(fork "unistd.h" CPPUTEST_HAVE_FORK) +check_cxx_symbol_exists(waitpid "sys/wait.h" CPPUTEST_HAVE_WAITPID) +check_cxx_symbol_exists(gettimeofday "sys/time.h" CPPUTEST_HAVE_GETTIMEOFDAY) +check_cxx_symbol_exists(pthread_mutex_lock "pthread.h" CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK) + +if (NOT CMAKE_CXX_COMPILER_ID STREQUAL "IAR") + check_cxx_symbol_exists(strdup "string.h" CPPUTEST_HAVE_STRDUP) +endif() +check_type_size("long long" SIZEOF_LONGLONG LANGUAGE CXX) +if(HAVE_SIZEOF_LONGLONG) + set(CPPUTEST_HAVE_LONG_LONG_INT ON) +endif() configure_file ( "${PROJECT_SOURCE_DIR}/config.h.cmake" "${PROJECT_BINARY_DIR}/generated/CppUTestGeneratedConfig.h" - ) -include_directories(${PROJECT_BINARY_DIR}) -add_definitions(-DHAVE_CONFIG_H) +) -include_directories(${CppUTestRootDirectory}/include) -add_subdirectory(src/CppUTest) +add_subdirectory(src) -if (EXTENSIONS) - add_subdirectory(src/CppUTestExt) -endif (EXTENSIONS) +target_include_directories(CppUTest + PUBLIC + $ +) +target_compile_definitions(CppUTest + PUBLIC + HAVE_CONFIG_H +) -if (TESTS) +if (CPPUTEST_BUILD_TESTING) add_subdirectory(tests) -endif (TESTS) - -set (INCLUDE_INSTALL_DIR "include") -set (LIB_INSTALL_DIR "lib") -set (INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include") - -# Pkg-config file. -set (prefix "${CMAKE_INSTALL_PREFIX}") -set (exec_prefix "\${prefix}") -set (libdir "\${exec_prefix}/${LIB_INSTALL_DIR}") -set (includedir "\${prefix}/${INCLUDE_INSTALL_DIR}") -set (PACKAGE_VERSION "${CppUTest_version_major}.${CppUTest_version_minor}") - -configure_file (cpputest.pc.in - ${CMAKE_CURRENT_BINARY_DIR}/${CppUTest_PKGCONFIG_FILE} @ONLY) - -install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${CppUTest_PKGCONFIG_FILE} - DESTINATION ${LIB_INSTALL_DIR}/pkgconfig - ) - -install(FILES "${CMAKE_CURRENT_BINARY_DIR}/generated/CppUTestGeneratedConfig.h" - DESTINATION "${INCLUDE_INSTALL_DIR}/CppUTest" - ) +endif () -# Try to include helper module -include(CMakePackageConfigHelpers OPTIONAL - RESULT_VARIABLE PkgHelpers_AVAILABLE) -# guard against older versions of cmake which do not provide it -if(PkgHelpers_AVAILABLE) - configure_package_config_file(CppUTestConfig.cmake.install.in - ${CMAKE_CURRENT_BINARY_DIR}/install/CppUTestConfig.cmake - INSTALL_DESTINATION ${LIB_INSTALL_DIR}/CppUTest/cmake - PATH_VARS INCLUDE_INSTALL_DIR LIB_INSTALL_DIR) - write_basic_package_version_file( - ${CMAKE_CURRENT_BINARY_DIR}/install/CppUTestConfigVersion.cmake - VERSION ${CppUTest_version_major}.${CppUTest_version_minor} - COMPATIBILITY SameMajorVersion ) - install(FILES ${CMAKE_CURRENT_BINARY_DIR}/install/CppUTestConfig.cmake - ${CMAKE_CURRENT_BINARY_DIR}/install/CppUTestConfigVersion.cmake - DESTINATION ${LIB_INSTALL_DIR}/CppUTest/cmake ) - install(EXPORT CppUTestTargets - DESTINATION ${LIB_INSTALL_DIR}/CppUTest/cmake) - configure_package_config_file(CppUTestConfig.cmake.build.in - ${CMAKE_CURRENT_BINARY_DIR}/CppUTestConfig.cmake - INSTALL_DESTINATION ${CMAKE_CURRENT_BINARY_DIR} - PATH_VARS INCLUDE_DIR CMAKE_CURRENT_BINARY_DIR) - export(TARGETS CppUTest CppUTestExt - FILE "${CMAKE_CURRENT_BINARY_DIR}/CppUTestTargets.cmake") - write_basic_package_version_file( - ${CMAKE_CURRENT_BINARY_DIR}/CppUTestConfigVersion.cmake - VERSION ${CppUTest_version_major}.${CppUTest_version_minor} - COMPATIBILITY SameMajorVersion ) - set(CppUTest_DIR "${CMAKE_CURRENT_BINARY_DIR}" CACHE PATH "The directory containing a CMake configuration file for CppUTest.") -else() - message("If you wish to use find_package(CppUTest) in your own project to find CppUTest library" - " please update cmake to version which provides CMakePackageConfighelpers module" - " or write generators for CppUTestConfig.cmake by yourself.") +if (CPPUTEST_EXAMPLES) + add_subdirectory(examples) endif() -message(" -------------------------------------------------------- -CppUTest Version ${CppUTest_version_major}.${CppUTest_version_minor} - -Current compiler options: - CC: ${CMAKE_C_COMPILER} - CXX: ${CMAKE_CXX_COMPILER} - CppUTest CFLAGS: ${CPPUTEST_C_FLAGS} - CppUTest CXXFLAGS: ${CPPUTEST_CXX_FLAGS} - CppUTest LDFLAGS: ${CPPUTEST_LD_FLAGS} - -Features configured in CppUTest: - Memory Leak Detection: ${MEMORY_LEAK_DETECTION} - Compiling Extensions: ${EXTENSIONS} - Support Long Long: ${LONGLONG} - Use CppUTest flags: ${CPPUTEST_FLAGS} - - Using Standard C library: ${STD_C} - Using Standard C++ library: ${STD_CPP} - Using C++11 library: ${C++11} - - Generating map file: ${MAP_FILE} - Compiling with coverage: ${COVERAGE} - - Compile and run self-tests ${TESTS} - Run self-tests separately ${TESTS_DETAILED} - -------------------------------------------------------- -") +if(PROJECT_IS_TOP_LEVEL) + include(cmake/install.cmake) +endif() diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 000000000..a4a3f8327 --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,183 @@ +{ + "version": 3, + "configurePresets": [ + { + "name": "defaults", + "binaryDir": "cpputest_build", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "RelWithDebInfo", + "CMAKE_CXX_EXTENSIONS": false + } + }, + { + "name": "GNU", + "inherits": ["defaults"], + "environment": { + "CFLAGS": "-Werror", + "CXXFLAGS": "-Werror" + }, + "cacheVariables": { + "CMAKE_C_COMPILER": "gcc", + "CMAKE_CXX_COMPILER": "g++" + } + }, + { + "name": "Clang", + "inherits": ["GNU"], + "cacheVariables": { + "CMAKE_C_COMPILER": "clang", + "CMAKE_CXX_COMPILER": "clang++" + } + }, + { + "name": "clang-tidy", + "inherits": ["Clang"], + "cacheVariables": { + "CMAKE_CXX_CLANG_TIDY": "clang-tidy;-header-filter=.*", + "CMAKE_C_CLANG_TIDY": "clang-tidy;-header-filter=.*" + } + }, + { + "name": "MSVC", + "inherits": ["defaults"], + "environment": { + "CFLAGS": "/WX", + "CXXFLAGS": "/WX" + } + }, + { + "name": "ClangCL", + "inherits": ["MSVC"], + "generator": "Visual Studio 17 2022", + "toolset": "ClangCL" + }, + { + "name": "MinGW", + "inherits": ["GNU"], + "environment": { + "LDFLAGS": "-static" + }, + "cacheVariables": { + "CMAKE_C_COMPILER": "x86_64-w64-mingw32-gcc", + "CMAKE_CXX_COMPILER": "x86_64-w64-mingw32-g++", + "CMAKE_SYSTEM_NAME": "Windows", + "CMAKE_CROSSCOMPILING_EMULATOR": "wine" + } + }, + { + "name": "arm-embedded", + "inherits": ["defaults"], + "toolchainFile": "${sourceDir}/cmake/Toolchains/arm-none-eabi-gcc.toolchain.cmake", + "cacheVariables": { + "CMAKE_CROSSCOMPILING_EMULATOR": "docker;run;--rm;-v=${sourceDir}:${sourceDir};multiarch/qemu-user-static:arm-7.1.0-2;qemu-arm-static;-cpu;cortex-m4" + } + }, + { + "name": "coverage", + "inherits": ["GNU"], + "environment": { + "CFLAGS": "--coverage", + "CXXFLAGS": "--coverage" + }, + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug", + "CMAKE_CXX_STANDARD": "11", + "CPPUTEST_EXAMPLES": false + } + }, + { + "name": "no-std-cpp", + "inherits": ["GNU"], + "environment": { + "CXXFLAGS": "-Werror -nostdinc++" + }, + "cacheVariables": { + "CPPUTEST_STD_CPP_LIB_DISABLED": true + } + }, + { + "name": "no-rtti", + "inherits": ["GNU"], + "environment": { + "CXXFLAGS": "-Werror -fno-rtti" + } + }, + { + "name": "no-exceptions", + "inherits": ["GNU"], + "environment": { + "CXXFLAGS": "-Werror -fno-exceptions" + } + }, + { + "name": "no-std-c", + "inherits": ["GNU"], + "environment": { + "CXXFLAGS": "-DCPPUTEST_CHAR_BIT=8 -Werror -nostdinc", + "CFLAGS": "-DCPPUTEST_CHAR_BIT=8 -Werror -nostdinc" + }, + "cacheVariables": { + "CPPUTEST_STD_C_LIB_DISABLED": true + } + }, + { + "name": "no-long-long", + "inherits": ["GNU"], + "cacheVariables": { + "CPPUTEST_USE_LONG_LONG": false + } + }, + { + "name": "asan", + "inherits": ["Clang"], + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug" + }, + "environment": { + "CFLAGS": "-fsanitize=address -fno-omit-frame-pointer", + "CXXFLAGS": "-fsanitize=address -fno-omit-frame-pointer", + "LDFLAGS": "-fsanitize=address" + } + }, + { + "name": "detailed", + "inherits": ["defaults"], + "cacheVariables": { + "CPPUTEST_TESTS_DETAILED": true + } + }, + { + "name": "gtest", + "inherits": ["defaults"], + "generator": "Ninja Multi-Config", + "cacheVariables": { + "CPPUTEST_TEST_GTEST": true, + "gtest_build_tests": true + } + }, + { + "name": "IAR", + "inherits": ["defaults"], + "cacheVariables": { + "CMAKE_SYSTEM_NAME": "Generic", + "CMAKE_C_COMPILER": "iccarm", + "CMAKE_C_FLAGS_INIT": "--cpu Cortex-M4F --dlib_config normal", + "CMAKE_CXX_COMPILER": "iccarm", + "CMAKE_CXX_FLAGS_INIT": "--cpu Cortex-M4F --dlib_config normal", + "CMAKE_EXE_LINKER_FLAGS": "--semihosting --config ${sourceDir}/platforms/iar/CppUTestTest.icf" + } + }, + { + "name": "DOS", + "inherits": ["defaults"], + "generator": "Watcom WMake", + "cacheVariables": { + "CMAKE_SYSTEM_NAME": "DOS", + "CMAKE_BUILD_TYPE": "MinRelSize", + "CMAKE_CXX_STANDARD": "98", + "CPPUTEST_MEM_LEAK_DETECTION_DISABLED": true, + "CPPUTEST_STD_CPP_LIB_DISABLED": true + } + } + ] +} diff --git a/ChangeLog b/ChangeLog index 3985c9c82..399179154 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,18 +1,4 @@ -Addition to Release 3.7 and Release 3.7.1: - -* -v and -ojunit together -* Better memory leak printing -* MEMCMP_EQUAL -* STRNCMP_EQUAL -* Memory Leak Detector multi-threading support -* Mock Output parameters -* Better Windows support -* Many Mock improvements -* Many small fixes and improvements -* Less platform specific dependencies -* More platforms supported - -For further changelog check the github page: +For changelog check the github page: https://github.com/cpputest/cpputest diff --git a/CppUTest.dep b/CppUTest.dep deleted file mode 100644 index b3dbf6f43..000000000 --- a/CppUTest.dep +++ /dev/null @@ -1,583 +0,0 @@ -# Microsoft Developer Studio Generated Dependency File, included by CppUTest.mak - -.\src\CppUTestExt\CodeMemoryReportFormatter.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestMemoryAllocator.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\CppUTestExt\CodeMemoryReportFormatter.h"\ - ".\include\CppUTestExt\MemoryReportAllocator.h"\ - ".\include\CppUTestExt\MemoryReportFormatter.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\CommandLineArguments.cpp : \ - ".\include\CppUTest\CommandLineArguments.h"\ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestFilter.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\CommandLineTestRunner.cpp : \ - ".\include\CppUTest\CommandLineArguments.h"\ - ".\include\CppUTest\CommandLineTestRunner.h"\ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\JunitTestOutput.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestFilter.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestRegistry.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\JUnitTestOutput.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\JunitTestOutput.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\MemoryLeakDetector.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetector.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleMutex.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestMemoryAllocator.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\MemoryLeakWarningPlugin.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetector.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleMutex.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestMemoryAllocator.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\src\CppUTestExt\MemoryReportAllocator.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestMemoryAllocator.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\CppUTestExt\MemoryReportAllocator.h"\ - ".\include\CppUTestExt\MemoryReportFormatter.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\src\CppUTestExt\MemoryReporterPlugin.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestMemoryAllocator.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\CppUTestExt\CodeMemoryReportFormatter.h"\ - ".\include\CppUTestExt\MemoryReportAllocator.h"\ - ".\include\CppUTestExt\MemoryReporterPlugin.h"\ - ".\include\CppUTestExt\MemoryReportFormatter.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\src\CppUTestExt\MemoryReportFormatter.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestMemoryAllocator.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\CppUTestExt\MemoryReportAllocator.h"\ - ".\include\CppUTestExt\MemoryReportFormatter.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -".\src\CppUTestExt\MockActualCall.cpp" : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\cpputestext\mockactualcall.h"\ - ".\include\CppUTestExt\MockCheckedActualCall.h"\ - ".\include\CppUTestExt\MockCheckedExpectedCall.h"\ - ".\include\cpputestext\mockexpectedcall.h"\ - ".\include\CppUTestExt\MockExpectedCallsList.h"\ - ".\include\CppUTestExt\MockFailure.h"\ - ".\include\CppUTestExt\MockNamedValue.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -".\src\CppUTestExt\MockExpectedCall.cpp" : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\CppUTestExt\MockCheckedExpectedCall.h"\ - ".\include\cpputestext\mockexpectedcall.h"\ - ".\include\CppUTestExt\MockNamedValue.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -".\src\CppUTestExt\MockExpectedCallsList.cpp" : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\CppUTestExt\MockCheckedExpectedCall.h"\ - ".\include\cpputestext\mockexpectedcall.h"\ - ".\include\CppUTestExt\MockExpectedCallsList.h"\ - ".\include\CppUTestExt\MockNamedValue.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -".\src\CppUTestExt\MockFailure.cpp" : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\cpputestext\mockexpectedcall.h"\ - ".\include\CppUTestExt\MockExpectedCallsList.h"\ - ".\include\CppUTestExt\MockFailure.h"\ - ".\include\CppUTestExt\MockNamedValue.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -".\src\CppUTestExt\MockNamedValue.cpp" : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\CppUTestExt\MockNamedValue.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -".\src\CppUTestExt\MockSupport.cpp" : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\cpputestext\mockactualcall.h"\ - ".\include\CppUTestExt\MockCheckedActualCall.h"\ - ".\include\CppUTestExt\MockCheckedExpectedCall.h"\ - ".\include\cpputestext\mockexpectedcall.h"\ - ".\include\CppUTestExt\MockExpectedCallsList.h"\ - ".\include\CppUTestExt\MockFailure.h"\ - ".\include\CppUTestExt\MockNamedValue.h"\ - ".\include\CppUTestExt\MockSupport.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -".\src\CppUTestExt\MockSupport_c.cpp" : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\cpputestext\mockactualcall.h"\ - ".\include\CppUTestExt\MockCheckedActualCall.h"\ - ".\include\CppUTestExt\MockCheckedExpectedCall.h"\ - ".\include\cpputestext\mockexpectedcall.h"\ - ".\include\CppUTestExt\MockExpectedCallsList.h"\ - ".\include\CppUTestExt\MockFailure.h"\ - ".\include\CppUTestExt\MockNamedValue.h"\ - ".\include\CppUTestExt\MockSupport.h"\ - ".\include\CppUTestExt\MockSupport_c.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -".\src\CppUTestExt\MockSupportPlugin.cpp" : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\cpputestext\mockactualcall.h"\ - ".\include\CppUTestExt\MockCheckedActualCall.h"\ - ".\include\CppUTestExt\MockCheckedExpectedCall.h"\ - ".\include\cpputestext\mockexpectedcall.h"\ - ".\include\CppUTestExt\MockExpectedCallsList.h"\ - ".\include\CppUTestExt\MockFailure.h"\ - ".\include\CppUTestExt\MockNamedValue.h"\ - ".\include\CppUTestExt\MockSupport.h"\ - ".\include\CppUTestExt\MockSupportPlugin.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -".\src\CppUTestExt\OrderedTest.cpp" : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestFilter.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestRegistry.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\CppUTestExt\OrderedTest.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\SimpleMutex.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleMutex.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\SimpleString.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestMemoryAllocator.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\TestFailure.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\TestFilter.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFilter.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\TestHarness_c.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetector.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestHarness_c.h"\ - ".\include\CppUTest\TestMemoryAllocator.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\TestMemoryAllocator.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetector.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestMemoryAllocator.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\TestOutput.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\TestPlugin.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\TestRegistry.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestFilter.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestRegistry.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\TestResult.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\SRC\CPPUTEST\Utest.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestFilter.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestRegistry.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - - -.\src\Platforms\VisualCpp\UtestPlatform.cpp : \ - ".\include\CppUTest\CppUTestConfig.h"\ - ".\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - ".\include\CppUTest\MemoryLeakWarningPlugin.h"\ - ".\include\CppUTest\PlatformSpecificFunctions.h"\ - ".\include\CppUTest\PlatformSpecificFunctions_c.h"\ - ".\include\CppUTest\SimpleString.h"\ - ".\include\CppUTest\StandardCLibrary.h"\ - ".\include\CppUTest\TestFailure.h"\ - ".\include\CppUTest\TestHarness.h"\ - ".\include\CppUTest\TestOutput.h"\ - ".\include\CppUTest\TestPlugin.h"\ - ".\include\CppUTest\TestResult.h"\ - ".\include\CppUTest\Utest.h"\ - ".\include\CppUTest\UtestMacros.h"\ - ".\include\platforms\visualcpp\platform.h"\ - ".\include\platforms\visualcpp\stdint.h"\ - diff --git a/CppUTest.dsp b/CppUTest.dsp deleted file mode 100644 index f13f8216e..000000000 --- a/CppUTest.dsp +++ /dev/null @@ -1,361 +0,0 @@ -# Microsoft Developer Studio Project File - Name="CppUTest" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Static Library" 0x0104 - -CFG=CppUTest - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "CppUTest.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "CppUTest.mak" CFG="CppUTest - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "CppUTest - Win32 Release" (based on "Win32 (x86) Static Library") -!MESSAGE "CppUTest - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "CppUTest - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c -# ADD CPP /nologo /W3 /GX /O2 /I ".\include\Platforms\VisualCpp" /I ".\include" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D "CPPUTEST_MEM_LEAK_DETECTION_DISABLED" /D "CPPUTEST_USE_LONG_LONG" /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo /out:"lib\CppUTest.lib" - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c -# ADD CPP /nologo /MDd /W3 /GX /ZI /Od /I ".\include\Platforms\VisualCpp" /I ".\include" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /D "CPPUTEST_MEM_LEAK_DETECTION_DISABLED" /D "CPPUTEST_USE_LONG_LONG" /FR /FD /GZ /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo /out:"lib\CppUTestd.lib" - -!ENDIF - -# Begin Target - -# Name "CppUTest - Win32 Release" -# Name "CppUTest - Win32 Debug" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\src\CppUTestExt\CodeMemoryReportFormatter.cpp -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\MemoryReportAllocator.cpp -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\MemoryReporterPlugin.cpp -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\MemoryReportFormatter.cpp -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\MockActualCall.cpp" -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\MockExpectedCall.cpp" -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\MockExpectedCallsList.cpp" -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\MockFailure.cpp" -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\MockNamedValue.cpp" -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\MockSupport.cpp" -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\MockSupportPlugin.cpp" -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\MockSupport_c.cpp" -# End Source File -# Begin Source File - -SOURCE=.\src\CppUTestExt\OrderedTest.cpp" -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\CommandLineArguments.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\CommandLineTestRunner.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\JUnitTestOutput.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\MemoryLeakDetector.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\MemoryLeakWarningPlugin.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\SimpleMutex.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\SimpleString.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\TeamCityTestOutput.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\TestFailure.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\TestFilter.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\TestHarness_c.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\TestMemoryAllocator.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\TestOutput.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\TestPlugin.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\TestRegistry.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\TestResult.cpp -# End Source File -# Begin Source File - -SOURCE=.\SRC\CPPUTEST\Utest.cpp -# End Source File -# Begin Source File - -SOURCE=.\src\Platforms\VisualCpp\UtestPlatform.cpp -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=.\include\CppUTestExt\CodeMemoryReportFormatter.h" -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\GMock.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\GTestConvertor.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\MemoryReportAllocator.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\MemoryReporterPlugin.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\MemoryReportFormatter.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\MockCheckedActualCall.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\MockCheckedExpectedCall.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\MockExpectedCallsList.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\MockFailure.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\MockNamedValue.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\MockSupport.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\MockSupportPlugin.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\MockSupport_c.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTestExt\OrderedTest.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\CommandLineTestRunner.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\EqualsFailure.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\Failure.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\JunitTestOutput.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\MemoryLeakWarning.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\MemoryLeakWarningPlugin.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\MockTestOutput.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\NullTest.h -# End Source File -# Begin Source File - -SOURCE=.\src\Platforms\VisualCpp\Platform.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\RealTestOutput.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\SimpleString.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\SimpleStringExtensions.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\TestHarness.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\TestHarness_c.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\TestInstaller.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\TestOutput.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\TestPlugin.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\TestRegistry.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\TestResult.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\Utest.h -# End Source File -# Begin Source File - -SOURCE=.\include\CppUTest\VirtualCall.h -# End Source File -# End Group -# End Target -# End Project diff --git a/CppUTest.dsw b/CppUTest.dsw deleted file mode 100644 index cab2e26f9..000000000 --- a/CppUTest.dsw +++ /dev/null @@ -1,44 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "AllTests"=.\tests\AllTests.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ - Begin Project Dependency - Project_Dep_Name CppUTest - End Project Dependency -}}} - -############################################################################### - -Project: "CppUTest"=.\CppUTest.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/CppUTest.mak b/CppUTest.mak deleted file mode 100644 index 52b1aca6a..000000000 --- a/CppUTest.mak +++ /dev/null @@ -1,891 +0,0 @@ -# Microsoft Developer Studio Generated NMAKE File, Based on CppUTest.dsp -!IF "$(CFG)" == "" -CFG=CppUTest - Win32 Debug -!MESSAGE No configuration specified. Defaulting to CppUTest - Win32 Debug. -!ENDIF - -!IF "$(CFG)" != "CppUTest - Win32 Release" && "$(CFG)" != "CppUTest - Win32 Debug" -!MESSAGE Invalid configuration "$(CFG)" specified. -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "CppUTest.mak" CFG="CppUTest - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "CppUTest - Win32 Release" (based on "Win32 (x86) Static Library") -!MESSAGE "CppUTest - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE -!ERROR An invalid configuration is specified. -!ENDIF - -!IF "$(OS)" == "Windows_NT" -NULL= -!ELSE -NULL=nul -!ENDIF - -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "CppUTest - Win32 Release" - -OUTDIR=.\Release -INTDIR=.\Release -# Begin Custom Macros -OutDir=.\Release -# End Custom Macros - -ALL : "$(OUTDIR)\CppUTest.lib" - - -CLEAN : - -@erase "$(INTDIR)\CodeMemoryReportFormatter.obj" - -@erase "$(INTDIR)\CommandLineArguments.obj" - -@erase "$(INTDIR)\CommandLineTestRunner.obj" - -@erase "$(INTDIR)\JUnitTestOutput.obj" - -@erase "$(INTDIR)\TeamCityTestOutput.obj" - -@erase "$(INTDIR)\MemoryLeakDetector.obj" - -@erase "$(INTDIR)\MemoryLeakWarningPlugin.obj" - -@erase "$(INTDIR)\MemoryReportAllocator.obj" - -@erase "$(INTDIR)\MemoryReporterPlugin.obj" - -@erase "$(INTDIR)\MemoryReportFormatter.obj" - -@erase "$(INTDIR)\MockActualCall.obj" - -@erase "$(INTDIR)\MockExpectedCall.obj" - -@erase "$(INTDIR)\MockExpectedCallsList.obj" - -@erase "$(INTDIR)\MockFailure.obj" - -@erase "$(INTDIR)\MockNamedValue.obj" - -@erase "$(INTDIR)\MockSupport.obj" - -@erase "$(INTDIR)\MockSupport_c.obj" - -@erase "$(INTDIR)\MockSupportPlugin.obj" - -@erase "$(INTDIR)\OrderedTest.obj" - -@erase "$(INTDIR)\SimpleMutex.obj" - -@erase "$(INTDIR)\SimpleString.obj" - -@erase "$(INTDIR)\TestFailure.obj" - -@erase "$(INTDIR)\TestFilter.obj" - -@erase "$(INTDIR)\TestHarness_c.obj" - -@erase "$(INTDIR)\TestMemoryAllocator.obj" - -@erase "$(INTDIR)\TestOutput.obj" - -@erase "$(INTDIR)\TestPlugin.obj" - -@erase "$(INTDIR)\TestRegistry.obj" - -@erase "$(INTDIR)\TestResult.obj" - -@erase "$(INTDIR)\Utest.obj" - -@erase "$(INTDIR)\UtestPlatform.obj" - -@erase "$(INTDIR)\vc60.idb" - -@erase "$(OUTDIR)\CppUTest.lib" - -"$(OUTDIR)" : - if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" - -CPP_PROJ=/nologo /ML /W3 /GX /O2 /I ".\include\Platforms\VisualCpp" /I ".\include" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D "CPPUTEST_MEM_LEAK_DETECTION_DISABLED" /D "CPPUTEST_USE_LONG_LONG" /Fp"$(INTDIR)\CppUTest.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c -BSC32=bscmake.exe -BSC32_FLAGS=/nologo /o"$(OUTDIR)\CppUTest.bsc" -BSC32_SBRS= \ - -LIB32=link.exe -lib -LIB32_FLAGS=/nologo /out:"$(OUTDIR)\CppUTest.lib" -LIB32_OBJS= \ - "$(INTDIR)\CodeMemoryReportFormatter.obj" \ - "$(INTDIR)\MemoryReportAllocator.obj" \ - "$(INTDIR)\MemoryReporterPlugin.obj" \ - "$(INTDIR)\MemoryReportFormatter.obj" \ - "$(INTDIR)\MockActualCall.obj" \ - "$(INTDIR)\MockExpectedCall.obj" \ - "$(INTDIR)\MockExpectedCallsList.obj" \ - "$(INTDIR)\MockFailure.obj" \ - "$(INTDIR)\MockNamedValue.obj" \ - "$(INTDIR)\MockSupport.obj" \ - "$(INTDIR)\MockSupportPlugin.obj" \ - "$(INTDIR)\MockSupport_c.obj" \ - "$(INTDIR)\OrderedTest.obj" \ - "$(INTDIR)\CommandLineArguments.obj" \ - "$(INTDIR)\CommandLineTestRunner.obj" \ - "$(INTDIR)\JUnitTestOutput.obj" \ - "$(INTDIR)\TeamCityTestOutput.obj" \ - "$(INTDIR)\MemoryLeakDetector.obj" \ - "$(INTDIR)\MemoryLeakWarningPlugin.obj" \ - "$(INTDIR)\SimpleMutex.obj" \ - "$(INTDIR)\SimpleString.obj" \ - "$(INTDIR)\TestFailure.obj" \ - "$(INTDIR)\TestFilter.obj" \ - "$(INTDIR)\TestHarness_c.obj" \ - "$(INTDIR)\TestMemoryAllocator.obj" \ - "$(INTDIR)\TestOutput.obj" \ - "$(INTDIR)\TestPlugin.obj" \ - "$(INTDIR)\TestRegistry.obj" \ - "$(INTDIR)\TestResult.obj" \ - "$(INTDIR)\Utest.obj" \ - "$(INTDIR)\UtestPlatform.obj" - -"$(OUTDIR)\CppUTest.lib" : "$(OUTDIR)" $(DEF_FILE) $(LIB32_OBJS) - $(LIB32) @<< - $(LIB32_FLAGS) $(DEF_FLAGS) $(LIB32_OBJS) -<< - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - -OUTDIR=.\Debug -INTDIR=.\Debug -# Begin Custom Macros -OutDir=.\Debug -# End Custom Macros - -ALL : ".\lib\CppUTest.lib" "$(OUTDIR)\CppUTest.bsc" - - -CLEAN : - -@erase "$(INTDIR)\CodeMemoryReportFormatter.obj" - -@erase "$(INTDIR)\CodeMemoryReportFormatter.sbr" - -@erase "$(INTDIR)\CommandLineArguments.obj" - -@erase "$(INTDIR)\CommandLineArguments.sbr" - -@erase "$(INTDIR)\CommandLineTestRunner.obj" - -@erase "$(INTDIR)\CommandLineTestRunner.sbr" - -@erase "$(INTDIR)\JUnitTestOutput.obj" - -@erase "$(INTDIR)\JUnitTestOutput.sbr" - -@erase "$(INTDIR)\TeamCityTestOutput.obj" - -@erase "$(INTDIR)\TeamCityTestOutput.sbr" - -@erase "$(INTDIR)\MemoryLeakDetector.obj" - -@erase "$(INTDIR)\MemoryLeakDetector.sbr" - -@erase "$(INTDIR)\MemoryLeakWarningPlugin.obj" - -@erase "$(INTDIR)\MemoryLeakWarningPlugin.sbr" - -@erase "$(INTDIR)\MemoryReportAllocator.obj" - -@erase "$(INTDIR)\MemoryReportAllocator.sbr" - -@erase "$(INTDIR)\MemoryReporterPlugin.obj" - -@erase "$(INTDIR)\MemoryReporterPlugin.sbr" - -@erase "$(INTDIR)\MemoryReportFormatter.obj" - -@erase "$(INTDIR)\MemoryReportFormatter.sbr" - -@erase "$(INTDIR)\MockActualCall.obj" - -@erase "$(INTDIR)\MockActualCall.sbr" - -@erase "$(INTDIR)\MockExpectedCall.obj" - -@erase "$(INTDIR)\MockExpectedCall.sbr" - -@erase "$(INTDIR)\MockExpectedCallsList.obj" - -@erase "$(INTDIR)\MockExpectedCallsList.sbr" - -@erase "$(INTDIR)\MockFailure.obj" - -@erase "$(INTDIR)\MockFailure.sbr" - -@erase "$(INTDIR)\MockNamedValue.obj" - -@erase "$(INTDIR)\MockNamedValue.sbr" - -@erase "$(INTDIR)\MockSupport.obj" - -@erase "$(INTDIR)\MockSupport.sbr" - -@erase "$(INTDIR)\MockSupport_c.obj" - -@erase "$(INTDIR)\MockSupport_c.sbr" - -@erase "$(INTDIR)\MockSupportPlugin.obj" - -@erase "$(INTDIR)\MockSupportPlugin.sbr" - -@erase "$(INTDIR)\OrderedTest.obj" - -@erase "$(INTDIR)\OrderedTest.sbr" - -@erase "$(INTDIR)\SimpleMutex.obj" - -@erase "$(INTDIR)\SimpleMutex.sbr" - -@erase "$(INTDIR)\SimpleString.obj" - -@erase "$(INTDIR)\SimpleString.sbr" - -@erase "$(INTDIR)\TestFailure.obj" - -@erase "$(INTDIR)\TestFailure.sbr" - -@erase "$(INTDIR)\TestFilter.obj" - -@erase "$(INTDIR)\TestFilter.sbr" - -@erase "$(INTDIR)\TestHarness_c.obj" - -@erase "$(INTDIR)\TestHarness_c.sbr" - -@erase "$(INTDIR)\TestMemoryAllocator.obj" - -@erase "$(INTDIR)\TestMemoryAllocator.sbr" - -@erase "$(INTDIR)\TestOutput.obj" - -@erase "$(INTDIR)\TestOutput.sbr" - -@erase "$(INTDIR)\TestPlugin.obj" - -@erase "$(INTDIR)\TestPlugin.sbr" - -@erase "$(INTDIR)\TestRegistry.obj" - -@erase "$(INTDIR)\TestRegistry.sbr" - -@erase "$(INTDIR)\TestResult.obj" - -@erase "$(INTDIR)\TestResult.sbr" - -@erase "$(INTDIR)\Utest.obj" - -@erase "$(INTDIR)\Utest.sbr" - -@erase "$(INTDIR)\UtestPlatform.obj" - -@erase "$(INTDIR)\UtestPlatform.sbr" - -@erase "$(INTDIR)\vc60.idb" - -@erase "$(INTDIR)\vc60.pdb" - -@erase "$(OUTDIR)\CppUTest.bsc" - -@erase ".\lib\CppUTest.lib" - -"$(OUTDIR)" : - if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" - -CPP_PROJ=/nologo /MDd /W3 /GX /ZI /Od /I ".\include\Platforms\VisualCpp" /I ".\include" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /D "CPPUTEST_MEM_LEAK_DETECTION_DISABLED" /D "CPPUTEST_USE_LONG_LONG" /FR"$(INTDIR)\\" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /GZ /c -BSC32=bscmake.exe -BSC32_FLAGS=/nologo /o"$(OUTDIR)\CppUTest.bsc" -BSC32_SBRS= \ - "$(INTDIR)\CodeMemoryReportFormatter.sbr" \ - "$(INTDIR)\MemoryReportAllocator.sbr" \ - "$(INTDIR)\MemoryReporterPlugin.sbr" \ - "$(INTDIR)\MemoryReportFormatter.sbr" \ - "$(INTDIR)\MockActualCall.sbr" \ - "$(INTDIR)\MockExpectedCall.sbr" \ - "$(INTDIR)\MockExpectedCallsList.sbr" \ - "$(INTDIR)\MockFailure.sbr" \ - "$(INTDIR)\MockNamedValue.sbr" \ - "$(INTDIR)\MockSupport.sbr" \ - "$(INTDIR)\MockSupportPlugin.sbr" \ - "$(INTDIR)\MockSupport_c.sbr" \ - "$(INTDIR)\OrderedTest.sbr" \ - "$(INTDIR)\CommandLineArguments.sbr" \ - "$(INTDIR)\CommandLineTestRunner.sbr" \ - "$(INTDIR)\JUnitTestOutput.sbr" \ - "$(INTDIR)\TeamCityTestOutput.sbr" \ - "$(INTDIR)\MemoryLeakDetector.sbr" \ - "$(INTDIR)\MemoryLeakWarningPlugin.sbr" \ - "$(INTDIR)\SimpleMutex.sbr" \ - "$(INTDIR)\SimpleString.sbr" \ - "$(INTDIR)\TestFailure.sbr" \ - "$(INTDIR)\TestFilter.sbr" \ - "$(INTDIR)\TestHarness_c.sbr" \ - "$(INTDIR)\TestMemoryAllocator.sbr" \ - "$(INTDIR)\TestOutput.sbr" \ - "$(INTDIR)\TestPlugin.sbr" \ - "$(INTDIR)\TestRegistry.sbr" \ - "$(INTDIR)\TestResult.sbr" \ - "$(INTDIR)\Utest.sbr" \ - "$(INTDIR)\UtestPlatform.sbr" - -"$(OUTDIR)\CppUTest.bsc" : "$(OUTDIR)" $(BSC32_SBRS) - $(BSC32) @<< - $(BSC32_FLAGS) $(BSC32_SBRS) -<< - -LIB32=link.exe -lib -LIB32_FLAGS=/nologo /out:"lib\CppUTest.lib" -LIB32_OBJS= \ - "$(INTDIR)\CodeMemoryReportFormatter.obj" \ - "$(INTDIR)\MemoryReportAllocator.obj" \ - "$(INTDIR)\MemoryReporterPlugin.obj" \ - "$(INTDIR)\MemoryReportFormatter.obj" \ - "$(INTDIR)\MockActualCall.obj" \ - "$(INTDIR)\MockExpectedCall.obj" \ - "$(INTDIR)\MockExpectedCallsList.obj" \ - "$(INTDIR)\MockFailure.obj" \ - "$(INTDIR)\MockNamedValue.obj" \ - "$(INTDIR)\MockSupport.obj" \ - "$(INTDIR)\MockSupportPlugin.obj" \ - "$(INTDIR)\MockSupport_c.obj" \ - "$(INTDIR)\OrderedTest.obj" \ - "$(INTDIR)\CommandLineArguments.obj" \ - "$(INTDIR)\CommandLineTestRunner.obj" \ - "$(INTDIR)\JUnitTestOutput.obj" \ - "$(INTDIR)\TeamCityTestOutput.obj" \ - "$(INTDIR)\MemoryLeakDetector.obj" \ - "$(INTDIR)\MemoryLeakWarningPlugin.obj" \ - "$(INTDIR)\SimpleMutex.obj" \ - "$(INTDIR)\SimpleString.obj" \ - "$(INTDIR)\TestFailure.obj" \ - "$(INTDIR)\TestFilter.obj" \ - "$(INTDIR)\TestHarness_c.obj" \ - "$(INTDIR)\TestMemoryAllocator.obj" \ - "$(INTDIR)\TestOutput.obj" \ - "$(INTDIR)\TestPlugin.obj" \ - "$(INTDIR)\TestRegistry.obj" \ - "$(INTDIR)\TestResult.obj" \ - "$(INTDIR)\Utest.obj" \ - "$(INTDIR)\UtestPlatform.obj" - -".\lib\CppUTest.lib" : "$(OUTDIR)" $(DEF_FILE) $(LIB32_OBJS) - $(LIB32) @<< - $(LIB32_FLAGS) $(DEF_FLAGS) $(LIB32_OBJS) -<< - -!ENDIF - -.c{$(INTDIR)}.obj:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - -.cpp{$(INTDIR)}.obj:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - -.cxx{$(INTDIR)}.obj:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - -.c{$(INTDIR)}.sbr:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - -.cpp{$(INTDIR)}.sbr:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - -.cxx{$(INTDIR)}.sbr:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - - -!IF "$(NO_EXTERNAL_DEPS)" != "1" -!IF EXISTS("CppUTest.dep") -!INCLUDE "CppUTest.dep" -!ELSE -!MESSAGE Warning: cannot find "CppUTest.dep" -!ENDIF -!ENDIF - - -!IF "$(CFG)" == "CppUTest - Win32 Release" || "$(CFG)" == "CppUTest - Win32 Debug" -SOURCE=.\src\CppUTestExt\CodeMemoryReportFormatter.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\CodeMemoryReportFormatter.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\CodeMemoryReportFormatter.obj" "$(INTDIR)\CodeMemoryReportFormatter.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\CommandLineArguments.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\CommandLineArguments.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\CommandLineArguments.obj" "$(INTDIR)\CommandLineArguments.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\CommandLineTestRunner.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\CommandLineTestRunner.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\CommandLineTestRunner.obj" "$(INTDIR)\CommandLineTestRunner.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\JUnitTestOutput.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\JUnitTestOutput.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\JUnitTestOutput.obj" "$(INTDIR)\JUnitTestOutput.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\TeamCityTestOutput.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\TeamCityTestOutput.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\TeamCityTestOutput.obj" "$(INTDIR)\TeamCityTestOutput.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\MemoryLeakDetector.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MemoryLeakDetector.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MemoryLeakDetector.obj" "$(INTDIR)\MemoryLeakDetector.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\MemoryLeakWarningPlugin.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MemoryLeakWarningPlugin.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MemoryLeakWarningPlugin.obj" "$(INTDIR)\MemoryLeakWarningPlugin.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\src\CppUTestExt\MemoryReportAllocator.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MemoryReportAllocator.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MemoryReportAllocator.obj" "$(INTDIR)\MemoryReportAllocator.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\src\CppUTestExt\MemoryReporterPlugin.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MemoryReporterPlugin.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MemoryReporterPlugin.obj" "$(INTDIR)\MemoryReporterPlugin.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\src\CppUTestExt\MemoryReportFormatter.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MemoryReportFormatter.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MemoryReportFormatter.obj" "$(INTDIR)\MemoryReportFormatter.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=".\src\CppUTestExt\MockActualCall.cpp" - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MockActualCall.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MockActualCall.obj" "$(INTDIR)\MockActualCall.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=".\src\CppUTestExt\MockExpectedCall.cpp" - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MockExpectedCall.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MockExpectedCall.obj" "$(INTDIR)\MockExpectedCall.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=".\src\CppUTestExt\MockExpectedCallsList.cpp" - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MockExpectedCallsList.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MockExpectedCallsList.obj" "$(INTDIR)\MockExpectedCallsList.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=".\src\CppUTestExt\MockFailure.cpp" - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MockFailure.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MockFailure.obj" "$(INTDIR)\MockFailure.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=".\src\CppUTestExt\MockNamedValue.cpp" - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MockNamedValue.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MockNamedValue.obj" "$(INTDIR)\MockNamedValue.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=".\src\CppUTestExt\MockSupport.cpp" - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MockSupport.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MockSupport.obj" "$(INTDIR)\MockSupport.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=".\src\CppUTestExt\MockSupport_c.cpp" - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MockSupport_c.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MockSupport_c.obj" "$(INTDIR)\MockSupport_c.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=".\src\CppUTestExt\MockSupportPlugin.cpp" - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\MockSupportPlugin.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\MockSupportPlugin.obj" "$(INTDIR)\MockSupportPlugin.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=".\src\CppUTestExt\OrderedTest.cpp" - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\OrderedTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\OrderedTest.obj" "$(INTDIR)\OrderedTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\SimpleMutex.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\SimpleMutex.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\SimpleMutex.obj" "$(INTDIR)\SimpleMutex.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\SimpleString.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\SimpleString.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\SimpleString.obj" "$(INTDIR)\SimpleString.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\TestFailure.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\TestFailure.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\TestFailure.obj" "$(INTDIR)\TestFailure.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\TestFilter.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\TestFilter.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\TestFilter.obj" "$(INTDIR)\TestFilter.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\TestHarness_c.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\TestHarness_c.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\TestHarness_c.obj" "$(INTDIR)\TestHarness_c.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\TestMemoryAllocator.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\TestMemoryAllocator.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\TestMemoryAllocator.obj" "$(INTDIR)\TestMemoryAllocator.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\TestOutput.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\TestOutput.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\TestOutput.obj" "$(INTDIR)\TestOutput.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\TestPlugin.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\TestPlugin.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\TestPlugin.obj" "$(INTDIR)\TestPlugin.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\TestRegistry.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\TestRegistry.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\TestRegistry.obj" "$(INTDIR)\TestRegistry.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\TestResult.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\TestResult.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\TestResult.obj" "$(INTDIR)\TestResult.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\SRC\CPPUTEST\Utest.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\Utest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\Utest.obj" "$(INTDIR)\Utest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\src\Platforms\VisualCpp\UtestPlatform.cpp - -!IF "$(CFG)" == "CppUTest - Win32 Release" - - -"$(INTDIR)\UtestPlatform.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "CppUTest - Win32 Debug" - - -"$(INTDIR)\UtestPlatform.obj" "$(INTDIR)\UtestPlatform.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - - -!ENDIF - diff --git a/CppUTest.vcproj b/CppUTest.vcproj index c0edc3813..9a8bfdcc2 100644 --- a/CppUTest.vcproj +++ b/CppUTest.vcproj @@ -41,7 +41,7 @@ + + + + + + + + @@ -604,6 +626,28 @@ /> + + + + + + + + @@ -883,6 +927,10 @@ RelativePath=".\include\CppUTestExt\GTest.h" > + + @@ -899,6 +947,10 @@ RelativePath=".\include\CppUTest\MemoryLeakDetector.h" > + + @@ -983,6 +1035,10 @@ RelativePath="include\CppUTest\SimpleString.h" > + + diff --git a/CppUTest.vcxproj b/CppUTest.vcxproj index 16e718e85..4a2f18e61 100644 --- a/CppUTest.vcxproj +++ b/CppUTest.vcxproj @@ -5,10 +5,18 @@ Debug Win32 + + Debug + x64 + Release Win32 + + Release + x64 + {F468F539-27BD-468E-BE64-DDE641400B51} @@ -19,35 +27,54 @@ false MultiByte + + StaticLibrary + false + MultiByte + StaticLibrary false MultiByte + + StaticLibrary + false + MultiByte + - + + + - + + + <_ProjectFileVersion>10.0.30319.1 - lib\ - cpputest_build\Debug\$(ProjectName)\ - lib\ - cpputest_build\Release\$(ProjectName)\ + lib\x86\ + lib\x64\ + cpputest_build\Debug\x86\$(ProjectName)\ + cpputest_build\Debug\x64\$(ProjectName)\ + lib\x86\ + lib\x64\ + cpputest_build\Release\x86\$(ProjectName)\ + cpputest_build\Release\x64\$(ProjectName)\ $(ProjectName)d + $(ProjectName)d Disabled - .\include;.\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) + .\include;%(AdditionalIncludeDirectories) _LIB;WIN32;_DEBUG;STDC_WANT_SECURE_LIB;CPPUTEST_USE_LONG_LONG;%(PreprocessorDefinitions) EnableFastChecks MultiThreadedDebugDLL @@ -76,10 +103,42 @@ true + + + Disabled + .\include;%(AdditionalIncludeDirectories) + _LIB;WIN32;_DEBUG;STDC_WANT_SECURE_LIB;CPPUTEST_USE_LONG_LONG;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + winmm.lib;%(AdditionalDependencies) + + + true + .\Debug/CppUTestd.bsc + + + + + + + + true + + Disabled - .\include;.\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) + .\include;%(AdditionalIncludeDirectories) OnlyExplicitInline WIN32;NDEBUG;_LIB;STDC_WANT_SECURE_LIB;CPPUTEST_USE_LONG_LONG;%(PreprocessorDefinitions) true @@ -88,6 +147,42 @@ Level3 true OldStyle + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + winmm.lib;%(AdditionalDependencies) + + + true + .\Release/CppUTest.bsc + + + + + + + + true + + + + + Disabled + .\include;%(AdditionalIncludeDirectories) + OnlyExplicitInline + WIN32;NDEBUG;_LIB;STDC_WANT_SECURE_LIB;CPPUTEST_USE_LONG_LONG;%(PreprocessorDefinitions) + true + MultiThreadedDLL + true + Level3 + true + OldStyle + true NDEBUG;%(PreprocessorDefinitions) @@ -112,6 +207,7 @@ + @@ -133,6 +229,7 @@ + @@ -143,16 +240,13 @@ - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions) - %(PreprocessorDefinitions) - + + @@ -177,12 +271,14 @@ + + diff --git a/CppUTestConfig.cmake.install.in b/CppUTestConfig.cmake.install.in index 2edba1c1d..3c79ea3aa 100644 --- a/CppUTestConfig.cmake.install.in +++ b/CppUTestConfig.cmake.install.in @@ -1,7 +1,9 @@ @PACKAGE_INIT@ set_and_check(CppUTest_INCLUDE_DIRS "@PACKAGE_INCLUDE_INSTALL_DIR@") +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/Modules") include("${CMAKE_CURRENT_LIST_DIR}/CppUTestTargets.cmake") set(CppUTest_LIBRARIES CppUTest CppUTestExt) +include("${CMAKE_CURRENT_LIST_DIR}/Modules/CppUTestBuildTimeDiscoverTests.cmake") check_required_components(CppUTest) diff --git a/CppUTest_VS201x.sln b/CppUTest_VS201x.sln index 12db37f5f..d794568ba 100644 --- a/CppUTest_VS201x.sln +++ b/CppUTest_VS201x.sln @@ -8,17 +8,27 @@ EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {913088F6-37C0-4195-80E9-548C7C5303CB}.Debug|Win32.ActiveCfg = Debug|Win32 {913088F6-37C0-4195-80E9-548C7C5303CB}.Debug|Win32.Build.0 = Debug|Win32 + {913088F6-37C0-4195-80E9-548C7C5303CB}.Debug|x64.ActiveCfg = Debug|x64 + {913088F6-37C0-4195-80E9-548C7C5303CB}.Debug|x64.Build.0 = Debug|x64 {913088F6-37C0-4195-80E9-548C7C5303CB}.Release|Win32.ActiveCfg = Release|Win32 {913088F6-37C0-4195-80E9-548C7C5303CB}.Release|Win32.Build.0 = Release|Win32 + {913088F6-37C0-4195-80E9-548C7C5303CB}.Release|x64.ActiveCfg = Release|x64 + {913088F6-37C0-4195-80E9-548C7C5303CB}.Release|x64.Build.0 = Release|x64 {F468F539-27BD-468E-BE64-DDE641400B51}.Debug|Win32.ActiveCfg = Debug|Win32 {F468F539-27BD-468E-BE64-DDE641400B51}.Debug|Win32.Build.0 = Debug|Win32 + {F468F539-27BD-468E-BE64-DDE641400B51}.Debug|x64.ActiveCfg = Debug|x64 + {F468F539-27BD-468E-BE64-DDE641400B51}.Debug|x64.Build.0 = Debug|x64 {F468F539-27BD-468E-BE64-DDE641400B51}.Release|Win32.ActiveCfg = Release|Win32 {F468F539-27BD-468E-BE64-DDE641400B51}.Release|Win32.Build.0 = Release|Win32 + {F468F539-27BD-468E-BE64-DDE641400B51}.Release|x64.ActiveCfg = Release|x64 + {F468F539-27BD-468E-BE64-DDE641400B51}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Makefile.am b/Makefile.am index 793980012..3406079c7 100644 --- a/Makefile.am +++ b/Makefile.am @@ -24,6 +24,21 @@ TESTS = $(check_PROGRAMS) pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = cpputest.pc +cmakemodulesdir = $(libdir)/CppUTest/cmake/Modules +cmakemodules_DATA = \ + cmake/Modules/CppUTestBuildTimeDiscoverTests.cmake + +cmakescriptsdir = $(libdir)/CppUTest/cmake/Scripts +cmakescripts_DATA = \ + cmake/Scripts/CppUTestBuildTimeDiscoverTests.cmake + +cmakedir = $(libdir)/CppUTest/cmake +cmake_DATA = \ + build/cmake_package_files/CppUTestConfig.cmake \ + build/cmake_package_files/CppUTestConfigVersion.cmake \ + build/cmake_package_files/CppUTestTargets-relwithdebinfo.cmake \ + build/cmake_package_files/CppUTestTargets.cmake + EXTRA_DIST = \ cpputest.pc.in \ $(ALL_FILES_IN_GIT) @@ -39,6 +54,7 @@ lib_libCppUTest_a_SOURCES = \ src/CppUTest/MemoryLeakDetector.cpp \ src/CppUTest/MemoryLeakWarningPlugin.cpp \ src/CppUTest/SimpleString.cpp \ + src/CppUTest/SimpleStringInternalCache.cpp \ src/CppUTest/SimpleMutex.cpp \ src/CppUTest/TeamCityTestOutput.cpp \ src/CppUTest/TestFailure.cpp \ @@ -61,12 +77,14 @@ include_cpputest_HEADERS = \ include/CppUTest/CppUTestConfig.h \ include/CppUTest/JUnitTestOutput.h \ include/CppUTest/MemoryLeakDetector.h \ + include/CppUTest/MemoryLeakDetectorForceInclude.h \ include/CppUTest/MemoryLeakDetectorMallocMacros.h \ include/CppUTest/MemoryLeakDetectorNewMacros.h \ include/CppUTest/MemoryLeakWarningPlugin.h \ include/CppUTest/PlatformSpecificFunctions.h \ include/CppUTest/PlatformSpecificFunctions_c.h \ include/CppUTest/SimpleString.h \ + include/CppUTest/SimpleStringInternalCache.h \ include/CppUTest/SimpleMutex.h \ include/CppUTest/StandardCLibrary.h \ include/CppUTest/TeamCityTestOutput.h \ @@ -90,6 +108,7 @@ lib_libCppUTestExt_a_CXXFLAGS = $(lib_libCppUTest_a_CXXFLAGS) lib_libCppUTestExt_a_SOURCES = \ src/CppUTestExt/CodeMemoryReportFormatter.cpp \ + src/CppUTestExt/GTest.cpp \ src/CppUTestExt/IEEE754ExceptionsPlugin.cpp \ src/CppUTestExt/MemoryReportAllocator.cpp \ src/CppUTestExt/MemoryReporterPlugin.cpp \ @@ -108,8 +127,10 @@ if INCLUDE_CPPUTEST_EXT include_cpputestextdir = $(includedir)/CppUTestExt include_cpputestext_HEADERS = \ + include/CppUTestExt/CodeMemoryReportFormatter.h \ include/CppUTestExt/GMock.h \ include/CppUTestExt/GTest.h \ + include/CppUTestExt/GTestSupport.h \ include/CppUTestExt/GTestConvertor.h \ include/CppUTestExt/IEEE754ExceptionsPlugin.h \ include/CppUTestExt/MemoryReportAllocator.h \ @@ -136,38 +157,41 @@ CppUTestTests_LDADD = lib/libCppUTest.a $(CPPUTEST_LDADD) CppUTestTests_LDFLAGS = $(AM_LDFLAGS) $(CPPUTEST_LDFLAGS) $(CPPUTEST_ADDITIONAL_LDFLAGS) CppUTestTests_SOURCES = \ - tests/AllocationInCFile.c \ - tests/AllocationInCppFile.cpp \ - tests/AllocLetTestFree.c \ - tests/AllocLetTestFreeTest.cpp \ - tests/AllTests.cpp \ - tests/CheatSheetTest.cpp \ - tests/CommandLineArgumentsTest.cpp \ - tests/CommandLineTestRunnerTest.cpp \ - tests/JUnitOutputTest.cpp \ - tests/MemoryLeakDetectorTest.cpp \ - tests/MemoryOperatorOverloadTest.cpp \ - tests/MemoryLeakWarningTest.cpp \ - tests/PluginTest.cpp \ - tests/PreprocessorTest.cpp \ - tests/SetPluginTest.cpp \ - tests/SimpleStringTest.cpp \ - tests/SimpleMutexTest.cpp \ - tests/TeamCityOutputTest.cpp \ - tests/TestFailureNaNTest.cpp \ - tests/TestFailureTest.cpp \ - tests/TestFilterTest.cpp \ - tests/TestHarness_cTest.cpp \ - tests/TestHarness_cTestCFile.c \ - tests/TestInstallerTest.cpp \ - tests/TestMemoryAllocatorTest.cpp \ - tests/TestOutputTest.cpp \ - tests/TestRegistryTest.cpp \ - tests/TestResultTest.cpp \ - tests/TestUTestMacro.cpp \ - tests/TestUTestStringMacro.cpp \ - tests/UtestTest.cpp \ - tests/UtestPlatformTest.cpp + tests/CppUTest/AllocationInCFile.c \ + tests/CppUTest/AllocationInCppFile.cpp \ + tests/CppUTest/AllocLetTestFree.c \ + tests/CppUTest/AllocLetTestFreeTest.cpp \ + tests/CppUTest/AllTests.cpp \ + tests/CppUTest/CheatSheetTest.cpp \ + tests/CppUTest/CompatabilityTests.cpp \ + tests/CppUTest/CommandLineArgumentsTest.cpp \ + tests/CppUTest/CommandLineTestRunnerTest.cpp \ + tests/CppUTest/DummyMemoryLeakDetector.cpp \ + tests/CppUTest/JUnitOutputTest.cpp \ + tests/CppUTest/MemoryLeakDetectorTest.cpp \ + tests/CppUTest/MemoryOperatorOverloadTest.cpp \ + tests/CppUTest/MemoryLeakWarningTest.cpp \ + tests/CppUTest/PluginTest.cpp \ + tests/CppUTest/PreprocessorTest.cpp \ + tests/CppUTest/SetPluginTest.cpp \ + tests/CppUTest/SimpleStringTest.cpp \ + tests/CppUTest/SimpleStringCacheTest.cpp \ + tests/CppUTest/SimpleMutexTest.cpp \ + tests/CppUTest/TeamCityOutputTest.cpp \ + tests/CppUTest/TestFailureNaNTest.cpp \ + tests/CppUTest/TestFailureTest.cpp \ + tests/CppUTest/TestFilterTest.cpp \ + tests/CppUTest/TestHarness_cTest.cpp \ + tests/CppUTest/TestHarness_cTestCFile.c \ + tests/CppUTest/TestInstallerTest.cpp \ + tests/CppUTest/TestMemoryAllocatorTest.cpp \ + tests/CppUTest/TestOutputTest.cpp \ + tests/CppUTest/TestRegistryTest.cpp \ + tests/CppUTest/TestResultTest.cpp \ + tests/CppUTest/TestUTestMacro.cpp \ + tests/CppUTest/TestUTestStringMacro.cpp \ + tests/CppUTest/UtestTest.cpp \ + tests/CppUTest/UtestPlatformTest.cpp CppUTestExtTests_CPPFLAGS = $(lib_libCppUTestExt_a_CPPFLAGS) CppUTestExtTests_CFLAGS = $(lib_libCppUTestExt_a_CFLAGS) @@ -203,7 +227,9 @@ CppUTestExtTests_SOURCES = \ tests/CppUTestExt/MockSupport_cTestCFile.c \ tests/CppUTestExt/MockStrictOrderTest.cpp \ tests/CppUTestExt/MockReturnValueTest.cpp \ - tests/CppUTestExt/OrderedTestTest.cpp + tests/CppUTestExt/OrderedTestTest.cpp \ + tests/CppUTestExt/OrderedTestTest_c.c \ + tests/CppUTestExt/MockFakeLongLong.cpp DISTCLEANFILES = \ filename.map.txt \ @@ -235,45 +261,104 @@ if INCLUDE_CPPUTEST_EXT ./$(CPPUTESTEXT_TESTS) endif + +cpputest_build_gtest112: + mkdir -p cpputest_build_gtest112 + cd cpputest_build_gtest112; \ + wget https://github.com/google/googletest/archive/refs/tags/release-1.12.1.zip -O gtest-1.12.1.zip && unzip gtest-1.12.1.zip; \ + cd googletest-release-1.12.1; cmake .; make + +cpputest_build_gtest111: + mkdir -p cpputest_build_gtest111 + cd cpputest_build_gtest111; \ + wget https://github.com/google/googletest/archive/refs/tags/release-1.11.0.zip -O gtest-1.11.0.zip && unzip gtest-1.11.0.zip; \ + cd googletest-release-1.11.0; cmake .; make + +cpputest_build_gtest110: + mkdir -p cpputest_build_gtest110 + cd cpputest_build_gtest110; \ + wget https://github.com/google/googletest/archive/refs/tags/release-1.10.0.zip -O gtest-1.10.0.zip && unzip gtest-1.10.0.zip; \ + cd googletest-release-1.10.0; cmake .; make + +cpputest_build_gtest18: + mkdir -p cpputest_build_gtest18 + cd cpputest_build_gtest18; \ + wget https://github.com/google/googletest/archive/release-1.8.0.zip -O gtest-1.8.0.zip && unzip gtest-1.8.0.zip; \ + cd googletest-release-1.8.0; cmake .; make + cpputest_build_gtest17: mkdir -p cpputest_build_gtest17 cd cpputest_build_gtest17; \ - wget https://googlemock.googlecode.com/files/gmock-1.7.0.zip && unzip gmock-1.7.0.zip - cd cpputest_build_gtest17/gmock-1.7.0; ./configure && make check + wget https://github.com/google/googletest/archive/release-1.7.0.zip -O gtest-1.7.0.zip && unzip gtest-1.7.0.zip; \ + wget https://github.com/google/googlemock/archive/release-1.7.0.zip -O gmock-1.7.0.zip && unzip gmock-1.7.0.zip; \ + mv googletest-release-1.7.0 googlemock-release-1.7.0/gtest; \ + cd googlemock-release-1.7.0; autoreconf -i; ./configure && make cpputest_build_gtest16: mkdir -p cpputest_build_gtest16 cd cpputest_build_gtest16; \ - wget https://googlemock.googlecode.com/files/gmock-1.6.0.zip && unzip gmock-1.6.0.zip - cd cpputest_build_gtest16/gmock-1.6.0; ./configure CXXFLAGS=-DGTEST_USE_OWN_TR1_TUPLE=1 && make check + wget https://github.com/google/googletest/archive/release-1.6.0.zip -O gtest-1.6.0.zip && unzip gtest-1.6.0.zip; \ + wget https://github.com/google/googlemock/archive/release-1.6.0.zip -O gmock-1.6.0.zip && unzip gmock-1.6.0.zip; \ + mv googletest-release-1.6.0 googlemock-release-1.6.0/gtest; \ + cd googlemock-release-1.6.0; autoreconf -i; ./configure CXXFLAGS=-DGTEST_USE_OWN_TR1_TUPLE=1 && make cpputest_build_gtest15: mkdir -p cpputest_build_gtest15 cd cpputest_build_gtest15; \ - wget https://googlemock.googlecode.com/files/gmock-1.5.0.zip && unzip gmock-1.5.0.zip - cd cpputest_build_gtest15/gmock-1.5.0; ./configure CXXFLAGS=-DGTEST_USE_OWN_TR1_TUPLE=1 && make + wget https://github.com/google/googletest/archive/release-1.5.0.zip -O gtest-1.5.0.zip && unzip gtest-1.5.0.zip; \ + wget https://github.com/google/googlemock/archive/release-1.5.0.zip -O gmock-1.5.0.zip && unzip gmock-1.5.0.zip; \ + mv googletest-release-1.5.0 googlemock-release-1.5.0/gtest; \ + cd googlemock-release-1.5.0; autoreconf -i; ./configure CXXFLAGS=-DGTEST_USE_OWN_TR1_TUPLE=1 && make check_gtest15: cpputest_build_gtest15 @echo "Build using gmock 1.5"; - export GMOCK_HOME=`pwd`/cpputest_build_gtest15/gmock-1.5.0; \ - make distclean; $(srcdir)/configure; make check + export GMOCK_HOME=`pwd`/cpputest_build_gtest15/googlemock-release-1.5.0; \ + make distclean; $(srcdir)/configure --enable-std-cpp98; make check check_gtest16: cpputest_build_gtest16 @echo "Build using gmock 1.6"; - export GMOCK_HOME=`pwd`/cpputest_build_gtest16/gmock-1.6.0; \ - make distclean; $(srcdir)/configure; make check + export GMOCK_HOME=`pwd`/cpputest_build_gtest16/googlemock-release-1.6.0; \ + make distclean; $(srcdir)/configure --enable-std-cpp98; make check check_gtest17: cpputest_build_gtest17 @echo "Build using gmock 1.7" - export GMOCK_HOME=`pwd`/cpputest_build_gtest17/gmock-1.7.0; \ - make distclean; $(srcdir)/configure; make check + export GMOCK_HOME=`pwd`/cpputest_build_gtest17/googlemock-release-1.7.0; \ + make distclean; $(srcdir)/configure --enable-std-cpp98; make check + +check_gtest18: cpputest_build_gtest18 + @echo "Build using gmock 1.8" + export GMOCK_HOME=`pwd`/cpputest_build_gtest18/googletest-release-1.8.0/googlemock; \ + export GTEST_HOME=`pwd`/cpputest_build_gtest18/googletest-release-1.8.0/googletest; \ + make distclean; $(srcdir)/configure --enable-std-cpp98; make check + +check_gtest110: cpputest_build_gtest110 + @echo "Build using gmock 1.10" + export GMOCK_MOCK=`pwd`/cpputest_build_gtest110/googletest-release-1.10.0; \ + export GTEST_HOME=`pwd`/cpputest_build_gtest110/googletest-release-1.10.0; \ + make distclean; $(srcdir)/configure --enable-std-cpp11; make check + +check_gtest111: cpputest_build_gtest111 + @echo "Build using gmock 1.11" + export GMOCK_MOCK=`pwd`/cpputest_build_gtest111/googletest-release-1.11.0; \ + export GTEST_HOME=`pwd`/cpputest_build_gtest111/googletest-release-1.11.0; \ + make distclean; $(srcdir)/configure --enable-std-cpp11; make check + +check_gtest112: cpputest_build_gtest112 + @echo "Build using gmock 1.12" + export GMOCK_MOCK=`pwd`/cpputest_build_gtest121/googletest-release-1.12.1; \ + export GTEST_HOME=`pwd`/cpputest_build_gtest121/googletest-release-1.12.1; \ + make distclean; $(srcdir)/configure --enable-std-cpp11; make check remove_gtest_directories: rm -rf cpputest_build_gtest15 rm -rf cpputest_build_gtest16 rm -rf cpputest_build_gtest17 + rm -rf cpputest_build_gtest18 + rm -rf cpputest_build_gtest110 + rm -rf cpputest_build_gtest111 + rm -rf cpputest_build_gtest112 -check_gtest: remove_gtest_directories check_gtest15 check_gtest16 check_gtest17 +check_gtest: remove_gtest_directories check_gtest15 check_gtest16 check_gtest17 check_gtest18 check_gtest110 check_gtest111 check_gtest112 check_basic: @echo "If dash is available, run the configure with dash to find bash-isms and increase portability" @@ -287,9 +372,21 @@ check_basic: @echo "Building without extensions" make distclean; $(srcdir)/configure --disable-extensions; make check + @echo "Building with the Std C++ 98 turned on. Compiler acts differently then." + make distclean; $(srcdir)/configure --enable-std-cpp98; make + @echo "Building with the Std C++ 11 turned on. Compiler acts differently then." make distclean; $(srcdir)/configure --enable-std-cpp11; make + @echo "Building with the Std C++ 14 turned on. Compiler acts differently then." + make distclean; $(srcdir)/configure --enable-std-cpp14; make + + @echo "Building with the Std C++ 17 turned on. Compiler acts differently then." + make distclean; $(srcdir)/configure --enable-std-cpp17; make + + @echo "Building with the Std C++ 20 turned on. Compiler acts differently then." + make distclean; $(srcdir)/configure --enable-std-cpp20; make + @echo "Building without the Standard C library" make distclean; $(srcdir)/configure --disable-std-c; make @@ -299,6 +396,9 @@ check_basic: @echo "Building without memory leak detection" make distclean; $(srcdir)/configure --disable-memory-leak-detection; make check + @echo "Building with address sanitizer" + make distclean; $(srcdir)/configure --enable-sanitize-address; make check + @echo "Building without memory leak detection and without Standard C++" make distclean; $(srcdir)/configure --disable-memory-leak-detection --disable-std-cpp; make check diff --git a/Makefile_using_MakefileWorker b/Makefile_using_MakefileWorker index a4b0a12b2..66ec53932 100644 --- a/Makefile_using_MakefileWorker +++ b/Makefile_using_MakefileWorker @@ -11,14 +11,15 @@ endif CPPUTEST_HOME = . OLD_MAKE = oldmake +MAKE_CMD = make -f $(CPPUTEST_HOME)/Makefile_using_MakefileWorker CPPUTEST_ENABLE_DEBUG = Y SRC_DIRS = \ src/CppUTest \ src/Platforms/$(CPP_PLATFORM) - + TEST_SRC_DIRS = \ - tests + tests/CppUTest INCLUDE_DIRS =\ include @@ -27,75 +28,119 @@ include $(CPPUTEST_HOME)/build/MakefileWorker.mk #these are a sample of the other alternative flag settings .PHONY: test_all -test_all: start test_old_make +test_all: start + $(MAKE_CMD) test_defaults + $(MAKE_CMD) test_disable_std_cpp + $(MAKE_CMD) test_disable_memory_leak_detection + $(MAKE_CMD) test_disable_std_cpp_and_leak_detection + $(MAKE_CMD) test_disable_debug + $(MAKE_CMD) test_override_flags + $(MAKE_CMD) test_disable_std_c + $(MAKE_CMD) test_target_platform + $(MAKE_CMD) test_override_and_disable + $(MAKE_CMD) test_examples + $(MAKE_CMD) test_junit_output + $(MAKE_CMD) test_gcov + $(MAKE_CMD) test_vpath + $(MAKE_CMD) test_vpath_install + +.PHONY: test_defaults +test_defaults: start @echo Building with the default flags. - make clean - $(TIME) make + $(MAKE_CMD) clean + $(TIME) $(MAKE_CMD) ./$(TEST_TARGET) -r - make clean - @echo Building with the STDC++ new disabled. - $(TIME) make CPPUTEST_USE_STD_CPP_LIB=Y extensions - make CPPUTEST_USE_STD_CPP_LIB=Y cleanExtensions + $(MAKE_CMD) clean + +.PHONY: test_disable_std_cpp +test_disable_std_cpp: start + @echo Building with the STDC++ new disabled. + $(TIME) $(MAKE_CMD) CPPUTEST_USE_STD_CPP_LIB=N extensions + $(MAKE_CMD) CPPUTEST_USE_STD_CPP_LIB=N cleanExtensions + +.PHONY: test_disable_memory_leak_detection +test_disable_memory_leak_detection: start @echo Building with Memory Leak Detection disabled - $(TIME) make CPPUTEST_USE_MEM_LEAK_DETECTION=N extensions - make CPPUTEST_USE_MEM_LEAK_DETECTION=N cleanExtensions + $(TIME) $(MAKE_CMD) CPPUTEST_USE_MEM_LEAK_DETECTION=N extensions + $(MAKE_CMD) CPPUTEST_USE_MEM_LEAK_DETECTION=N cleanExtensions + +.PHONY: test_disable_std_cpp_and_leak_detection +test_disable_std_cpp_and_leak_detection: start @echo Building with Memory Leak Detection disabled and STD C++ disabled - $(TIME) make CPPUTEST_USE_MEM_LEAK_DETECTION=N CPPUTEST_USE_STD_CPP_LIB=Y extensions - make CPPUTEST_USE_MEM_LEAK_DETECTION=N CPPUTEST_USE_STD_CPP_LIB=Y cleanExtensions + $(TIME) $(MAKE_CMD) CPPUTEST_USE_MEM_LEAK_DETECTION=N CPPUTEST_USE_STD_CPP_LIB=Y extensions + $(MAKE_CMD) CPPUTEST_USE_MEM_LEAK_DETECTION=N CPPUTEST_USE_STD_CPP_LIB=Y cleanExtensions + +.PHONY: test_disable_debug +test_disable_debug: start @echo Building with debug disabled - $(TIME) make CPPUTEST_ENABLE_DEBUG=N extensions - make CPPUTEST_ENABLE_DEBUG=N cleanExtensions + $(TIME) $(MAKE_CMD) CPPUTEST_ENABLE_DEBUG=N extensions + $(MAKE_CMD) CPPUTEST_ENABLE_DEBUG=N cleanExtensions + +.PHONY: test_override_flags +test_override_flags: start @echo Building with overridden CXXFLAGS and CFLAGS and CPPFLAGS - $(TIME) make CLFAGS="" CXXFLAGS="" CPPFLAGS="-Iinclude" - make CFLAGS="" CXXFLAGS="" clean + $(TIME) $(MAKE_CMD) CFLAGS="" CXXFLAGS="" CPPFLAGS="-Iinclude" + $(MAKE_CMD) CFLAGS="" CXXFLAGS="" clean + +.PHONY: test_disable_std_c +test_disable_std_c: start @echo Building without Standard C library includes - $(TIME) make CPPUTEST_USE_STD_C_LIB=N all_no_tests - make CPPUTEST_USE_STD_C_LIB=N clean + $(TIME) $(MAKE_CMD) CPPUTEST_USE_STD_C_LIB=N CPPUTEST_ADDITIONAL_CPPFLAGS="-DCPPUTEST_CHAR_BIT=8" all_no_tests + $(MAKE_CMD) CPPUTEST_USE_STD_C_LIB=N clean + +.PHONY: test_target_platform +test_target_platform: start @echo Building with a different TARGET_PLATFORM - make TARGET_PLATFORM=real_platform + $(MAKE_CMD) TARGET_PLATFORM=real_platform + +.PHONY: test_override_and_disable +test_override_and_disable: start @echo Building with overridden CXXFLAGS and CFLAGS and memory leak and STDC++ disabled - $(TIME) make CLFAGS="" CXXFLAGS="" CPPFLAGS="-Iinclude -DCPPUTEST_STD_CPP_LIB_DISABLED -DCPPUTEST_MEM_LEAK_DETECTION_DISABLED" - make CFLAGS="" CXXFLAGS="" CPPFLAGS="-DCPPUTEST_STD_CPP_LIB_DISABLED -DCPPUTEST_MEM_LEAK_DETECTION_DISABLED" clean - @echo Building examples - make cleanExamples - $(TIME) make examples - make cleanExamples + $(TIME) $(MAKE_CMD) CFLAGS="" CXXFLAGS="" CPPFLAGS="-Iinclude -DCPPUTEST_STD_CPP_LIB_DISABLED -DCPPUTEST_MEM_LEAK_DETECTION_DISABLED" + $(MAKE_CMD) CFLAGS="" CXXFLAGS="" CPPFLAGS="-DCPPUTEST_STD_CPP_LIB_DISABLED -DCPPUTEST_MEM_LEAK_DETECTION_DISABLED" clean + +.PHONY: test_examples +test_examples: start + @echo Building examples + $(MAKE_CMD) cleanExamples + $(TIME) $(MAKE_CMD) examples + $(MAKE_CMD) cleanExamples + +.PHONY: test_junit_output +test_junit_output: start @echo Testing JUnit output - $(TIME) make + $(TIME) $(MAKE_CMD) $(SILENCE)./$(TEST_TARGET) -ojunit > junit_run_output $(SILENCE)if [ -s junit_run_output ]; then echo "JUnit run has output. Build failed!"; exit 1; fi - make clean - make CPPUTEST_MAP_FILE=map.txt - make clean + $(MAKE_CMD) clean + $(MAKE_CMD) CPPUTEST_MAP_FILE=map.txt + $(MAKE_CMD) clean + +.PHONY: test_gcov +test_gcov: start @echo Testing GCOV usage - $(TIME) make CPPUTEST_USE_GCOV=Y everythingInstall - make gcov - make -f Makefile_CppUTestExt gcov - make -C examples gcov - make cleanEverythingInstall + $(TIME) $(MAKE_CMD) CPPUTEST_USE_GCOV=Y everythingInstall + $(MAKE_CMD) gcov + $(MAKE) -f Makefile_CppUTestExt gcov + $(MAKE) -C examples gcov + $(MAKE_CMD) cleanEverythingInstall + +.PHONY: test_vpath +test_vpath: start @echo Testing VPATH usage - $(TIME) make CPPUTEST_USE_GCOV=Y CPPUTEST_USE_VPATH=Y everythingInstall - make CPPUTEST_USE_VPATH=Y gcov - make CPPUTEST_USE_VPATH=Y -f Makefile_CppUTestExt gcov - make CPPUTEST_USE_VPATH=Y -C examples gcov - make clean cleanExamples + $(TIME) $(MAKE_CMD) CPPUTEST_USE_GCOV=Y CPPUTEST_USE_VPATH=Y everythingInstall + $(MAKE_CMD) CPPUTEST_USE_VPATH=Y gcov + $(MAKE) CPPUTEST_USE_VPATH=Y -f Makefile_CppUTestExt gcov + $(MAKE) CPPUTEST_USE_VPATH=Y -C examples gcov + $(MAKE_CMD) clean cleanExamples + +.PHONY: test_vpath_install +test_vpath_install: start @echo Testing VPATH usage - $(TIME) make CPPUTEST_USE_VPATH=Y everythingInstall - make CPPUTEST_USE_VPATH=Y cleanEverythingInstall - make flags - make debug - -HAS_OLD_MAKE = $(shell $(OLD_MAKE) -v 2>/dev/null) - -test_old_make: - $(SILENCE)if [ "$(HAS_OLD_MAKE)" = "" ]; then \ - echo "Old make with the name $(OLD_MAKE) not found. Skipping testing with old make version"; \ - else \ - $(OLD_MAKE) -f Makefile_for_old_make clean && \ - $(OLD_MAKE) -f Makefile_for_old_make && \ - $(OLD_MAKE) -f Makefile_for_old_make extensions && \ - $(OLD_MAKE) -f Makefile_for_old_make clean; \ - fi + $(TIME) $(MAKE_CMD) CPPUTEST_USE_VPATH=Y everythingInstall + $(MAKE_CMD) CPPUTEST_USE_VPATH=Y cleanEverythingInstall + $(MAKE_CMD) flags + $(MAKE_CMD) debug .PHONY: examples examples: $(TEST_TARGET) extensions diff --git a/README.md b/README.md index f49c4bcdc..163ea219c 100644 --- a/README.md +++ b/README.md @@ -1,50 +1,58 @@ -CppUTest -======== +# CppUTest -CppUTest unit testing and mocking framework for C/C++ - -[More information on the project page](http://cpputest.github.com) +[![GitHub Actions](https://github.com/cpputest/cpputest/actions/workflows/basic.yml/badge.svg)](https://github.com/cpputest/cpputest/actions/workflows/basic.yml) +[![AppveyorBuild status](https://ci.appveyor.com/api/projects/status/irh38i4wblsb5tew?svg=true)](https://ci.appveyor.com/project/basvodde/cpputest) +[![Coverage Status](https://coveralls.io/repos/cpputest/cpputest/badge.svg?branch=master&service=github)](https://coveralls.io/github/cpputest/cpputest?branch=master) +[![ConanCenter package](https://repology.org/badge/version-for-repo/conancenter/cpputest.svg)](https://conan.io/center/cpputest) -Travis Linux build status: -[![Build Status](https://travis-ci.org/cpputest/cpputest.png?branch=master)](https://travis-ci.org/cpputest/cpputest) +CppUTest unit testing and mocking framework for C/C++ -AppVeyor Windows build status: -[![Build status](https://ci.appveyor.com/api/projects/status/irh38i4wblsb5tew?svg=true)](https://ci.appveyor.com/project/basvodde/cpputest) +[More information on the project page](https://cpputest.github.io) -Coverage: -[![Coverage Status](https://coveralls.io/repos/cpputest/cpputest/badge.svg?branch=master&service=github)](https://coveralls.io/github/cpputest/cpputest?branch=master) +Slack channel: +[Join if link not expired](https://join.slack.com/t/cpputest/shared_invite/zt-epq97u9h-6yBQHHl2cvUADjEENtdASw) ## Getting Started You'll need to do the following to get started: -Building from source (unix-based, cygwin, MacOSX): +Building from source (Unix-based, Cygwin, MacOS): + +```bash +git clone https://github.com/cpputest/cpputest.git +cd cpputest +mkdir cpputest_build +cd cpputest_build +autoreconf .. -i +../configure +make +``` -* Download latest version -* autogen.sh -* configure -* make -* make check -* You can use "make install" if you want to install CppUTest system-wide +You can use `make install` if you want to install CppUTest system-wide. You can also use CMake, which also works for Windows Visual Studio. -* Download latest version -* cmake CMakeList.txt -* make +```bash +git clone https://github.com/cpputest/cpputest.git +cd cpputest +mkdir cpputest_build +cmake -B cpputest_build +cmake --build cpputest_build +``` Then to get started, you'll need to do the following: + * Add the include path to the Makefile. Something like: - * CPPFLAGS += -I(CPPUTEST_HOME)/include + * `CPPFLAGS += -I$(CPPUTEST_HOME)/include` * Add the memory leak macros to your Makefile (needed for additional debug info!). Something like: - * CXXFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorNewMacros.h - * CFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorMallocMacros.h + * `CXXFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorNewMacros.h` + * `CFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorMallocMacros.h` * Add the library linking to your Makefile. Something like: - * LD_LIBRARIES = -L$(CPPUTEST_HOME)/lib -lCppUTest -lCppUTestExt + * `LD_LIBRARIES = -L$(CPPUTEST_HOME)/lib -lCppUTest -lCppUTestExt` After this, you can write your first test: -```C++ +```cpp TEST_GROUP(FirstTestGroup) { }; @@ -55,49 +63,58 @@ TEST(FirstTestGroup, FirstTest) } ``` +You can build and install cpputest using [vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager: + +```console +$ vcpkg install cpputest (More information: https://github.com/microsoft/vcpkg) +``` + ## Command line switches -* -v verbose, print each test name as it runs -* -r# repeat the tests some number of times, default is one, default if # is not specified is 2. This is handy if you are experiencing memory leaks related to statics and caches. -* -g group only run test whose group contains the substring group -* -n name only run test whose name contains the substring name +* `-h` help, shows the latest help, including the parameters we've implemented after updating this README page. +* `-v` verbose, print each test name as it runs +* `-r#` repeat the tests some number of times, default is one, default if # is not specified is 2. This is handy if you are experiencing memory leaks related to statics and caches. +* `-s#` random shuffle the test execution order. # is an integer used for seeding the random number generator. # is optional, and if omitted, the seed value is chosen automatically, which results in a different order every time. The seed value is printed to console to make it possible to reproduce a previously generated execution order. Handy for detecting problems related to dependencies between tests. +* `-g` group only run test whose group contains the substring group +* `-n` name only run test whose name contains the substring name +* `-f` crash on fail, run the tests as normal but, when a test fails, crash rather than report the failure in the normal way ## Test Macros -* TEST(group, name) - define a test -* IGNORE_TEST(group, name) - turn off the execution of a test -* TEST_GROUP(group) - Declare a test group to which certain tests belong. This will also create the link needed from another library. -* TEST_GROUP_BASE(group, base) - Same as TEST_GROUP, just use a different base class than Utest -* TEST_SETUP() - Declare a void setup method in a TEST_GROUP - this is the same as declaring void setup() -* TEST_TEARDOWN() - Declare a void setup method in a TEST_GROUP -* IMPORT_TEST_GROUP(group) - Export the name of a test group so it can be linked in from a library. Needs to be done in main. +* `TEST(group, name)` - define a test +* `IGNORE_TEST(group, name)` - turn off the execution of a test +* `TEST_GROUP(group)` - Declare a test group to which certain tests belong. This will also create the link needed from another library. +* `TEST_GROUP_BASE(group, base)` - Same as `TEST_GROUP`, just use a different base class than Utest +* `TEST_SETUP()` - Declare a void setup method in a `TEST_GROUP` - this is the same as declaring void `setup()` +* `TEST_TEARDOWN()` - Declare a void setup method in a `TEST_GROUP` +* `IMPORT_TEST_GROUP(group)` - Export the name of a test group so it can be linked in from a library. Needs to be done in `main`. ## Set up and tear down support -* Each TEST_GROUP may contain a setup and/or a teardown method. -* setup() is called prior to each TEST body and teardown() is called after the test body. +* Each `TEST_GROUP` may contain a `setup` and/or a `teardown` method. +* `setup()` is called prior to each `TEST` body and `teardown()` is called after the test body. ## Assertion Macros The failure of one of these macros causes the current test to immediately exit -* CHECK(boolean condition) - checks any boolean result -* CHECK_TRUE(boolean condition) - checks for true -* CHECK_FALSE(boolean condition) - checks for false -* CHECK_EQUAL(expected, actual) - checks for equality between entities using ==. So if you have a class that supports operator==() you can use this macro to compare two instances. -* STRCMP_EQUAL(expected, actual) - check const char* strings for equality using strcmp -* LONGS_EQUAL(expected, actual) - Compares two numbers -* BYTES_EQUAL(expected, actual) - Compares two numbers, eight bits wide -* POINTERS_EQUAL(expected, actual) - Compares two const void * -* DOUBLES_EQUAL(expected, actual, tolerance) - Compares two doubles within some tolerance -* FAIL(text) - always fails -* TEST_EXIT - Exit the test without failure - useful for contract testing (implementing an assert fake) +* `CHECK(boolean condition)` - checks any boolean result +* `CHECK_TRUE(boolean condition)` - checks for true +* `CHECK_FALSE(boolean condition)` - checks for false +* `CHECK_EQUAL(expected, actual)` - checks for equality between entities using `==`. So if you have a class that supports `operator==()` you can use this macro to compare two instances. +* `STRCMP_EQUAL(expected, actual)` - check const `char*` strings for equality using `strcmp` +* `LONGS_EQUAL(expected, actual)` - Compares two numbers +* `BYTES_EQUAL(expected, actual)` - Compares two numbers, eight bits wide +* `POINTERS_EQUAL(expected, actual)` - Compares two `const void *` +* `DOUBLES_EQUAL(expected, actual, tolerance)` - Compares two doubles within some tolerance +* `ENUMS_EQUAL_INT(excepted, actual)` - Compares two enums which their underlying type is `int` +* `ENUMS_EQUAL_TYPE(underlying_type, excepted, actual)` - Compares two enums which they have the same underlying type +* `FAIL(text)` - always fails +* `TEST_EXIT` - Exit the test without failure - useful for contract testing (implementing an assert fake) +Customize `CHECK_EQUAL` to work with your types that support `operator==()` -Customize CHECK_EQUAL to work with your types that support operator==() - -* Create the function: -** SimpleString StringFrom (const yourType&) +- Create the function: `SimpleString StringFrom(const yourType&)` The Extensions directory has a few of these. @@ -110,7 +127,7 @@ The Extensions directory has a few of these. Example of a main with a TestPlugin: -```C++ +```cpp int main(int ac, char** av) { LogPlugin logPlugin; @@ -126,19 +143,19 @@ Memory leak detection * A platform specific memory leak detection mechanism is provided. * If a test fails and has allocated memory prior to the fail and that memory is not cleaned up by TearDown, a memory leak is reported. It is best to only chase memory leaks when other errors have been eliminated. -* Some code uses lazy initialization and appears to leak when it really does not (for example: gcc stringstream used to in an earlier release). One cause is that some standard library calls allocate something and do not free it until after main (or never). - To find out if a memory leak is due to lazy initialization set the -r switch to run tests twice. The signature of this situation is that the first run shows leaks and the second run shows no leaks. When both runs show leaks, you have a leak to find. +* Some code uses lazy initialization and appears to leak when it really does not (for example: gcc stringstream used to in an earlier release). One cause is that some standard library calls allocate something and do not free it until after `main` (or never). + To find out if a memory leak is due to lazy initialization set the `-r` switch to run tests twice. The signature of this situation is that the first run shows leaks and the second run shows no leaks. When both runs show leaks, you have a leak to find. ## How is memory leak detection implemented? -* Before setup() a memory usage checkpoint is recorded -* After teardown() another checkpoint is taken and compared to the original checkpoint +* Before `setup()` a memory usage checkpoint is recorded +* After `teardown()` another checkpoint is taken and compared to the original checkpoint * In Visual Studio the MS debug heap capabilities are used -* For GCC a simple new/delete count is used in overridden operators new, new[], delete and delete[] +* For GCC a simple new/delete count is used in overridden operators `new`, `new[]`, `delete` and `delete[]` If you use some leaky code that you can't or won't fix you can tell a TEST to ignore a certain number of leaks as in this example: -```C++ +```cpp TEST(MemoryLeakWarningTest, Ignore1) { EXPECT_N_LEAKS(1); @@ -148,20 +165,18 @@ TEST(MemoryLeakWarningTest, Ignore1) ## Example Main -```C++ +```cpp #include "CppUTest/CommandLineTestRunner.h" int main(int ac, char** av) { - return CommandLineTestRunner::RunAllTests(ac, av); + return RUN_ALL_TESTS(ac, av); } - -IMPORT_TEST_GROUP(ClassName) ``` ## Example Test -```C++ +```cpp #include "CppUTest/TestHarness.h" #include "ClassName.h" @@ -177,7 +192,7 @@ TEST_GROUP(ClassName) { delete className; } -} +}; TEST(ClassName, Create) { @@ -192,8 +207,58 @@ TEST(ClassName, Create) ``` There are some scripts that are helpful in creating your initial h, cpp, and -Test files. See scripts/README.TXT +Test files. See scripts/README.TXT +## Conan +CppUTest is available through [conan-center][conan-center]. +##### conanfile.txt + +```ini +[requires] +cpputest/4.0 + +[generators] +cmake_find_package +cmake_paths +``` + +##### CMake + +```cmake +find_package(CppUTest REQUIRED) + +add_executable(example_test ExampleTest.cpp) + +target_link_libraries(example_test PRIVATE + CppUTest::CppUTest + CppUTest::CppUTestExt) +``` + +## Integration as external CMake project + +Sometimes you want to use CppUTest in your project without installing it to your system or for having control over the version you are using. This little snippet get the wanted version from GitHub and builds it as a library. + +```cmake +# CppUTest +include(FetchContent) +FetchContent_Declare( + CppUTest + GIT_REPOSITORY https://github.com/cpputest/cpputest.git + GIT_TAG master # or use release tag, eg. v4.0 +) +FetchContent_MakeAvailable(CppUTest) +``` + +It can be used then like so: + +```cmake +add_executable(example_test UnitTest1.cpp UnitTest2.cpp) + +target_link_libraries(example_test PRIVATE + CppUTest::CppUTest + CppUTest::CppUTestExt) +``` +[conan-center]: https://conan.io/center/cpputest diff --git a/README_CppUTest_for_C.txt b/README_CppUTest_for_C.txt index 578c348e8..8674364ce 100644 --- a/README_CppUTest_for_C.txt +++ b/README_CppUTest_for_C.txt @@ -7,10 +7,9 @@ common problems to solve. ---++ Using extern "C" When including C-header files or when declaring C-variables and routines -in a .cpp file, you'll have to surround them with an extern "C". This is -because the C++ linker works different than the C linker and you need to -instruct the compiler about this. If you do NOT do this, you will probably -get a linker error, like unresolved symbols, for a routine that you did +in a .cpp file, you'll need to enclose them within an extern "C". This is +because the C++ linker works differently than the C linker and you need to +instruct the compiler about this else you may encounter a linker error. Like unresolved symbols for a routine that you did implement. An example: @@ -25,10 +24,10 @@ extern "C" { CppUTest comes with a file called TestHarness_c.h which contains a couple of routines that can be used in C code, like C-versions of the CHECK-macro's. -The file also contains malloc and free routines that can be used for using +The file also contains malloc and free routines that can be used for accessing the CppUTest memory leak detector. These routines should be used instead of the normal malloc/free. This can be achieved by #defining them somewhere, for -examples as a compiler option: -Dmalloc=cpputest_malloc. +example as a compiler option: -Dmalloc=cpputest_malloc. It's important to remember that TestHarness_c.h is a C-header file. It can be used in C code, but when using in C++ code, you need to use extern "C" before diff --git a/README_InstallCppUTest.txt b/README_InstallCppUTest.txt index ebe0f9efa..bb67cc2a8 100644 --- a/README_InstallCppUTest.txt +++ b/README_InstallCppUTest.txt @@ -1,10 +1,10 @@ 1. Unzip into , resulting in - /CppUTest/ + /CppUTest/ + + MAKE SURE DOES NOT HAVE SPACES IN IT + MAKE SURE DOES NOT HAVE SPACES IN IT + MAKE SURE DOES NOT HAVE SPACES IN IT - MAKE SURE DOES NOT HAVE SPACES IN IT - MAKE SURE DOES NOT HAVE SPACES IN IT - MAKE SURE DOES NOT HAVE SPACES IN IT - 2. Build CppUTest and examples 2a. For unix/gcc (including cygwin) @@ -12,59 +12,49 @@ > ../configure > make > make tdd # This is to run the CppUTest unit tests - + 2b. For Microsoft Visual C++ V6 - Double click /CppUTest/CppUTest.dsw - Run without debugging, see the test results in the command window - Exit MS Visual C++ - - To run the examples: - Double click /CppUTest/example/CppUTestExample.dsw - Run without debugging, see the test results in the command window - You should define the environment variable CPP_U_TEST to point to CppUTest - to run these. - - NOTE: To create your own project, you need to have CppUTest and your project - compiled with the same compile and link settings + We couldn't install the compiler anymore. We removed the project files. + You will need to make your own 2c. For ARMCC from Keil MDK-ARM (building CppUTest library only) > make all -C platforms/armcc Please see README and Makefile in platforms/armcc to adjust options, default CPU architecture is ARM7TDMI and default CPU execution mode is THUMB. - + 3c. For Microsoft Visual Studio 2008 Double click /CppUTest/CppUTest.sln - + If Visual studio reports that the solution file was created with a newer version of Visual Studio, then try 3d - + Then press control-F5 to "Start without debugging" - + See CppUTest build and run its tests. - + 3d. For Older Microsoft Visual Studio .NET Double click /CppUTest/CppUTest.dsw Allow VS.NET to convert the files by clicking "yes to all" Run without debugging, see the test results in the command window Exit MS VS.NET - + Allow VS.NET to convert the files by clicking "yes to all" Run without debugging, see the test results in the command window - - NOTE: To create your own project, you need to have CppUTest and your project + + NOTE: To create your own project, you need to have CppUTest and your project compiled with the same compile and link settings - -4. to setup the support scripts. These scripts work in various unix systems + +4. to setup the support scripts. These scripts work in various unix systems and cygwin. (these are quite handy) If you are using windows install some tool like cygwin, msys or MKSToolkit to run these scripts. > cd /CppUTest > ./scripts/InstallScripts.sh -This command adds some symbolic links to /usr/local/bin, so you have +This command adds some symbolic links to /usr/local/bin, so you have to run it as root. sudo ./InstallScripts.sh - + MSYS - http://www.mingw.org/msys.shtml CYGWIN - http://www.cygwin.com/ MKSToolkit - http://mkstoolkit.com/ diff --git a/README_UsersOfPriorVersions.txt b/README_UsersOfPriorVersions.txt deleted file mode 100644 index 8fbb2ba7e..000000000 --- a/README_UsersOfPriorVersions.txt +++ /dev/null @@ -1,27 +0,0 @@ -If you were a user of CppTestTools you will have a few changes to make. - -CppUTest is the unit test harness from CppTestTools -CppFit is the FIT implementaions from CppTestTools - (CppFit is a separate download) - -Sorry, this is not a complete set of instructions for converting, but -here are some suggestions. - -In each test file - change namespace for SetUp and TearDown to TEST_GROUP(GroupName) - (GroupName is the class name by convention) - delete IMPORT_TEST_GROUP - (TEST_GROUP has this built in now) - #include "UnitTestHarness/somefile.h" should be - #include "CppUTest/somefile.h" - -Your Makefiles have to change: - Change DOTO to OBJS - Replace CPP_TEST_TOOLS with CPP_U_TEST - Replace MakefileHelpers with build - Change -I$(CPP_TEST_TOOLS) to -I$(CPP_U_TEST)/include\ - For libraries using fixtures add -I$(CPP_FIT)/include - Add the RunAllTests.sh script to your AllTests directory - - - \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml index 3e2426f83..6ed3b31b8 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -2,6 +2,12 @@ version: 3.7.0-ci{build} image: Visual Studio 2015 +cache: + - C:\ProgramData\chocolatey\bin -> appveyor.yml + - C:\ProgramData\chocolatey\lib -> appveyor.yml + - C:\Tools\MinGW32 -> appveyor.yml + - C:\Tools\MinGW64 -> appveyor.yml + environment: Configuration: Release matrix: @@ -14,15 +20,25 @@ environment: PlatformToolset: 5.3.0 - Platform: MinGW64 PlatformToolset: 5.3.0 + - Platform: MinGWClang64 + PlatformToolset: 5.3.0 + - Platform: MinGWClang32 + PlatformToolset: 5.3.0 - Platform: Win32 PlatformToolset: v90 - Platform: Win32 PlatformToolset: v100 - Platform: Win32 + PlatformToolset: v110 + - Platform: Win32 + PlatformToolset: v120 + - Platform: Win32 + PlatformToolset: v140 + - Platform: x64 PlatformToolset: v140 install: -- ps: if ($env:Platform -like 'MinGW*') { choco install mingw --version $env:PlatformToolset $( if ($env:Platform -like '*32') { Write-Output -forcex86 } ) | Out-Null } +- ps: if ($env:Platform -like 'MinGW*') { choco install mingw --version $env:PlatformToolset $( if ($env:Platform -like '*32') { Write-Output --forcex86 --params /exception:dwarf } ) } build_script: - ps: scripts\appveyor_ci_build.ps1 diff --git a/build/MakefileWorker.mk b/build/MakefileWorker.mk index bd054ad4d..46852df8d 100644 --- a/build/MakefileWorker.mk +++ b/build/MakefileWorker.mk @@ -24,6 +24,8 @@ # These do not go in a library. They are explicitly included in the test runner # MOCKS_SRC_DIRS - Directories containing mock source files to build into the test runner # These do not go in a library. They are explicitly included in the test runner +# MOCKS_SRC_FILES - Specific mock source files to build into the unit test runner +# These do not go in a library. They are explicitly included in the test runner #---------- # You can adjust these variables to influence how to build the test target # and where to put and name outputs @@ -46,6 +48,7 @@ # of the test harness # CPPUTEST_USE_GCOV - Turn on coverage analysis # Clean then build with this flag set to Y, then 'make gcov' +# CPPUTEST_USE_GCOV_NO_GCNO_FILES - Disable gcov's .gcno files from being generated # CPPUTEST_MAPFILE - generate a map file # CPPUTEST_WARNINGFLAGS - overly picky by default # OTHER_MAKEFILE_TO_INCLUDE - a hook to use this makefile to make @@ -62,6 +65,8 @@ # CPPUTEST_CPPFLAGS - flags for the C++ AND C preprocessor # CPPUTEST_CFLAGS - flags for the C complier # CPPUTEST_LDFLAGS - Linker flags +# CPPUTEST_CXX_PREFIX - prefix for the C++ compiler +# CPPUTEST_CC_PREFIX - prefix for the C compiler #---------- # Some behavior is weird on some platforms. Need to discover the platform. @@ -73,14 +78,14 @@ MINGW_STR = MINGW CYGWIN_STR = CYGWIN LINUX_STR = Linux SUNOS_STR = SunOS -UNKNWOWN_OS_STR = Unknown +UNKNOWN_OS_STR = Unknown # Compilers CC_VERSION_OUTPUT ="$(shell $(CXX) -v 2>&1)" CLANG_STR = clang SUNSTUDIO_CXX_STR = SunStudio -UNAME_OS = $(UNKNWOWN_OS_STR) +UNAME_OS = $(UNKNOWN_OS_STR) ifeq ($(findstring $(MINGW_STR),$(UNAME_OUTPUT)),$(MINGW_STR)) UNAME_OS = $(MINGW_STR) @@ -170,6 +175,11 @@ ifndef CPPUTEST_USE_GCOV CPPUTEST_USE_GCOV = N endif +# Skip generating gcov's .gcno files, off by default +ifndef CPPUTEST_USE_GCOV_NO_GCNO_FILES + CPPUTEST_USE_GCOV_NO_GCNO_FILES = N +endif + ifndef CPPUTEST_PEDANTIC_ERRORS CPPUTEST_PEDANTIC_ERRORS = Y endif @@ -192,18 +202,38 @@ ifeq ($(COMPILER_NAME),$(CLANG_STR)) # -Wno-disabled-macro-expansion -> Have to disable the macro expansion warning as the operator new overload warns on that. # -Wno-padded -> I sort-of like this warning but if there is a bool at the end of the class, it seems impossible to remove it! (except by making padding explicit) # -Wno-global-constructors Wno-exit-time-destructors -> Great warnings, but in CppUTest it is impossible to avoid as the automatic test registration depends on the global ctor and dtor -# -Wno-weak-vtables -> The TEST_GROUP macro declares a class and will automatically inline its methods. Thats ok as they are only in one translation unit. Unfortunately, the warning can't detect that, so it must be disabled. +# -Wno-weak-vtables -> The TEST_GROUP macro declares a class and will automatically inline its methods. That's ok as they are only in one translation unit. Unfortunately, the warning can't detect that, so it must be disabled. # -Wno-old-style-casts -> We only use old style casts by decision # -Wno-c++11-long-long -> When it detects long long, then we can use it and no need for a warning about that - CPPUTEST_CXX_WARNINGFLAGS += -Weverything -Wno-disabled-macro-expansion -Wno-padded -Wno-global-constructors -Wno-exit-time-destructors -Wno-weak-vtables -Wno-old-style-cast -Wno-c++11-long-long - CPPUTEST_C_WARNINGFLAGS += -Weverything -Wno-padded +# -Wno-c++98-compat-pedantic -> Incompatibilities with C++98, these are happening through #define. + CPPUTEST_CXX_WARNINGFLAGS += -Wno-disabled-macro-expansion -Wno-padded -Wno-global-constructors -Wno-exit-time-destructors -Wno-weak-vtables -Wno-old-style-cast -Wno-c++11-long-long -Wno-c++98-compat-pedantic -Wreserved-id-macro + CPPUTEST_C_WARNINGFLAGS += -Wno-padded -Wreserved-id-macro -# Clang "7" (Xcode 7 command-line tools) introduced new warnings by default that don't exist on previous versions of clang and cause errors when present. -ifeq ($(findstring clang-7,$(CC_VERSION_OUTPUT)),clang-7) -# -Wno-reserved-id-macro -> Many CppUTest macros start with __, which is a reserved namespace -# -Wno-keyword-macro -> CppUTest redefines the 'new' keyword for memory leak tracking - CPPUTEST_CXX_WARNINGFLAGS += -Wno-reserved-id-macro -Wno-keyword-macro - CPPUTEST_C_WARNINGFLAGS += -Wno-reserved-id-macro -Wno-keyword-macro +# Clang 7 and 12 introduced new warnings by default that don't exist on previous versions of clang and cause errors when present. +CLANG_VERSION := $(shell echo $(CC_VERSION_OUTPUT) | sed -n 's/.* \([0-9]*\.[0-9]*\.[0-9]*\).*/\1/p') +CLANG_VERSION_NUM := $(subst .,,$(CLANG_VERSION)) +CLANG_VERSION_NUM_GT_700 := $(shell [ "$(CLANG_VERSION_NUM)" -ge 700 ] && echo Y || echo N) +CLANG_VERSION_NUM_GT_1200 := $(shell [ "$(CLANG_VERSION_NUM)" -ge 1200 ] && echo Y || echo N) +CLANG_VERSION_NUM_GT_1205 := $(shell [ "$(CLANG_VERSION_NUM)" -ge 1205 ] && echo Y || echo N) + +ifeq ($(CLANG_VERSION_NUM_GT_700), Y) + CPPUTEST_CXX_WARNINGFLAGS += -Wkeyword-macro + CPPUTEST_C_WARNINGFLAGS += -Wkeyword-macro +endif + +ifeq ($(UNAME_OS),$(MACOSX_STR)) +#apple clang has some special behavior +ifeq ($(CLANG_VERSION_NUM_GT_1200), Y) +# -Wno-poison-system-directories -> Apparently apple clang thinks everything is a cross compile, making this useless + CPPUTEST_CXX_WARNINGFLAGS += -Wno-poison-system-directories + CPPUTEST_C_WARNINGFLAGS += -Wno-poison-system-directories +endif # clang 1200 + +ifeq ($(CLANG_VERSION_NUM_GT_1205), Y) +# Not sure why apple clang throws these warnings on cpputest code when clang doesn't + CPPUTEST_CXX_WARNINGFLAGS += -Wno-suggest-override -Wno-suggest-destructor-override + CPPUTEST_C_WARNINGFLAGS += -Wno-suggest-override -Wno-suggest-destructor-override +endif endif endif @@ -222,7 +252,7 @@ else endif endif -# Default dir for the outout library +# Default dir for the output library ifndef CPPUTEST_LIB_DIR ifndef TARGET_PLATFORM CPPUTEST_LIB_DIR = lib @@ -236,7 +266,7 @@ ifndef CPPUTEST_MAP_FILE CPPUTEST_MAP_FILE = N endif -# No extentions is default +# No extensions is default ifndef CPPUTEST_USE_EXTENSIONS CPPUTEST_USE_EXTENSIONS = N endif @@ -310,8 +340,12 @@ endif ifeq ($(CPPUTEST_USE_GCOV), Y) - CPPUTEST_CXXFLAGS += -fprofile-arcs -ftest-coverage - CPPUTEST_CFLAGS += -fprofile-arcs -ftest-coverage + CPPUTEST_CXXFLAGS += -fprofile-arcs + CPPUTEST_CFLAGS += -fprofile-arcs + ifneq ($(CPPUTEST_USE_GCOV_NO_GCNO_FILES), Y) + CPPUTEST_CXXFLAGS += -ftest-coverage + CPPUTEST_CFLAGS += -ftest-coverage + endif endif CPPUTEST_CXXFLAGS += $(CPPUTEST_WARNINGFLAGS) $(CPPUTEST_CXX_WARNINGFLAGS) @@ -374,7 +408,7 @@ TEST_OBJS = $(call src_to_o,$(TEST_SRC)) STUFF_TO_CLEAN += $(TEST_OBJS) -MOCKS_SRC += $(call get_src_from_dir_list, $(MOCKS_SRC_DIRS)) +MOCKS_SRC += $(call get_src_from_dir_list, $(MOCKS_SRC_DIRS)) $(MOCKS_SRC_FILES) MOCKS_OBJS = $(call src_to_o,$(MOCKS_SRC)) STUFF_TO_CLEAN += $(MOCKS_OBJS) @@ -478,35 +512,53 @@ TEST_DEPS = $(TEST_OBJS) $(MOCKS_OBJS) $(PRODUCTION_CODE_START) $(TARGET_LIB) $( test-deps: $(TEST_DEPS) $(TEST_TARGET): $(TEST_DEPS) +ifndef MORE_SILENCE @echo Linking $@ +endif $(SILENCE)$(CXX) -o $@ $^ $(LD_LIBRARIES) $(LDFLAGS) $(TARGET_LIB): $(OBJ) +ifndef MORE_SILENCE @echo Building archive $@ +endif $(SILENCE)mkdir -p $(dir $@) +ifndef MORE_SILENCE $(SILENCE)$(AR) $(ARFLAGS) $@ $^ +else + $(SILENCE)$(AR) $(ARFLAGS) $@ $^ >/dev/null +endif $(SILENCE)$(RANLIB) $@ test: $(TEST_TARGET) - $(RUN_TEST_TARGET) | tee $(TEST_OUTPUT) + @$(eval TEST_RUN_RETURN_CODE_FILE=$(shell mktemp /tmp/cpputestResult.XXX)) + @($(RUN_TEST_TARGET); echo $$? > $(TEST_RUN_RETURN_CODE_FILE)) | tee $(TEST_OUTPUT) + @ret=$$(cat $(TEST_RUN_RETURN_CODE_FILE)); rm $(TEST_RUN_RETURN_CODE_FILE); if [ "$$ret" -ne 0 ]; then echo "$$(tput setaf 1)$(TEST_TARGET) returned $${ret}$$(tput sgr0)"; fi; exit $$ret vtest: $(TEST_TARGET) - $(RUN_TEST_TARGET) -v | tee $(TEST_OUTPUT) + @$(eval TEST_RUN_RETURN_CODE_FILE=$(shell mktemp /tmp/cpputestResult.XXX)) + @($(RUN_TEST_TARGET) -v; echo $$? > $(TEST_RUN_RETURN_CODE_FILE)) | tee $(TEST_OUTPUT) + @ret=$$(cat $(TEST_RUN_RETURN_CODE_FILE)); rm $(TEST_RUN_RETURN_CODE_FILE); if [ "$$ret" -ne 0 ]; then echo "$$(tput setaf 1)$(TEST_TARGET) returned $${ret}$$(tput sgr0)"; fi; exit $$ret $(CPPUTEST_OBJS_DIR)/%.o: %.cc +ifndef MORE_SILENCE @echo compiling $(notdir $<) +endif $(SILENCE)mkdir -p $(dir $@) - $(SILENCE)$(COMPILE.cpp) $(DEP_FLAGS) $(OUTPUT_OPTION) $< + $(SILENCE)$(CPPUTEST_CXX_PREFIX)$(COMPILE.cpp) $(DEP_FLAGS) $(OUTPUT_OPTION) $< $(CPPUTEST_OBJS_DIR)/%.o: %.cpp +ifndef MORE_SILENCE @echo compiling $(notdir $<) +endif $(SILENCE)mkdir -p $(dir $@) - $(SILENCE)$(COMPILE.cpp) $(DEP_FLAGS) $(OUTPUT_OPTION) $< + $(SILENCE)$(CPPUTEST_CXX_PREFIX)$(COMPILE.cpp) $(DEP_FLAGS) $(OUTPUT_OPTION) $< $(CPPUTEST_OBJS_DIR)/%.o: %.c +ifndef MORE_SILENCE @echo compiling $(notdir $<) +endif $(SILENCE)mkdir -p $(dir $@) - $(SILENCE)$(COMPILE.c) $(DEP_FLAGS) $(OUTPUT_OPTION) $< + $(SILENCE)$(CPPUTEST_CC_PREFIX)$(COMPILE.c) $(DEP_FLAGS) $(OUTPUT_OPTION) $< ifneq "$(MAKECMDGOALS)" "clean" -include $(DEP_FILES) @@ -514,9 +566,11 @@ endif .PHONY: clean clean: +ifndef MORE_SILENCE @echo Making clean +endif $(SILENCE)$(RM) $(STUFF_TO_CLEAN) - $(SILENCE)rm -rf gcov $(CPPUTEST_OBJS_DIR) + $(SILENCE)rm -rf gcov $(CPPUTEST_OBJS_DIR) $(CPPUTEST_LIB_DIR) $(SILENCE)find . -name "*.gcno" | xargs rm -f $(SILENCE)find . -name "*.gcda" | xargs rm -f diff --git a/build/alltests.mmp b/build/alltests.mmp index 8eaaf5b13..40c1dc86a 100644 --- a/build/alltests.mmp +++ b/build/alltests.mmp @@ -29,7 +29,7 @@ TARGET cpputest.exe TARGETTYPE exe UID 0x00000000 0x03A6305A -USERINCLUDE ..\include ..\include\CppUTest ..\include\Platforms\Symbian ..\tests +USERINCLUDE ..\include ..\include\CppUTest ..\tests SYSTEMINCLUDE \epoc32\include \epoc32\include\stdapis STATICLIBRARY libcrt0.lib diff --git a/build/bld.inf b/build/bld.inf index 7894587e7..c2305acfe 100644 --- a/build/bld.inf +++ b/build/bld.inf @@ -36,6 +36,7 @@ PRJ_EXPORTS ..\include\CppUTest\Failure.h \epoc32\include\CppUTest\Failure.h ..\include\CppUTest\TestRegistry.h \epoc32\include\CppUTest\TestRegistry.h ..\include\CppUTest\SimpleString.h \epoc32\include\CppUTest\SimpleString.h +..\include\CppUTest\SimpleStringInternalCache.h \epoc32\include\CppUTest\SimpleStringInternalCache.h ..\include\CppUTest\MemoryLeakWarning.h \epoc32\include\CppUTest\MemoryLeakWarning.h ..\include\CppUTest\CommandLineTestRunner.h \epoc32\include\CppuTest\CommandLineTestRunner.h ..\include\CppUTest\TestOutput.h \epoc32\include\CppuTest\TestOutput.h diff --git a/build/cmake_package_files/CppUTestConfig.cmake b/build/cmake_package_files/CppUTestConfig.cmake new file mode 100644 index 000000000..cce1985ae --- /dev/null +++ b/build/cmake_package_files/CppUTestConfig.cmake @@ -0,0 +1,32 @@ + +####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() ####### +####### Any changes to this file will be overwritten by the next CMake run #### +####### The input file was CppUTestConfig.cmake.install.in ######## + +get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE) + +macro(set_and_check _var _file) + set(${_var} "${_file}") + if(NOT EXISTS "${_file}") + message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !") + endif() +endmacro() + +macro(check_required_components _NAME) + foreach(comp ${${_NAME}_FIND_COMPONENTS}) + if(NOT ${_NAME}_${comp}_FOUND) + if(${_NAME}_FIND_REQUIRED_${comp}) + set(${_NAME}_FOUND FALSE) + endif() + endif() + endforeach() +endmacro() + +#################################################################################### + +set_and_check(CppUTest_INCLUDE_DIRS "${PACKAGE_PREFIX_DIR}/include") +include("${CMAKE_CURRENT_LIST_DIR}/CppUTestTargets.cmake") +set(CppUTest_LIBRARIES CppUTest CppUTestExt) +include("${CMAKE_CURRENT_LIST_DIR}/Modules/CppUTestBuildTimeDiscoverTests.cmake") + +check_required_components(CppUTest) diff --git a/build/cmake_package_files/CppUTestConfigVersion.cmake b/build/cmake_package_files/CppUTestConfigVersion.cmake new file mode 100644 index 000000000..69a28a705 --- /dev/null +++ b/build/cmake_package_files/CppUTestConfigVersion.cmake @@ -0,0 +1,37 @@ +# This is a basic version file for the Config-mode of find_package(). +# It is used by write_basic_package_version_file() as input file for configure_file() +# to create a version-file which can be installed along a config.cmake file. +# +# The created file sets PACKAGE_VERSION_EXACT if the current version string and +# the requested version string are exactly the same and it sets +# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version, +# but only if the requested major version is the same as the current one. +# The variable CVF_VERSION must be set before calling configure_file(). +set(PACKAGE_VERSION "4.0") +if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION) + set(PACKAGE_VERSION_COMPATIBLE FALSE) +else() + if("4.0" MATCHES "^([0-9]+)\\.") + set(CVF_VERSION_MAJOR "${CMAKE_MATCH_1}") + else() + set(CVF_VERSION_MAJOR "4.0") + endif() + if(PACKAGE_FIND_VERSION_MAJOR STREQUAL CVF_VERSION_MAJOR) + set(PACKAGE_VERSION_COMPATIBLE TRUE) + else() + set(PACKAGE_VERSION_COMPATIBLE FALSE) + endif() + if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION) + set(PACKAGE_VERSION_EXACT TRUE) + endif() +endif() +# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it: +if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "8" STREQUAL "") + return() +endif() +# check that the installed version has the same 32/64bit-ness as the one which is currently searching: +if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "8") + math(EXPR installedBits "8 * 8") + set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)") + set(PACKAGE_VERSION_UNSUITABLE TRUE) +endif() diff --git a/build/cmake_package_files/CppUTestTargets-relwithdebinfo.cmake b/build/cmake_package_files/CppUTestTargets-relwithdebinfo.cmake new file mode 100644 index 000000000..31ffbf4ba --- /dev/null +++ b/build/cmake_package_files/CppUTestTargets-relwithdebinfo.cmake @@ -0,0 +1,29 @@ +#---------------------------------------------------------------- +# Generated CMake target import file for configuration "RelWithDebInfo". +#---------------------------------------------------------------- + +# Commands may need to know the format version. +set(CMAKE_IMPORT_FILE_VERSION 1) + +# Import target "CppUTest" for configuration "RelWithDebInfo" +set_property(TARGET CppUTest APPEND PROPERTY IMPORTED_CONFIGURATIONS RELWITHDEBINFO) +set_target_properties(CppUTest PROPERTIES + IMPORTED_LINK_INTERFACE_LANGUAGES_RELWITHDEBINFO "CXX" + IMPORTED_LOCATION_RELWITHDEBINFO "${_IMPORT_PREFIX}/lib/libCppUTest.a" + ) + +list(APPEND _IMPORT_CHECK_TARGETS CppUTest ) +list(APPEND _IMPORT_CHECK_FILES_FOR_CppUTest "${_IMPORT_PREFIX}/lib/libCppUTest.a" ) + +# Import target "CppUTestExt" for configuration "RelWithDebInfo" +set_property(TARGET CppUTestExt APPEND PROPERTY IMPORTED_CONFIGURATIONS RELWITHDEBINFO) +set_target_properties(CppUTestExt PROPERTIES + IMPORTED_LINK_INTERFACE_LANGUAGES_RELWITHDEBINFO "CXX" + IMPORTED_LOCATION_RELWITHDEBINFO "${_IMPORT_PREFIX}/lib/libCppUTestExt.a" + ) + +list(APPEND _IMPORT_CHECK_TARGETS CppUTestExt ) +list(APPEND _IMPORT_CHECK_FILES_FOR_CppUTestExt "${_IMPORT_PREFIX}/lib/libCppUTestExt.a" ) + +# Commands beyond this point should not need to know the version. +set(CMAKE_IMPORT_FILE_VERSION) diff --git a/build/cmake_package_files/CppUTestTargets.cmake b/build/cmake_package_files/CppUTestTargets.cmake new file mode 100644 index 000000000..e1d587696 --- /dev/null +++ b/build/cmake_package_files/CppUTestTargets.cmake @@ -0,0 +1,101 @@ +# Generated by CMake + +if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.5) + message(FATAL_ERROR "CMake >= 2.6.0 required") +endif() +cmake_policy(PUSH) +cmake_policy(VERSION 2.6) +#---------------------------------------------------------------- +# Generated CMake target import file. +#---------------------------------------------------------------- + +# Commands may need to know the format version. +set(CMAKE_IMPORT_FILE_VERSION 1) + +# Protect against multiple inclusion, which would fail when already imported targets are added once more. +set(_targetsDefined) +set(_targetsNotDefined) +set(_expectedTargets) +foreach(_expectedTarget CppUTest CppUTestExt) + list(APPEND _expectedTargets ${_expectedTarget}) + if(NOT TARGET ${_expectedTarget}) + list(APPEND _targetsNotDefined ${_expectedTarget}) + endif() + if(TARGET ${_expectedTarget}) + list(APPEND _targetsDefined ${_expectedTarget}) + endif() +endforeach() +if("${_targetsDefined}" STREQUAL "${_expectedTargets}") + unset(_targetsDefined) + unset(_targetsNotDefined) + unset(_expectedTargets) + set(CMAKE_IMPORT_FILE_VERSION) + cmake_policy(POP) + return() +endif() +if(NOT "${_targetsDefined}" STREQUAL "") + message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_targetsDefined}\nTargets not yet defined: ${_targetsNotDefined}\n") +endif() +unset(_targetsDefined) +unset(_targetsNotDefined) +unset(_expectedTargets) + + +# Compute the installation prefix relative to this file. +get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH) +get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) +get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) +get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) +if(_IMPORT_PREFIX STREQUAL "/") + set(_IMPORT_PREFIX "") +endif() + +# Create imported target CppUTest +add_library(CppUTest STATIC IMPORTED) + +set_target_properties(CppUTest PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;${_IMPORT_PREFIX}/include/CppUTest" +) + +# Create imported target CppUTestExt +add_library(CppUTestExt STATIC IMPORTED) + +set_target_properties(CppUTestExt PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;${_IMPORT_PREFIX}/include/CppUTestExt" +) + +# Load information for each installed configuration. +get_filename_component(_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) +file(GLOB CONFIG_FILES "${_DIR}/CppUTestTargets-*.cmake") +foreach(f ${CONFIG_FILES}) + include(${f}) +endforeach() + +# Cleanup temporary variables. +set(_IMPORT_PREFIX) + +# Loop over all imported files and verify that they actually exist +foreach(target ${_IMPORT_CHECK_TARGETS} ) + foreach(file ${_IMPORT_CHECK_FILES_FOR_${target}} ) + if(NOT EXISTS "${file}" ) + message(FATAL_ERROR "The imported target \"${target}\" references the file + \"${file}\" +but this file does not exist. Possible reasons include: +* The file was deleted, renamed, or moved to another location. +* An install or uninstall procedure did not complete successfully. +* The installation package was faulty and contained + \"${CMAKE_CURRENT_LIST_FILE}\" +but not all the files it references. +") + endif() + endforeach() + unset(_IMPORT_CHECK_FILES_FOR_${target}) +endforeach() +unset(_IMPORT_CHECK_TARGETS) + +# This file does not depend on other imported targets which have +# been exported from the same project but in a separate export set. + +# Commands beyond this point should not need to know the version. +set(CMAKE_IMPORT_FILE_VERSION) +cmake_policy(POP) diff --git a/build/cpputest.mmp b/build/cpputest.mmp index 8093f8c59..103063507 100644 --- a/build/cpputest.mmp +++ b/build/cpputest.mmp @@ -29,7 +29,7 @@ TARGET cpputest.lib TARGETTYPE LIB UID 0x00000000 0x03A6305A -USERINCLUDE ..\include ..\include\CppUTest ..\include\Platforms\Symbian +USERINCLUDE ..\include ..\include\CppUTest SYSTEMINCLUDE \epoc32\include \epoc32\include\stdapis SOURCEPATH ..\src\CppUTest diff --git a/cmake/Modules/CppUTest.cmake b/cmake/Modules/CppUTest.cmake new file mode 100644 index 000000000..160959a5e --- /dev/null +++ b/cmake/Modules/CppUTest.cmake @@ -0,0 +1,117 @@ +set(_CPPUTEST_DISCOVERY_SCRIPT ${CMAKE_CURRENT_LIST_DIR}/_CppUTestDiscovery.cmake + CACHE INTERNAL "CppUTest discovery scripts" +) + +option(CPPUTEST_TESTS_DETAILED "Run discovered tests individually") +option(CPPUTEST_JUNIT_REPORT "Output JUnit test reports") + +function(cpputest_discover_tests target) + set(options JUNIT) + set(oneValueArgs DETAILED) + set(multiValueArgs EXTRA_ARGS) + cmake_parse_arguments( + "" + "${options}" + "${oneValueArgs}" + "${multiValueArgs}" + ${ARGN} + ) + + # Validate arguments. + if(NOT TARGET ${target}) + message(FATAL_ERROR + "Cannot discover tests for target \"${target}\" " + "which is not built by this project." + ) + endif() + + get_property(target_type + TARGET ${target} + PROPERTY TYPE + ) + if(NOT target_type STREQUAL "EXECUTABLE") + message(FATAL_ERROR + "Cannot discover tests for target \"${target}\" " + "which is not an executable." + ) + endif() + + get_property(emulator + TARGET ${target} + PROPERTY CROSSCOMPILING_EMULATOR + ) + if(CMAKE_CROSSCOMPILING) + if(NOT emulator) + message(WARNING "Cannot discover cross compiled tests without an emulator") + return() + endif() + endif() + + if(NOT DEFINED _EXTRA_ARGS) + set(_EXTRA_ARGS -v) + endif() + + if(NOT DEFINED _DETAILED) + set(_DETAILED ${CPPUTEST_TESTS_DETAILED}) + endif() + + if(_JUNIT OR CPPUTEST_JUNIT_REPORT) + list(APPEND _EXTRA_ARGS -ojunit) + endif() + + set(CTEST_INCLUDE_FILE "${CMAKE_CURRENT_BINARY_DIR}/${target}_include.cmake") + if(CMAKE_CONFIGURATION_TYPES) + set(CTEST_GENERATED_FILE "${CMAKE_CURRENT_BINARY_DIR}/${target}.$.cmake") + file(WRITE "${CTEST_INCLUDE_FILE}" + "if(EXISTS \"${CMAKE_CURRENT_BINARY_DIR}/${target}.\${CTEST_CONFIGURATION_TYPE}.cmake\")\n" + " include(\"${CMAKE_CURRENT_BINARY_DIR}/${target}.\${CTEST_CONFIGURATION_TYPE}.cmake\")\n" + "endif()\n" + ) + else() + set(CTEST_GENERATED_FILE "${CMAKE_CURRENT_BINARY_DIR}/${target}.cmake") + file(WRITE "${CTEST_INCLUDE_FILE}" + "if(EXISTS \"${CTEST_GENERATED_FILE}\")\n" + " include(\"${CTEST_GENERATED_FILE}\")\n" + "endif()\n" + ) + endif() + + add_custom_command( + TARGET ${target} POST_BUILD + BYPRODUCTS "${CTEST_GENERATED_FILE}" + COMMAND + "${CMAKE_COMMAND}" + -D "TESTS_DETAILED:BOOL=${_DETAILED}" + -D "EXECUTABLE=$" + -D "EMULATOR=${emulator}" + -D "ARGS=${_EXTRA_ARGS}" + -D "CTEST_FILE=${CTEST_GENERATED_FILE}" + -P "${_CPPUTEST_DISCOVERY_SCRIPT}" + WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" + VERBATIM + ) + + if(${CMAKE_VERSION} VERSION_LESS "3.10") + # We can only set one. + get_property(already_set + DIRECTORY + PROPERTY TEST_INCLUDE_FILE + SET + ) + if(${already_set}) + message(FATAL_ERROR + "Cannot discovery multiple tests from the same file" + ) + endif() + set_property( + DIRECTORY + PROPERTY TEST_INCLUDE_FILE "${CTEST_INCLUDE_FILE}" + ) + else() + set_property( + DIRECTORY APPEND + PROPERTY TEST_INCLUDE_FILES "${CTEST_INCLUDE_FILE}" + ) + endif() + +endfunction() diff --git a/cmake/Modules/CppUTestBuildTimeDiscoverTests.cmake b/cmake/Modules/CppUTestBuildTimeDiscoverTests.cmake index 57a5649ed..cfffad56c 100644 --- a/cmake/Modules/CppUTestBuildTimeDiscoverTests.cmake +++ b/cmake/Modules/CppUTestBuildTimeDiscoverTests.cmake @@ -1,9 +1,55 @@ +option(CPPUTEST_TESTS_DETAILED "Run discovered tests individually") + +set(_DISCOVER_SCRIPT "${CMAKE_CURRENT_LIST_DIR}/../Scripts/CppUTestBuildTimeDiscoverTests.cmake") + # Create target to discover tests -function (cpputest_buildtime_discover_tests EXECUTABLE) - add_custom_command (TARGET ${EXECUTABLE} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -DTESTS_DETAILED:BOOL=${TESTS_DETAILED} -DEXECUTABLE=${EXECUTABLE} -P ${PROJECT_SOURCE_DIR}/cmake/Scripts/CppUTestBuildTimeDiscoverTests.cmake - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} - COMMENT "Discovering Tests in ${EXECUTABLE}" - VERBATIM) +function (cpputest_buildtime_discover_tests tgt) + message(DEPRECATION + "Use cpputest_discover_tests from the CppUTest module instead" + ) + + set(options) + set(oneValueArgs DETAILED) + set(multiValueArgs) + cmake_parse_arguments( + "" + "${options}" + "${oneValueArgs}" + "${multiValueArgs}" + ${ARGN} + ) + if(NOT DEFINED _DETAILED) + set(_DETAILED ${CPPUTEST_TESTS_DETAILED}) + endif() + + if(NOT TARGET ${tgt}) + message(FATAL_ERROR + "Cannot discover tests for target \"${tgt}\" " + "which is not built by this project." + ) + endif() + + get_property(target_type + TARGET ${tgt} + PROPERTY TYPE + ) + if(NOT target_type STREQUAL "EXECUTABLE") + message(FATAL_ERROR + "Cannot discover tests for target \"${tgt}\" " + "which is not an executable." + ) + endif() + + add_custom_command( + TARGET ${tgt} POST_BUILD + COMMAND + ${CMAKE_COMMAND} + -D "TESTS_DETAILED:BOOL=${_DETAILED}" + -D "EXECUTABLE=$" + -D "EMULATOR=$" + -P "${_DISCOVER_SCRIPT}" + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + COMMENT "Discovering Tests in ${tgt}" + VERBATIM + ) endfunction () diff --git a/cmake/Modules/CppUTestConfigurationOptions.cmake b/cmake/Modules/CppUTestConfigurationOptions.cmake deleted file mode 100644 index 634482cec..000000000 --- a/cmake/Modules/CppUTestConfigurationOptions.cmake +++ /dev/null @@ -1,80 +0,0 @@ -if (MSVC) - set(CPP_PLATFORM VisualCpp) - include_directories(${CppUTestRootDirectory}/include/Platforms/${CPP_PLATFORM}) - option(STDC_WANT_SECURE_LIB "Use MSVC safe functions" ON) - if(STDC_WANT_SECURE_LIB) - ADD_DEFINITIONS(-DSTDC_WANT_SECURE_LIB) - endif(STDC_WANT_SECURE_LIB) -elseif (STD_C) - set(CPP_PLATFORM Gcc) -else (MSVC) - set(STD_CPP False) - set(MEMORY_LEAK_DETECTION False) - set(CPPUTEST_CXX_FLAGS "${CPPUTEST_CXX_FLAGS} -nostdinc") - set(CPPUTEST_LD_FLAGS "${CPPUTEST_LD_FLAGS} -nostdinc") - set(CPPUTEST_STD_C_LIB_DISABLED 1) - set(CPP_PLATFORM GccNoStdC) -endif (MSVC) - -include("${CppUTestRootDirectory}/cmake/Modules/CppUTestWarningFlags.cmake") - -if (NOT STD_CPP) - set(CPPUTEST_STD_CPP_LIB_DISABLED 1) - if (STD_C AND NOT MSVC) - set(CPPUTEST_CXX_FLAGS "${CPPUTEST_CXX_FLAGS} -nostdinc++") - endif (STD_C AND NOT MSVC) -endif (NOT STD_CPP) - -if (MEMORY_LEAK_DETECTION) - if (MSVC) - set(CPPUTEST_C_FLAGS "${CPPUTEST_C_FLAGS} /FI \"${CppUTestRootDirectory}/include/CppUTest/MemoryLeakDetectorMallocMacros.h\"") - set(CPPUTEST_CXX_FLAGS "${CPPUTEST_CXX_FLAGS} /FI \"${CppUTestRootDirectory}/include/CppUTest/MemoryLeakDetectorMallocMacros.h\"") - else (MSVC) - set(CPPUTEST_C_FLAGS "${CPPUTEST_C_FLAGS} -include \"${CppUTestRootDirectory}/include/CppUTest/MemoryLeakDetectorMallocMacros.h\"") - set(CPPUTEST_CXX_FLAGS "${CPPUTEST_CXX_FLAGS} -include \"${CppUTestRootDirectory}/include/CppUTest/MemoryLeakDetectorNewMacros.h\"") - set(CPPUTEST_CXX_FLAGS "${CPPUTEST_CXX_FLAGS} -include \"${CppUTestRootDirectory}/include/CppUTest/MemoryLeakDetectorMallocMacros.h\"") - endif (MSVC) -else (MEMORY_LEAK_DETECTION) - set(CPPUTEST_MEM_LEAK_DETECTION_DISABLED 1) -endif (MEMORY_LEAK_DETECTION) - -if (LONGLONG) - set(CPPUTEST_USE_LONG_LONG 1) -endif (LONGLONG) - -if (MAP_FILE AND NOT MSVC) - set(CPPUTEST_LD_FLAGS "${CPPUTEST_LD_FLAGS} -Wl,-map,$<.map.txt") -endif (MAP_FILE AND NOT MSVC) - -if (COVERAGE AND NOT MSVC) - set(CPPUTEST_C_FLAGS "${CPPUTEST_C_FLAGS} --coverage") - set(CPPUTEST_CXX_FLAGS "${CPPUTEST_CXX_FLAGS} --coverage") - set(CMAKE_BUILD_TYPE "Debug") -endif (COVERAGE AND NOT MSVC) - -if (C++11) - find_package(CXX11 REQUIRED) - set(CPPUTEST_CXX_FLAGS "${CPPUTEST_CXX_FLAGS} ${CXX11_FLAGS}") -endif (C++11) - -set(GMOCK_HOME $ENV{GMOCK_HOME}) -if (DEFINED ENV{GMOCK_HOME}) - # GMock pulls in gtest. - set(CPPUTEST_INCLUDE_GTEST_TESTS 1) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DGTEST_USE_OWN_TR1_TUPLE=1") - include_directories(${GMOCK_HOME}/include ${GMOCK_HOME}/gtest ${GMOCK_HOME}/gtest/include) - add_subdirectory(${GMOCK_HOME} "${CMAKE_CURRENT_BINARY_DIR}/gmock") - set(CPPUNIT_EXTERNAL_LIBRARIES ${CPPUNIT_EXTERNAL_LIBARIES} gmock gtest) - - set(CPPUTEST_C_WARNING_FLAGS "") - set(CPPUTEST_CXX_WARNING_FLAGS "") -endif (DEFINED ENV{GMOCK_HOME}) - -set(CPPUTEST_C_FLAGS "${CPPUTEST_C_FLAGS} ${CPPUTEST_C_WARNING_FLAGS}") -set(CPPUTEST_CXX_FLAGS "${CPPUTEST_CXX_FLAGS} ${CPPUTEST_CXX_WARNING_FLAGS}") - -if (CPPUTEST_FLAGS) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CPPUTEST_C_FLAGS}") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CPPUTEST_CXX_FLAGS}") - set(CMAKE_LD_FLAGS "${CMAKE_LD_FLAGS} ${CPPUTEST_LD_FLAGS}") -endif (CPPUTEST_FLAGS) diff --git a/cmake/Modules/CppUTestNormalizeTestOutputLocation.cmake b/cmake/Modules/CppUTestNormalizeTestOutputLocation.cmake deleted file mode 100644 index acb5efb34..000000000 --- a/cmake/Modules/CppUTestNormalizeTestOutputLocation.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# Override output properties to put test executable at specificied location -function (cpputest_normalize_test_output_location TEST_TARGET) - set_target_properties(${TEST_TARGET} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) - foreach(OUTPUT_CONFIG ${CMAKE_CONFIGURATION_TYPES}) - string(TOUPPER ${OUTPUT_CONFIG} OUTPUT_CONFIG) - set_target_properties(${TEST_TARGET} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY_${OUTPUT_CONFIG} ${CMAKE_CURRENT_BINARY_DIR}) - endforeach(OUTPUT_CONFIG) -endfunction () - diff --git a/cmake/Modules/CppUTestWarningFlags.cmake b/cmake/Modules/CppUTestWarningFlags.cmake deleted file mode 100644 index 36f7067ea..000000000 --- a/cmake/Modules/CppUTestWarningFlags.cmake +++ /dev/null @@ -1,71 +0,0 @@ -if (MSVC) - set(CPPUTEST_C_WARNING_FLAGS "/WX") - set(CPPUTEST_CXX_WARNING_FLAGS "/WX /wd4290") -else (MSVC) - include(CheckCCompilerFlag) - include(CheckCXXCompilerFlag) - - macro(check_and_append_c_warning_flags) - foreach (flag ${ARGN}) - check_c_compiler_flag("-${flag}" WARNING_C_FLAG_${flag}) - if (WARNING_C_FLAG_${flag}) - set(CPPUTEST_C_WARNING_FLAGS "${CPPUTEST_C_WARNING_FLAGS} -${flag}") - endif (WARNING_C_FLAG_${flag}) - endforeach (flag) - endmacro(check_and_append_c_warning_flags) - - macro(check_and_append_cxx_warning_flags) - foreach (flag ${ARGN}) - check_cxx_compiler_flag("-${flag}" WARNING_CXX_FLAG_TO_CHECK) - if (WARNING_CXX_FLAG_TO_CHECK) - set(CPPUTEST_CXX_WARNING_FLAGS "${CPPUTEST_CXX_WARNING_FLAGS} -${flag}") - endif (WARNING_CXX_FLAG_TO_CHECK) - endforeach (flag) - endmacro(check_and_append_cxx_warning_flags) - - if (NOT GMOCK AND NOT REAL_GTEST) - list(APPEND WARNING_C_FLAGS Werror pedantic-errors) - endif (NOT GMOCK AND NOT REAL_GTEST) - - set(WARNING_C_FLAGS - Weverything - Wall - Wextra - Wshadow - Wswitch-default - Wswitch-enum - Wconversion - Wsign-conversion - Wno-padded - Wno-disabled-macro-expansion - Wno-reserved-id-macro - Wno-keyword-macro - Wno-long-long - ) - - set(WARNING_C_ONLY_FLAGS - Wstrict-prototypes - ) - - set(WARNING_CXX_FLAGS - ${WARNING_C_FLAGS} - Woverloaded-virtual - Wno-global-constructors - Wno-exit-time-destructors - Wno-weak-vtables - Wno-old-style-cast - ) - - if (C++11) - set(WARNING_CXX_FLAGS - ${WARNING_CXX_FLAGS} - Wno-c++98-compat - Wno-c++98-compat-pedantic - ) - endif (C++11) - - check_and_append_c_warning_flags(${WARNING_C_FLAGS}) - check_and_append_c_warning_flags(${WARNING_C_ONLY_FLAGS}) - check_and_append_cxx_warning_flags(${WARNING_CXX_FLAGS}) - -endif (MSVC) diff --git a/cmake/Modules/FindCXX11.cmake b/cmake/Modules/FindCXX11.cmake deleted file mode 100644 index 989a99b86..000000000 --- a/cmake/Modules/FindCXX11.cmake +++ /dev/null @@ -1,49 +0,0 @@ -# - Finds if the compiler has C++11 support -# This module can be used to detect compiler flags for using C++11, and checks -# a small subset of the language. -# -# The following variables are set: -# CXX11_FLAGS - flags to add to the CXX compiler for C++11 support -# CXX11_FOUND - true if the compiler supports C++11 -# -# TODO: When compilers starts implementing the whole C++11, check the full set - -include(CheckCXXSourceCompiles) -include(FindPackageHandleStandardArgs) - -set(CXX11_FLAG_CANDIDATES - # Eveerything that automatically accepts C++11 - " " - # gcc, clang and Intel Linux - "-std=c++11" - # Intel windows - "/Qstd=c++0x" - ) - -set(CXX11_TEST_SOURCE -" -#if __cplusplus < 201103L -#error \"Can not compile with C++11\" -#endif - -int main() -{} -") - -foreach(FLAG ${CXX11_FLAG_CANDIDATES}) - set(SAFE_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") - set(CMAKE_REQUIRED_FLAGS "${FLAG}") - unset(CXX11_FLAG_DETECTED CACHE) - message(STATUS "Try C++11 flag = [${FLAG}]") - check_cxx_source_compiles("${CXX11_TEST_SOURCE}" CXX11_FLAG_DETECTED) - set(CMAKE_REQUIRED_FLAGS "${SAFE_CMAKE_REQUIRED_FLAGS}") - if(CXX11_FLAG_DETECTED) - set(CXX11_FLAGS_INTERNAL "${FLAG}") - break() - endif(CXX11_FLAG_DETECTED) -endforeach(FLAG ${CXX11_FLAG_CANDIDATES}) - -set(CXX11_FLAGS "${CXX11_FLAGS_INTERNAL}") - -find_package_handle_standard_args(CXX11 DEFAULT_MSG CXX11_FLAGS) -mark_as_advanced(CXX11_FLAGS) diff --git a/cmake/Modules/_CppUTestDiscovery.cmake b/cmake/Modules/_CppUTestDiscovery.cmake new file mode 100644 index 000000000..a970fbc37 --- /dev/null +++ b/cmake/Modules/_CppUTestDiscovery.cmake @@ -0,0 +1,98 @@ +set(script) + +function(add_command NAME) + set(_args "") + # use ARGV* instead of ARGN, because ARGN splits arrays into multiple arguments + math(EXPR _last_arg ${ARGC}-1) + foreach(_n RANGE 1 ${_last_arg}) + set(_arg "${ARGV${_n}}") + if(_arg MATCHES "[^-./:a-zA-Z0-9_]") + set(_args "${_args} [==[${_arg}]==]") # form a bracket_argument + else() + set(_args "${_args} ${_arg}") + endif() + endforeach() + set(script "${script}${NAME}(${_args})\n" PARENT_SCOPE) +endfunction() + +if(NOT EXISTS "${EXECUTABLE}") + message(FATAL_ERROR + "Executable \"${EXECUTABLE}\" does not exist" + ) +endif() + +macro(add_test_to_script TEST_NAME TEST_LOCATION SELECT_ARG) + add_command( + add_test + "${TEST_NAME}" + ${EMULATOR} + "${EXECUTABLE}" + ${ARGS} + ${SELECT_ARG} + ${TEST_NAME} + ) + add_command( + set_tests_properties + "${TEST_NAME}" + PROPERTIES + DEF_SOURCE_LINE + "${TEST_LOCATION}" + ) +endmacro() + +execute_process( + COMMAND ${EMULATOR} "${EXECUTABLE}" -ll + OUTPUT_VARIABLE discovered_tests + RESULT_VARIABLE result + ERROR_VARIABLE error +) +if(NOT ${result} EQUAL 0) + message(FATAL_ERROR + "Error executing ${EXECUTABLE}:\n" + "${error}" + ) +endif() + +string(CONCAT LL_LINE_REGEX + "^([^.]*)" # test group + "\\." + "([^.]*)" # test name + "\\." + "(.*)" # file name (only this field is allowed to contain dots) + "\\." + "([^.]*)" # line number + "\n" +) +string(REGEX MATCHALL "[^\n]+\n" discovered_test_lines "${discovered_tests}") +if(TESTS_DETAILED) + foreach(line IN LISTS discovered_test_lines) + string(REGEX MATCH "${LL_LINE_REGEX}" __unused "${line}") + set(test_name "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}") + file(TO_CMAKE_PATH "${CMAKE_MATCH_3}" test_file) + set(test_location "${test_file}:${CMAKE_MATCH_4}") + add_test_to_script("${test_name}" "${test_location}" -st) + endforeach() +else() + foreach(line IN LISTS discovered_test_lines) + string(REGEX MATCH "${LL_LINE_REGEX}" __unused "${line}") + set(test_name "${CMAKE_MATCH_1}") + file(TO_CMAKE_PATH "${CMAKE_MATCH_3}" test_file) + set(test_line "${CMAKE_MATCH_4}") + if (NOT _${test_name}_file) + # if the group spans two files, arbitrarily choose the first one encountered + set(_${test_name}_file "${test_file}") + set(_${test_name}_line "${test_line}") + elseif(test_file STREQUAL _${test_name}_file AND test_line LESS _${test_name}_line) + # line number will eventually be the first line of the first test in the group's file + set(_${test_name}_line ${test_line}) + endif() + list(APPEND groups_seen ${test_name}) + endforeach() + list(REMOVE_DUPLICATES groups_seen) + foreach(test_name IN LISTS groups_seen) + set(test_location "${_${test_name}_file}:${_${test_name}_line}") + add_test_to_script("${test_name}" "${test_location}" -sg) + endforeach() +endif() + +file(WRITE "${CTEST_FILE}" "${script}") diff --git a/cmake/Scripts/CppUTestBuildTimeDiscoverTests.cmake b/cmake/Scripts/CppUTestBuildTimeDiscoverTests.cmake index 901e08bbc..c5d96c031 100644 --- a/cmake/Scripts/CppUTestBuildTimeDiscoverTests.cmake +++ b/cmake/Scripts/CppUTestBuildTimeDiscoverTests.cmake @@ -5,6 +5,13 @@ # # This script is to be called from ../Modules/CppUTestBuildTimeDiscoverTests.cmake # +# Notes on invocation and used variables: +# ${CMAKE_COMMAND} -DTESTS_DETAILED:BOOL= -DEXECUTABLE= -P +# +# TESTS_DETAILED c.f. top-level CMakeLists.txt +# FULLPATH-TO-EXECUTABLE - use $ or explicit +# The overwritten CTestTestfile.cmake is located in ${CMAKE_CURRENT_BINARY_DIR} +# # Steps to generate ADD_TEST() commands build time # - Read CTestTestfile.cmake # - Create update entries @@ -33,13 +40,13 @@ function (JOIN VALUES GLUE OUTPUT) set (${OUTPUT} "${_TMP_STR}" PARENT_SCOPE) endfunction() -function (buildtime_discover_tests EXECUTABLE_CMD DISCOVER_ARG OUTPUT) - execute_process(COMMAND ${EXECUTABLE_CMD} ${DISCOVER_ARG} +function (buildtime_discover_tests EXECUTABLE DISCOVER_ARG OUTPUT) + execute_process(COMMAND ${EMULATOR} ${EXECUTABLE} ${DISCOVER_ARG} OUTPUT_VARIABLE _TMP_OUTPUT ERROR_VARIABLE DISCOVER_ERR RESULT_VARIABLE DISCOVER_ERR) if(NOT ${DISCOVER_ERR} EQUAL 0) - message(SEND_ERROR "Executable \"${EXECUTABLE_CMD} ${DISCOVER_ARG}\" failed with output:\n" + message(SEND_ERROR "Executable \"${EXECUTABLE} ${DISCOVER_ARG}\" failed with output:\n" "${DISCOVER_ERR}\n" "Please check that the excutable was added.") endif(NOT ${DISCOVER_ERR} EQUAL 0) @@ -54,11 +61,11 @@ endfunction() set(CTESTFNAME "${CMAKE_CURRENT_BINARY_DIR}/CTestTestfile.cmake") file(STRINGS ${CTESTFNAME} CTESTTESTS) -set(EXECUTABLE_CMD "${CMAKE_CURRENT_BINARY_DIR}/${EXECUTABLE}") +get_filename_component(EXECUTABLE_SHORT_NAME ${EXECUTABLE} NAME_WE) if (TESTS_DETAILED) set(DISCOVER_ARG "-ln") - buildtime_discover_tests("${EXECUTABLE_CMD}" "${DISCOVER_ARG}" TestList_GroupsAndNames) + buildtime_discover_tests("${EXECUTABLE}" "${DISCOVER_ARG}" TestList_GroupsAndNames) set(lastgroup "") foreach(testfullname ${TestList_GroupsAndNames}) string(REGEX MATCH "^([^/.]+)" groupname ${testfullname}) @@ -68,14 +75,14 @@ if (TESTS_DETAILED) set(lastgroup "${groupname}") endif (NOT ("${groupname}" STREQUAL "${lastgroup}")) message("... ${testname}") - buildtime_add_test(${EXECUTABLE}.${testfullname} ${EXECUTABLE_CMD} -sg ${groupname} -sn ${testname} -c) + buildtime_add_test(${EXECUTABLE_SHORT_NAME}.${testfullname} ${EMULATOR} ${EXECUTABLE} -sg ${groupname} -sn ${testname}) endforeach() else (TESTS_DETAILED) set(DISCOVER_ARG "-lg") - buildtime_discover_tests("${EXECUTABLE_CMD}" "${DISCOVER_ARG}" TestList_Groups) + buildtime_discover_tests("${EXECUTABLE}" "${DISCOVER_ARG}" TestList_Groups) foreach(group ${TestList_Groups}) message("TestGroup: ${group}") - buildtime_add_test(${EXECUTABLE}.${group} "${EXECUTABLE_CMD}" -sg ${group} -c) + buildtime_add_test(${EXECUTABLE_SHORT_NAME}.${group} ${EMULATOR} "${EXECUTABLE}" -sg ${group}) endforeach() endif (TESTS_DETAILED) diff --git a/cmake/Toolchains/arm-none-eabi-gcc.toolchain.cmake b/cmake/Toolchains/arm-none-eabi-gcc.toolchain.cmake new file mode 100644 index 000000000..b9ab5030e --- /dev/null +++ b/cmake/Toolchains/arm-none-eabi-gcc.toolchain.cmake @@ -0,0 +1,8 @@ +set(CMAKE_SYSTEM_NAME Generic) +set(CMAKE_SYSTEM_PROCESSOR cortex-m4) + +set(CMAKE_C_COMPILER arm-none-eabi-gcc) + +set(CMAKE_C_FLAGS_INIT "-mcpu=cortex-m4") +set(CMAKE_CXX_FLAGS_INIT "-mcpu=cortex-m4") +set(CMAKE_EXE_LINKER_FLAGS_INIT "-specs=rdimon.specs") diff --git a/cmake/Toolchains/clang+mingw-win32.toolchain.cmake b/cmake/Toolchains/clang+mingw-win32.toolchain.cmake new file mode 100644 index 000000000..53711d5a8 --- /dev/null +++ b/cmake/Toolchains/clang+mingw-win32.toolchain.cmake @@ -0,0 +1,6 @@ +# Toolchain to use Clang compiler with MinGW binutils (e.g. linker) in Windows to generate 32-bits executables + +set(CMAKE_C_COMPILER clang) +set(CMAKE_C_FLAGS "-target i686-w64-mingw32 -m32" CACHE STRING "" FORCE) +set(CMAKE_CXX_COMPILER clang++) +set(CMAKE_CXX_FLAGS "-target i686-w64-mingw32 -m32" CACHE STRING "" FORCE) \ No newline at end of file diff --git a/cmake/Toolchains/clang+mingw-win64.toolchain.cmake b/cmake/Toolchains/clang+mingw-win64.toolchain.cmake new file mode 100644 index 000000000..8a2d26501 --- /dev/null +++ b/cmake/Toolchains/clang+mingw-win64.toolchain.cmake @@ -0,0 +1,6 @@ +# Toolchain to use Clang compiler with MinGW binutils (e.g. linker) in Windows to generate 64-bits executables + +set(CMAKE_C_COMPILER clang) +set(CMAKE_C_FLAGS "-target x86_64-w64-mingw32" CACHE STRING "" FORCE) +set(CMAKE_CXX_COMPILER clang++) +set(CMAKE_CXX_FLAGS "-target x86_64-w64-mingw32" CACHE STRING "" FORCE) \ No newline at end of file diff --git a/cmake/Toolchains/ewarm-linux.toolchain.cmake b/cmake/Toolchains/ewarm-linux.toolchain.cmake new file mode 100644 index 000000000..e0053a7bf --- /dev/null +++ b/cmake/Toolchains/ewarm-linux.toolchain.cmake @@ -0,0 +1,21 @@ +### BEGIN CMAKE_TOOLCHAIN_FILE +# "Generic" is used when compiling for bare-metal +set(CMAKE_SYSTEM_NAME Generic) + +# Set the EW installation root directory +#(Avoid spaces in the path or you need to escape them) +set(EW_ROOT_DIR "/opt/iarsystems/bxarm/arm/") + +# Compiler flags needed to compile for this CPU +set(CPU_FLAGS "--cpu Cortex-M4F") + +# Set up the CMake variables for compiler and assembler +# (The reason for both C and CXX variables is that CMake +# treats C and C++ tools individually) +set(CMAKE_C_COMPILER "${EW_ROOT_DIR}/bin/iccarm" "${CPU_FLAGS} --dlib_config normal") +set(CMAKE_CXX_COMPILER "${EW_ROOT_DIR}/bin/iccarm" "${CPU_FLAGS} --dlib_config normal") +set(CMAKE_ASM_COMPILER "${EW_ROOT_DIR}/bin/iasmarm" "${CPU_FLAGS}") + +# Build with cmake -S. -Bbuild -G "Unix Makefiles" -DCMAKE_TOOLCHAIN_FILE=cmake/Toolchains/ewarm-linux.toolchain.cmake + +### END CMAKE_TOOLCHAIN_FILE diff --git a/cmake/Toolchains/ewarm-win.toolchain.cmake b/cmake/Toolchains/ewarm-win.toolchain.cmake new file mode 100644 index 000000000..ab28b445f --- /dev/null +++ b/cmake/Toolchains/ewarm-win.toolchain.cmake @@ -0,0 +1,21 @@ +### BEGIN CMAKE_TOOLCHAIN_FILE +# "Generic" is used when compiling for bare-metal +set(CMAKE_SYSTEM_NAME Generic) + +# Set the EW installation root directory +#(Avoid spaces in the path or you need to escape them) +set(EW_ROOT_DIR "E:/Program Files\ (x86)/IAR\ Systems/Embedded\ Workbench\ Arm 8.50.6/arm") + +# Compiler flags needed to compile for this CPU +set(CPU_FLAGS "--cpu Cortex-M4F") + +# Set up the CMake variables for compiler and assembler +# (The reason for both C and CXX variables is that CMake +# treats C and C++ tools individually) +set(CMAKE_C_COMPILER "${EW_ROOT_DIR}/bin/iccarm.exe" "${CPU_FLAGS} --dlib_config normal") +set(CMAKE_CXX_COMPILER "${EW_ROOT_DIR}/bin/iccarm.exe" "${CPU_FLAGS} --dlib_config normal") +set(CMAKE_ASM_COMPILER "${EW_ROOT_DIR}/bin/iasmarm.exe" "${CPU_FLAGS}") + +# Build with cmake -S. -Bbuild -G "NMake Makefiles" -DCMAKE_TOOLCHAIN_FILE=cmake/Toolchains/ewarm-win.toolchain.cmake + +### END CMAKE_TOOLCHAIN_FILE diff --git a/cmake/install.cmake b/cmake/install.cmake new file mode 100644 index 000000000..f58ba31b9 --- /dev/null +++ b/cmake/install.cmake @@ -0,0 +1,65 @@ +set(INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_INCLUDEDIR}") +set(LIB_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}") +set(INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include") + +# Pkg-config file. +set(prefix "${CMAKE_INSTALL_PREFIX}") +set(exec_prefix "\${prefix}") +set(libdir "\${exec_prefix}/${LIB_INSTALL_DIR}") +set(includedir "\${prefix}/${INCLUDE_INSTALL_DIR}") +set(PACKAGE_VERSION "${PROJECT_VERSION}") + +configure_file(cpputest.pc.in cpputest.pc @ONLY) +install( + FILES "${CMAKE_CURRENT_BINARY_DIR}/cpputest.pc" + DESTINATION ${LIB_INSTALL_DIR}/pkgconfig +) + +install( + FILES "${CMAKE_CURRENT_BINARY_DIR}/generated/CppUTestGeneratedConfig.h" + DESTINATION "${INCLUDE_INSTALL_DIR}/generated" +) + +include(CMakePackageConfigHelpers) + +set(CPPUTEST_CONFIG_DEST "${LIB_INSTALL_DIR}/CppUTest/cmake") + +configure_package_config_file(CppUTestConfig.cmake.install.in + ${CMAKE_CURRENT_BINARY_DIR}/install/CppUTestConfig.cmake + INSTALL_DESTINATION "${CPPUTEST_CONFIG_DEST}" + PATH_VARS INCLUDE_INSTALL_DIR LIB_INSTALL_DIR) +write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/install/CppUTestConfigVersion.cmake + COMPATIBILITY SameMajorVersion +) +install( + FILES + ${CMAKE_CURRENT_BINARY_DIR}/install/CppUTestConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/install/CppUTestConfigVersion.cmake + DESTINATION "${CPPUTEST_CONFIG_DEST}" +) +install( + EXPORT CppUTestTargets + NAMESPACE CppUTest:: + DESTINATION "${CPPUTEST_CONFIG_DEST}" +) +install( + FILES ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Scripts/CppUTestBuildTimeDiscoverTests.cmake + DESTINATION "${CPPUTEST_CONFIG_DEST}/Scripts" +) +install( + FILES + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules/CppUTestBuildTimeDiscoverTests.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules/CppUTest.cmake + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules/_CppUTestDiscovery.cmake + DESTINATION "${CPPUTEST_CONFIG_DEST}/Modules" +) +configure_package_config_file(CppUTestConfig.cmake.build.in + ${CMAKE_CURRENT_BINARY_DIR}/CppUTestConfig.cmake + INSTALL_DESTINATION ${CMAKE_CURRENT_BINARY_DIR} + PATH_VARS INCLUDE_DIR CMAKE_CURRENT_BINARY_DIR +) +write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/CppUTestConfigVersion.cmake + COMPATIBILITY SameMajorVersion +) diff --git a/cmake/warnings.cmake b/cmake/warnings.cmake new file mode 100644 index 000000000..4b763f684 --- /dev/null +++ b/cmake/warnings.cmake @@ -0,0 +1,68 @@ +unset(WARNING_COMMON_FLAGS) +unset(WARNING_C_FLAGS) +unset(WARNING_CXX_FLAGS) + +if( + (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") OR + (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") OR + (CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") +) + set(WARNING_COMMON_FLAGS + -Wall + -Wextra + -pedantic + -Wshadow + -Wswitch-default + -Wswitch-enum + -Wconversion + -Wsign-conversion + -Wmissing-include-dirs + -Wno-padded + -Wno-disabled-macro-expansion + -Wreserved-id-macro + -Wreserved-identifier + -Wno-long-long + -Wno-unsafe-buffer-usage + ) + + set(WARNING_C_FLAGS + -Wstrict-prototypes + ) + + set(WARNING_CXX_FLAGS + -Woverloaded-virtual + -Wno-global-constructors + -Wno-exit-time-destructors + -Wno-weak-vtables + -Wno-old-style-cast + ) + + if(DEFINED CMAKE_CXX_STANDARD AND NOT CMAKE_CXX_STANDARD EQUAL 98) + list(APPEND WARNING_CXX_FLAGS + -Wno-c++98-compat + -Wno-c++98-compat-pedantic + -Wno-c++14-compat + -Wno-inconsistent-missing-destructor-override + -Wsuggest-override + ) + endif() + + set(CMAKE_REQUIRED_FLAGS "-Wno-error") +endif() + +include(CheckCCompilerFlag) +foreach(flag IN LISTS WARNING_COMMON_FLAGS WARNING_C_FLAGS) + check_c_compiler_flag("${flag}" WARNING_C_FLAG_${flag}) + if(WARNING_C_FLAG_${flag}) + add_compile_options("$<$:${flag}>") + endif() +endforeach() + +include(CheckCXXCompilerFlag) +foreach(flag IN LISTS WARNING_COMMON_FLAGS WARNING_CXX_FLAGS) + string(REPLACE "++" "xx" WARNING_CXX_FLAG_VAR "WARNING_CXX_FLAG_${flag}") + check_cxx_compiler_flag("${flag}" ${WARNING_CXX_FLAG_VAR}) + if(${WARNING_CXX_FLAG_VAR}) + add_compile_options("$<$:${flag}>") + endif() +endforeach() diff --git a/config.h.cmake b/config.h.cmake index e8a4b9fd4..037a695fb 100644 --- a/config.h.cmake +++ b/config.h.cmake @@ -2,11 +2,17 @@ #define CONFIG_H_ #cmakedefine CPPUTEST_MEM_LEAK_DETECTION_DISABLED -#cmakedefine CPPUTEST_USE_LONG_LONG +#cmakedefine01 CPPUTEST_USE_LONG_LONG +#cmakedefine CPPUTEST_HAVE_STRDUP + +#cmakedefine CPPUTEST_HAVE_FORK +#cmakedefine CPPUTEST_HAVE_WAITPID +#cmakedefine CPPUTEST_HAVE_KILL +#cmakedefine CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK + +#cmakedefine CPPUTEST_HAVE_GETTIMEOFDAY #cmakedefine CPPUTEST_STD_C_LIB_DISABLED #cmakedefine CPPUTEST_STD_CPP_LIB_DISABLED -#cmakedefine INCLUDE_GTEST_TESTS - #endif diff --git a/configure.ac b/configure.ac index 43d89a3cb..0c105e29b 100644 --- a/configure.ac +++ b/configure.ac @@ -1,6 +1,7 @@ AC_PREREQ([2.68]) -AC_INIT([CppUTest], [3.8], [https://github.com/cpputest/cpputest]) +AC_INIT([CppUTest], [4.0], [https://github.com/cpputest/cpputest]) +AC_CONFIG_AUX_DIR([.]) AM_INIT_AUTOMAKE([subdir-objects]) AC_CONFIG_SRCDIR([src/CppUTest/Utest.cpp]) AC_CONFIG_HEADERS([config.h]) @@ -33,6 +34,7 @@ AM_SILENT_RULES ACX_PTHREAD([LIBS="$PTHREAD_LIBS $LIBS"]) +AX_COMPILER_VERSION # This additional -lpthread was added due to a bug on gcc for MacOSX: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=42159 # According to the bug report, a workaround is to link -lpthread. Even the ACX_PTHREAD doesn't do that, so we add an # additional check if that it possible, and if it is, then we link pthread @@ -60,7 +62,7 @@ AC_TYPE_LONG_LONG_INT # Checks for library functions. AC_FUNC_FORK -AC_CHECK_FUNCS([gettimeofday memset strstr]) +AC_CHECK_FUNCS([waitpid gettimeofday memset strstr strdup pthread_mutex_lock kill]) AC_CHECK_PROG([CPPUTEST_HAS_GCC], [gcc], [yes], [no]) AC_CHECK_PROG([CPPUTEST_HAS_CLANG], [clang], [yes], [no]) @@ -74,31 +76,70 @@ saved_cxxflags="$CXXFLAGS" saved_ldflags="$LDFLAGS" if test "x$USE_MAINTAINER_MODE" = "xyes"; then -# FLag -Werror. +# Flag -Werror. CFLAGS=-Werror AC_MSG_CHECKING([whether CC and CXX supports -Werror]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS_STRICT="${CPPUTEST_CWARNINGFLAGS} -Werror"; CPPUTEST_CXXWARNINGFLAGS_STRICT="${CPPUTEST_CXXWARNINGFLAGS} -Werror" ], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" fi +AC_LANG_PUSH([C++]) ##################################################################################### -##### C++ 11 checks +##### C++ checks -### Checking for Standard C++ 11 compiler flags -AC_LANG_PUSH([C++]) +# Flag -std=c++1y +CXXFLAGS="-Werror -std=c++1y" +AC_MSG_CHECKING([whether CXX supports -std=c++1y]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CPP14FLAG="-std=c++1y" ], [AC_MSG_RESULT([no])]) +CXXFLAGS="$saved_cxxflags" + +# Flag std=c++14 +CXXFLAGS="-Werror -std=c++14" +AC_MSG_CHECKING([whether CXX supports -std=c++14]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CPP14FLAG="-std=c++14" ], [AC_MSG_RESULT([no])]) +CXXFLAGS="$saved_cxxflags" + +# Flag std=c++17 +CXXFLAGS="-Werror -std=c++17" +AC_MSG_CHECKING([whether CXX supports -std=c++17]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CPP17FLAG="-std=c++17" ], [AC_MSG_RESULT([no])]) +CXXFLAGS="$saved_cxxflags" + +# Flag std=c++20 +CXXFLAGS="-Werror -std=c++2a" +AC_MSG_CHECKING([whether CXX supports -std=c++2a]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CPP20FLAG="-std=c++2a" ], [AC_MSG_RESULT([no])]) +CXXFLAGS="$saved_cxxflags" + +# Flag std=c++20 +CXXFLAGS="-Werror -std=c++20" +AC_MSG_CHECKING([whether CXX supports -std=c++20]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CPP20FLAG="-std=c++20" ], [AC_MSG_RESULT([no])]) +CXXFLAGS="$saved_cxxflags" + +##################################################################################### +##### C++ version checks -# FLag -std=c++0x -CXXFLAGS="-std=c++0x" +### Checking for C++ version compiler flags + +# Flag -std=c++98 +CXXFLAGS="-Werror -std=c++98" +AC_MSG_CHECKING([whether CXX supports -std=c++98]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CPP98FLAG="-std=c++98" ], [AC_MSG_RESULT([no])]) +CXXFLAGS="$saved_cxxflags" + +# Flag -std=c++0x +CXXFLAGS="-Werror -std=c++0x" AC_MSG_CHECKING([whether CXX supports -std=c++0x]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CPP11FLAG="-std=c++0x" ], [AC_MSG_RESULT([no])]) CXXFLAGS="$saved_cxxflags" -CXXFLAGS="-std=c++11" +CXXFLAGS="-Werror -std=c++11" AC_MSG_CHECKING([whether CXX supports -std=c++11]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CPP11FLAG="-std=c++11" ], [AC_MSG_RESULT([no])]) CXXFLAGS="$saved_cxxflags" -CXXFLAGS="-stdlib=libc++" +CXXFLAGS="-Werror -stdlib=libc++" AC_MSG_CHECKING([whether CXX supports -stdlib=libc++]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]])], [AC_MSG_RESULT([yes]); CPPUTEST_CPP11FLAG="${CPPUTEST_CPP11FLAG} -stdlib=libc++" ], [AC_MSG_RESULT([no])]) CXXFLAGS="$saved_cxxflags" @@ -106,88 +147,99 @@ CXXFLAGS="$saved_cxxflags" # Flag -Wno-c++98-compat CXXFLAGS="-Werror -Wno-c++98-compat" AC_MSG_CHECKING([whether CXX supports -Wno-c++98-compat]) -AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CPP11BLACKLIST="${CPPUTEST_CPP11BLACKLIST} -Wno-c++98-compat" ], [AC_MSG_RESULT([no])]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-c++98-compat" ], [AC_MSG_RESULT([no])]) CXXFLAGS="$saved_cxxflags" # Flag -Wno-c++98-compat-pedantic CXXFLAGS="-Werror -Wno-c++98-compat-pedantic" AC_MSG_CHECKING([whether CXX supports -Wno-c++98-compat-pedantic]) -AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CPP11BLACKLIST="${CPPUTEST_CPP11BLACKLIST} -Wno-c++98-compat-pedantic" ], [AC_MSG_RESULT([no])]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-c++98-compat-pedantic" ], [AC_MSG_RESULT([no])]) +CXXFLAGS="$saved_cxxflags" + +# Flag -Wno-c++14-compat +CXXFLAGS="-Werror -Wno-c++14-compat" +AC_MSG_CHECKING([whether CXX supports -Wno-c++14-compat]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-c++14-compat" ], [AC_MSG_RESULT([no])]) CXXFLAGS="$saved_cxxflags" AC_LANG_POP -# FLag -Wno-c++11-long-long. This must be on if it is available as otherwise long long is supported but causes a warning. +# Flag -Wno-c++11-long-long. This must be on if it is available as otherwise long long is supported but causes a warning. CFLAGS="-Werror -Wno-c++11-long-long" AC_MSG_CHECKING([whether CC and CXX supports -Wno-c++11-long-long]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wno-c++11-long-long" CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-c++11-long-long" ], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" -# FLag -Wno-long-long must be on for C. +# Flag -Wno-long-long must be on for C. CFLAGS="-Werror -Wno-long-long" -AC_MSG_CHECKING([whether CC supports -Wno-long-long]) +AC_MSG_CHECKING([whether CC and CXX supports -Wno-long-long]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wno-long-long" CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-long-long"], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" ##################################################################################### -##### More of these warnings -# FLag -Weverything. -CFLAGS="-Werror -Weverything -Wno-unused-macros" -AC_MSG_CHECKING([whether CC and CXX supports -Weverything]) -AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Weverything"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Weverything" ], [AC_MSG_RESULT([no])]) -CFLAGS="$saved_cflags" - -# FLag -Wall. +# Flag -Wall. CFLAGS="-Werror -Wall" AC_MSG_CHECKING([whether CC and CXX supports -Wall]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wall"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wall" ], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" -# FLag -Wextra. +# Flag -Wextra. CFLAGS="-Werror -Wextra" AC_MSG_CHECKING([whether CC and CXX supports -Wextra]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wextra"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wextra" ], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" -# FLag -Wshadow. +# Flag -Wshadow. CFLAGS="-Werror -Wshadow" AC_MSG_CHECKING([whether CC and CXX supports -Wshadow]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wshadow"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wshadow" ], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" -# FLag -Wswitch-default +# Flag -Wswitch-default CFLAGS="-Werror -Wswitch-default" AC_MSG_CHECKING([whether CC and CXX supports -Wswitch-default]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wswitch-default"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wswitch-default" ], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" -# FLag -Wswitch-enum +# Flag -Wswitch-enum CFLAGS="-Werror -Wswitch-enum" AC_MSG_CHECKING([whether CC and CXX supports -Wswitch-enum]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wswitch-enum"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wswitch-enum" ], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" -# FLag -Wconversion +# Flag -Wconversion CFLAGS="-Werror -Wconversion" AC_MSG_CHECKING([whether CC and CXX supports -Wconversion]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wconversion"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wconversion" ], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" -# FLag -pedantic +# Flag -pedantic CFLAGS="-Werror -pedantic" AC_MSG_CHECKING([whether CC and CXX supports -pedantic]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -pedantic"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -pedantic" ], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" -# FLag -Wsign-conversion +# Flag -Wsign-conversion CFLAGS="-Werror -Wsign-conversion" AC_MSG_CHECKING([whether CC supports -Wsign-conversion]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wsign-conversion"], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" +# Flag -Wreserved-id-macro +CFLAGS="-Werror -Wreserved-id-macro" +AC_MSG_CHECKING([whether CC support -Wreserved-id-macro]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wreserved-id-macro"], [AC_MSG_RESULT([no])]) +CFLAGS="$saved_cflags" + +# Flag -Wreserved-identifier +CFLAGS="-Werror -Wreserved-identifier" +AC_MSG_CHECKING([whether CC supports -Wreserved-identifier]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wreserved-identifier"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wreserved-identifier" ], [AC_MSG_RESULT([no])]) +CFLAGS="$saved_cflags" + ##### C++ Warnings -# FLag -Wsign-conversion (for CXX) +# Flag -Wsign-conversion (for CXX) AC_LANG_PUSH([C++]) CXXFLAGS="-Werror -Wsign-conversion" @@ -195,7 +247,7 @@ AC_MSG_CHECKING([whether CXX supports -Wsign-conversion]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wsign-conversion"], [AC_MSG_RESULT([no])]) CXXFLAGS="$saved_cxxflags" -# FLag -Woverloaded-virtual +# Flag -Woverloaded-virtual CXXFLAGS="-Werror -Woverloaded-virtual" AC_MSG_CHECKING([whether CXX supports -Woverloaded-virtual]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Woverloaded-virtual" ], [AC_MSG_RESULT([no])]) @@ -203,7 +255,7 @@ CXXFLAGS="$saved_cxxflags" AC_LANG_POP -# FLag -Wstrict-prototypes +# Flag -Wstrict-prototypes CFLAGS="-Werror -Wstrict-prototypes" AC_MSG_CHECKING([whether CC supports -Wstrict-prototypes]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wstrict-prototypes" ], [AC_MSG_RESULT([no])]) @@ -214,61 +266,58 @@ CFLAGS="$saved_cflags" ##### Less of these warnings # # Disable some warnings as CppUTest has this and can't be prevented at the moment. -# FLag -Wno-disabled-macro-expansion. +# Flag -Wno-disabled-macro-expansion. CFLAGS="-Werror -Wno-disabled-macro-expansion" AC_MSG_CHECKING([whether CC and CXX supports -Wno-disabled-macro-expansion]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wno-disabled-macro-expansion"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-disabled-macro-expansion" ], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" -# FLag -Wno-padded. +# Flag -Wno-padded. CFLAGS="-Werror -Wno-padded" AC_MSG_CHECKING([whether CC and CXX supports -Wno-padded]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wno-padded"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-padded" ], [AC_MSG_RESULT([no])]) CFLAGS="$saved_cflags" -# FLag -Wno-reserved-id-macro. -CFLAGS="-Werror -Wno-reserved-id-macro" -AC_MSG_CHECKING([whether CC and CXX supports -Wno-reserved-id-macro]) -AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wno-reserved-id-macro"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-reserved-id-macro" ], [AC_MSG_RESULT([no])]) -CFLAGS="$saved_cflags" - -# FLag -Wno-keyword-macro. -CFLAGS="-Werror -Wno-keyword-macro" -AC_MSG_CHECKING([whether CC and CXX supports -Wno-keyword-macro]) -AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} -Wno-keyword-macro"; CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-keyword-macro" ], [AC_MSG_RESULT([no])]) -CFLAGS="$saved_cflags" - AC_LANG_PUSH([C++]) -# FLag -Wno-global-constructors. +# Flag -Wno-global-constructors. CXXFLAGS="-Werror -Wno-global-constructors" AC_MSG_CHECKING([whether CXX supports -Wno-global-constructors]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-global-constructors" ], [AC_MSG_RESULT([no])]) CXXFLAGS="$saved_cxxflags" -# FLag -Wno-exit-time-destructors. +# Flag -Wno-exit-time-destructors. CXXFLAGS="-Werror -Wno-exit-time-destructors" AC_MSG_CHECKING([whether CXX supports -Wno-exit-time-destructors]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-exit-time-destructors" ], [AC_MSG_RESULT([no])]) CXXFLAGS="$saved_cxxflags" -# FLag -Wno-weak-vtables. +# Flag -Wno-weak-vtables. CXXFLAGS="-Werror -Wno-weak-vtables" AC_MSG_CHECKING([whether CXX supports -Wno-weak-vtables]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-weak-vtables" ], [AC_MSG_RESULT([no])]) CXXFLAGS="$saved_cxxflags" -# FLag -Wno-old-style-cast. +# Flag -Wno-old-style-cast. CXXFLAGS="-Werror -Wno-old-style-cast" AC_MSG_CHECKING([whether CXX supports -Wno-old-style-cast]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -Wno-old-style-cast" ], [AC_MSG_RESULT([no])]) CXXFLAGS="$saved_cxxflags" +if test "x${memory_leak_detection}" = xyes; then + # GCC's default optimization breaks leak detection: + # https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Dialect-Options.html#index-fassume-sane-operators-new-delete + CXXFLAGS="-Werror -fno-assume-sane-operators-new-delete" + AC_MSG_CHECKING([whether CXX supports -fno-assume-sane-operators-new-delete]) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CXXWARNINGFLAGS="${CPPUTEST_CXXWARNINGFLAGS} -fno-assume-sane-operators-new-delete" ], [AC_MSG_RESULT([no])]) + CXXFLAGS="$saved_cxxflags" +fi + AC_LANG_POP ##################################################### ######## End warning section -# FLag --coverage +# Flag --coverage AC_LANG_PUSH([C++]) CXXFLAGS="-Werror --coverage" AC_MSG_CHECKING([whether CXX and the linker supports --coverage (broken in clang 3.3)]) @@ -285,16 +334,19 @@ AC_LANG_PUSH([C++]) # Can we use operator delete without exception handling specifier? (clang warns on this!) CXXFLAGS="-Werror" AC_MSG_CHECKING([whether CXX supports operator delete without exception handling specifier]) -AC_COMPILE_IFELSE([AC_LANG_PROGRAM([#include \nvoid operator delete(void* mem);])], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]); UT_DELETE_MUST_HAVE_EXCEPTION_SPECIFIER="yes"]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include +void operator delete(void* mem);]])], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]); UT_DELETE_MUST_HAVE_EXCEPTION_SPECIFIER="yes"]) CXXFLAGS="$saved_cxxflags" # Can we use operator new with exception specifier (g++4.7 on MacOSX is broken here) CXXFLAGS="-Werror" AC_MSG_CHECKING([whether CXX supports operator new with exception handling specifier]) -AC_COMPILE_IFELSE([AC_LANG_PROGRAM([#include \nvoid* operator new(size_t size) throw(std::bad_alloc);;])], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]); UT_NEW_CANT_HAVE_EXCEPTION_SPECIFIER="yes"]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include +#include +void* operator new(std::size_t size) throw(std::bad_alloc);;]])], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]); UT_NEW_CANT_HAVE_EXCEPTION_SPECIFIER="yes"]) CXXFLAGS="$saved_cxxflags" -# FLag -Wno-missing-exception-spec +# Flag -Wno-missing-exception-spec CXXFLAGS="-Werror -Wno-missing-exception-spec" AC_MSG_CHECKING([whether CXX supports -Wno-missing-exception-spec]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], [AC_MSG_RESULT([yes]); CPPUTEST_CXX_NO_INC_WARNINGFLAGS="${CPPUTEST_CXX_NO_INC_WARNINGFLAGS} -Wno-missing-exception-spec" ], [AC_MSG_RESULT([no])]) @@ -335,9 +387,21 @@ AC_ARG_ENABLE([std-c], [AC_HELP_STRING([--disable-std-c], [disable the use of St AC_ARG_ENABLE([std-cpp], [AC_HELP_STRING([--disable-std-cpp], [disable the use of Standard C++ Library])], [use_std_cpp=${enableval}], [use_std_cpp=${default_use_std_cpp}]) +AC_ARG_ENABLE([std-cpp98], [AC_HELP_STRING([--enable-std-cpp98], [enable the use of Standard C++ 98 (if the compiler supports that)])], + [use_std_cpp98=${enableval}], [use_std_cpp98=no]) + AC_ARG_ENABLE([std-cpp11], [AC_HELP_STRING([--enable-std-cpp11], [enable the use of Standard C++ 11 (if the compiler supports that)])], [use_std_cpp11=${enableval}], [use_std_cpp11=no]) +AC_ARG_ENABLE([std-cpp14], [AC_HELP_STRING([--enable-std-cpp14], [enable the use of Standard C++ 14 (if the compiler supports that)])], + [use_std_cpp14=${enableval}], [use_std_cpp14=no]) + +AC_ARG_ENABLE([std-cpp17], [AC_HELP_STRING([--enable-std-cpp17], [enable the use of Standard C++ 17 (if the compiler supports that)])], + [use_std_cpp17=${enableval}], [use_std_cpp17=no]) + +AC_ARG_ENABLE([std-cpp20], [AC_HELP_STRING([--enable-std-cpp20], [enable the use of Standard C++ 20 (if the compiler supports that)])], + [use_std_cpp20=${enableval}], [use_std_cpp20=no]) + AC_ARG_ENABLE([cpputest-flags], [AC_HELP_STRING([--disable-cpputest-flags], [disable CFLAGS/CPPFLAGS/CXXFLAGS set by CppUTest])], [cpputest_flags=${enableval}], [cpputest_flags=yes]) @@ -356,6 +420,9 @@ AC_ARG_ENABLE([generate-map-file], [AC_HELP_STRING([--enable-generate-map-file], AC_ARG_ENABLE([coverage], [AC_HELP_STRING([--enable-coverage], [enable running with coverage])], [coverage=${enableval}], [coverage=no]) +AC_ARG_ENABLE([sanitize-address], [AC_HELP_STRING([--enable-sanitize-address], [enable running with address sanitizer])], + [sanitize_address=${enableval}], [sanitize_address=no]) + ############################## Setting options ############################### AM_CONDITIONAL([INCLUDE_CPPUTEST_EXT], [test "x${cpputest_ext}" = xyes]) @@ -383,10 +450,36 @@ if test "x${use_std_cpp}" = xno; then fi fi +cpp_standard_used="default" + +# Using the C++98 standard? +if test "x${use_std_cpp98}" = xyes; then + CPPUTEST_CXXFLAGS="${CPPUTEST_CXXFLAGS} ${CPPUTEST_CPP98FLAG}" + cpp_standard_used="C++98" +fi # Using the C++11 standard? if test "x${use_std_cpp11}" = xyes; then - CPPUTEST_CXXFLAGS="${CPPUTEST_CXXFLAGS} ${CPPUTEST_CPP11FLAG} ${CPPUTEST_CPP11BLACKLIST}" + CPPUTEST_CXXFLAGS="${CPPUTEST_CXXFLAGS} ${CPPUTEST_CPP11FLAG}" + cpp_standard_used="C++11" +fi + +# Using the C++14 standard? +if test "x${use_std_cpp14}" = xyes; then + CPPUTEST_CXXFLAGS="${CPPUTEST_CXXFLAGS} ${CPPUTEST_CPP14FLAG}" + cpp_standard_used="C++14" +fi + +# Using the C++17 standard? +if test "x${use_std_cpp17}" = xyes; then + CPPUTEST_CXXFLAGS="${CPPUTEST_CXXFLAGS} ${CPPUTEST_CPP17FLAG}" + cpp_standard_used="C++17" +fi + +# Using the C++20 standard? +if test "x${use_std_cpp20}" = xyes; then + CPPUTEST_CXXFLAGS="${CPPUTEST_CXXFLAGS} ${CPPUTEST_CPP20FLAG}" + cpp_standard_used="C++20" fi # Dealing with memory leak detection @@ -402,6 +495,13 @@ if test "x${use_longlong}" = xno; then AC_DEFINE([LONG_LONG_DISABLED], 1, [disable long long]) fi +# Dealing with address sanitizer +if test "x${sanitize_address}" = xyes; then + CPPUTEST_CFLAGS="${CPPUTEST_CFLAGS} -fsanitize=address -fno-omit-frame-pointer" + CPPUTEST_CXXFLAGS="${CPPUTEST_CXXFLAGS} -fsanitize=address -fno-omit-frame-pointer" + CPPUTEST_LDFLAGS="${CPPUTEST_CXXFLAGS} -fsanitize=address -fno-omit-frame-pointer" +fi + # Generating map files. if test "x${generate_map_file}" = xyes; then CPPUTEST_LDFLAGS="${CPPUTEST_LDFLAGS} ${CPPUTEST_LD_MAP_GENERATION}" @@ -426,14 +526,19 @@ if test -n "${GMOCK_HOME}"; then AC_DEFINE([INCLUDE_GTEST_TESTS], 1, [Include the GTest-related tests in the build]) AC_ARG_VAR([GMOCK_HOME], [Location of the GMock]) - GTEST_HOME=${GMOCK_HOME}/gtest + + if test -z "${GTEST_HOME}"; then + GTEST_HOME=${GMOCK_HOME}/gtest + fi CPPUTEST_CPPFLAGS="${CPPUTEST_CPPFLAGS} -I${GMOCK_HOME}/include -I${GTEST_HOME}/include -I${GTEST_HOME}" - CPPUTEST_CXXFLAGS="${CPPUTEST_CXXFLAGS} -DGTEST_USE_OWN_TR1_TUPLE=1" + CPPUTEST_CXXFLAGS="${CPPUTEST_CXXFLAGS} -DGTEST_USE_OWN_TR1_TUPLE=1 -DGMOCK_RENAME_MAIN=1" if test -e ${GMOCK_HOME}/lib/libgmock.la && test -e ${GTEST_HOME}/lib/libgtest.la; then \ CPPUTEST_LDADD="${CPPUTEST_LDADD} ${GMOCK_HOME}/lib/libgmock.la ${GTEST_HOME}/lib/libgtest.la"; \ elif test -e ${GMOCK_HOME}/libgmock.a && test -e ${GTEST_HOME}/libgtest.a; then \ CPPUTEST_LDADD="${CPPUTEST_LDADD} ${GMOCK_HOME}/libgmock.a ${GTEST_HOME}/libgtest.a"; \ + elif test -e ${GMOCK_HOME}/libgmock.a && test -e ${GMOCK_HOME}/gtest/libgtest.a; then \ + CPPUTEST_LDADD="${CPPUTEST_LDADD} ${GMOCK_HOME}/libgmock.a ${GMOCK_HOME}/gtest/libgtest.a"; \ else \ AC_MSG_ERROR([ ------------------------------------- @@ -442,12 +547,6 @@ Did you compile it? -------------------------------------]); fi - # In Travis, do not show warnings. The GTest warnings cause a log overflow that errors the build. Nice :) - if test -n "${TRAVIS_BRANCH}"; then - CPPUTEST_CWARNINGFLAGS="" - CPPUTEST_CXXWARNINGFLAGS="" - fi - else # When we don't compile with GMock, we can be a bit stricter on warnings. CPPUTEST_CWARNINGFLAGS="${CPPUTEST_CWARNINGFLAGS} ${CPPUTEST_CWARNINGFLAGS_STRICT}" @@ -499,6 +598,7 @@ LT_INIT AC_CONFIG_FILES([Makefile]) AC_OUTPUT + echo \ "---------------------------------------------------------------- @@ -507,6 +607,8 @@ ${PACKAGE_NAME} Version ${PACKAGE_VERSION} Current compiler options: CC: ${CC} CXX: ${CXX} + CC version: ${ax_cv_c_compiler_version} + CXX version: ${ax_cv_cxx_compiler_version} LD: ${LD} Default CFLAGS: ${CFLAGS} Default CXXFLAGS: ${CXXFLAGS} @@ -517,10 +619,12 @@ Current compiler options: CppUTest LIB: ${LIBS} Features configured in ${PACKAGE_NAME}: + C++ standard used: ${cpp_standard_used} Memory Leak Detection: ${memory_leak_detection} Compiling extensions: ${cpputest_ext} Use Long Long (if available): ${use_longlong} Disable CppUTest compile/link flags: ${cpputest_flags} + Address sanitizer: ${sanitize_address} Using Standard C++ Library: ${use_std_cpp} Using Standard C Library: ${use_std_c} diff --git a/cpputest_build/.gitignore b/cpputest_build/.gitignore deleted file mode 100644 index d6b7ef32c..000000000 --- a/cpputest_build/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore diff --git a/docker/Dockerfile.dos b/docker/Dockerfile.dos new file mode 100644 index 000000000..c09f28fd9 --- /dev/null +++ b/docker/Dockerfile.dos @@ -0,0 +1,9 @@ +FROM ubuntu + +RUN apt-get -qq update && apt-get -qq install -y --no-install-recommends dosbox make openssl ca-certificates git + +WORKDIR /cpputest_build + +COPY ../ /cpputest + +CMD ["/cpputest/scripts/dos_build_test.sh"] diff --git a/docker/Dockerfile.ubuntu b/docker/Dockerfile.ubuntu new file mode 100644 index 000000000..b6bbf152c --- /dev/null +++ b/docker/Dockerfile.ubuntu @@ -0,0 +1,10 @@ +FROM ubuntu + +RUN apt-get update && \ + apt-get install -y -q --no-install-recommends file git gcc g++ make automake autoconf libtool + +WORKDIR /cpputest_build + +COPY ../ /cpputest + +CMD ["bash", "-c", "autoreconf -i /cpputest && /cpputest/configure && make tdd"] diff --git a/docs/WalkThrough_VS21010.docx b/docs/WalkThrough_VS21010.docx deleted file mode 100644 index 1927edb26..000000000 Binary files a/docs/WalkThrough_VS21010.docx and /dev/null differ diff --git a/examples/AllTests/AllTests.cpp b/examples/AllTests/AllTests.cpp index 5ff9de3b1..7d17d6f3d 100644 --- a/examples/AllTests/AllTests.cpp +++ b/examples/AllTests/AllTests.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,12 +34,12 @@ class MyDummyComparator : public MockNamedValueComparator { public: - virtual bool isEqual(const void* object1, const void* object2) + virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { return object1 == object2; } - virtual SimpleString valueToString(const void* object) + virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { return StringFrom(object); } diff --git a/examples/AllTests/AllTests.dsp b/examples/AllTests/AllTests.dsp deleted file mode 100644 index 517b5bf08..000000000 --- a/examples/AllTests/AllTests.dsp +++ /dev/null @@ -1,141 +0,0 @@ -# Microsoft Developer Studio Project File - Name="AllTests" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=AllTests - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "AllTests.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "AllTests.mak" CFG="AllTests - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "AllTests - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "AllTests - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "AllTests - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W3 /GX /O2 /I "..\..\include" /I "..\ApplicationLib" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "CPPUTEST_MEM_LEAK_DETECTION_DISABLED" /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 ..\..\lib\CppUTest.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib /nologo /subsystem:console /incremental:yes /machine:I386 -# Begin Special Build Tool -TargetPath=.\Release\AllTests.exe -SOURCE="$(InputPath)" -PostBuild_Cmds=$(TargetPath) -# End Special Build Tool - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /MDd /W3 /GX /ZI /Od /I "..\..\include" /I "..\ApplicationLib" /FI"CppUTest/MemoryLeakDetectorMallocMacros.h" /FI"CppUTest/MemoryLeakDetectorNewMacros.h" /D "_CONSOLE" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "CPPUTEST_MEM_LEAK_DETECTION_DISABLED" /FR /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 ..\..\lib\CppUTestd.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# SUBTRACT LINK32 /incremental:no -# Begin Special Build Tool -TargetPath=.\Debug\AllTests.exe -SOURCE="$(InputPath)" -PostBuild_Cmds=$(TargetPath) -v -# End Special Build Tool - -!ENDIF - -# Begin Target - -# Name "AllTests - Win32 Release" -# Name "AllTests - Win32 Debug" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\AllTests.cpp -# End Source File -# Begin Source File - -SOURCE=.\CircularBufferTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\EventDispatcherTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\HelloTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\MockDocumentationTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\PrinterTest.cpp -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=.\AllTests.h -# End Source File -# Begin Source File - -SOURCE=.\MockPrinter.h -# End Source File -# End Group -# Begin Group "Resource Files" - -# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" -# End Group -# End Target -# End Project diff --git a/examples/AllTests/AllTests.h b/examples/AllTests/AllTests.h index aebcc310d..9902c6f17 100644 --- a/examples/AllTests/AllTests.h +++ b/examples/AllTests/AllTests.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -25,8 +25,8 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -IMPORT_TEST_GROUP( Printer); -IMPORT_TEST_GROUP( CircularBuffer); -IMPORT_TEST_GROUP( HelloWorld); -IMPORT_TEST_GROUP( EventDispatcher); -IMPORT_TEST_GROUP( MockDocumentation); +IMPORT_TEST_GROUP(Printer); +IMPORT_TEST_GROUP(CircularBuffer); +IMPORT_TEST_GROUP(HelloWorld); +IMPORT_TEST_GROUP(EventDispatcher); +IMPORT_TEST_GROUP(MockDocumentation); diff --git a/examples/AllTests/AllTests.vcproj b/examples/AllTests/AllTests.vcproj index 4d1be1530..ad9ab2b72 100644 --- a/examples/AllTests/AllTests.vcproj +++ b/examples/AllTests/AllTests.vcproj @@ -45,7 +45,7 @@ :/wd4723> +) + +target_link_libraries(ExampleTests + PRIVATE + ApplicationLib + CppUTest::CppUTestExt +) + +include(CppUTest) +cpputest_discover_tests(ExampleTests) diff --git a/examples/AllTests/CircularBufferTest.cpp b/examples/AllTests/CircularBufferTest.cpp index 7554385ce..4602e5ab9 100644 --- a/examples/AllTests/CircularBufferTest.cpp +++ b/examples/AllTests/CircularBufferTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,27 +30,28 @@ #include "CircularBuffer.h" TEST_GROUP(CircularBuffer) -{ CircularBuffer* buffer; - -void setup() -{ - buffer = new CircularBuffer(); -} -void teardown() -{ - delete buffer; -} - -void fillTheQueue(int seed, int howMany) { - for (int i = 0; i < howMany; i++) - buffer->Put(seed + i); -} -void removeFromQueue(int howMany) -{ - for (int i = 0; i < howMany; i++) - buffer->Get(); -} + CircularBuffer* buffer; + + void setup() CPPUTEST_OVERRIDE + { + buffer = new CircularBuffer(); + } + void teardown() CPPUTEST_OVERRIDE + { + delete buffer; + } + + void fillTheQueue(int seed, int howMany) + { + for (int i = 0; i < howMany; i++) + buffer->Put(seed + i); + } + void removeFromQueue(int howMany) + { + for (int i = 0; i < howMany; i++) + buffer->Get(); + } }; TEST(CircularBuffer, EmptyAfterCreation) @@ -134,15 +135,14 @@ TEST(CircularBuffer, PutToFull) buffer->Put(9999); for (int i = 0; i < buffer->Capacity() - 1; i++) - LONGS_EQUAL(i+900+1, buffer->Get()); + LONGS_EQUAL(i + 900 + 1, buffer->Get()); LONGS_EQUAL(9999, buffer->Get()); CHECK(buffer->IsEmpty()); } -//Sometime people ask what tests the tests. -//Do you know the answer - +// Sometime people ask what tests the tests. +// Do you know the answer TEST(CircularBuffer, GetFromEmpty) { @@ -162,8 +162,7 @@ TEST(CircularBuffer, PrintEmpty) Printer* p = &mock; buffer->Print(p); - STRCMP_EQUAL("Circular buffer content:\n<>\n", - mock.getOutput().c_str()); + STRCMP_EQUAL("Circular buffer content:\n<>\n", mock.getOutput().c_str()); } TEST(CircularBuffer, PrintAfterOnePut) @@ -172,8 +171,7 @@ TEST(CircularBuffer, PrintAfterOnePut) buffer->Put(1); buffer->Print(&mock); - STRCMP_EQUAL("Circular buffer content:\n<1>\n", - mock.getOutput().c_str()); + STRCMP_EQUAL("Circular buffer content:\n<1>\n", mock.getOutput().c_str()); } TEST(CircularBuffer, PrintNotYetWrappedOrFull) @@ -184,8 +182,7 @@ TEST(CircularBuffer, PrintNotYetWrappedOrFull) buffer->Put(2); buffer->Put(3); buffer->Print(&mock); - STRCMP_EQUAL("Circular buffer content:\n<1, 2, 3>\n", - mock.getOutput().c_str()); + STRCMP_EQUAL("Circular buffer content:\n<1, 2, 3>\n", mock.getOutput().c_str()); } TEST(CircularBuffer, PrintNotYetWrappedAndIsFull) @@ -195,7 +192,8 @@ TEST(CircularBuffer, PrintNotYetWrappedAndIsFull) fillTheQueue(200, buffer->Capacity()); buffer->Print(&mock); - const char* expected = "Circular buffer content:\n" + const char* expected = + "Circular buffer content:\n" "<200, 201, 202, 203, 204>\n"; STRCMP_EQUAL(expected, mock.getOutput().c_str()); @@ -210,7 +208,8 @@ TEST(CircularBuffer, PrintWrappedAndIsFullOldestToNewest) buffer->Put(999); buffer->Print(&mock); - const char* expected = "Circular buffer content:\n" + const char* expected = + "Circular buffer content:\n" "<201, 202, 203, 204, 999>\n"; STRCMP_EQUAL(expected, mock.getOutput().c_str()); @@ -224,7 +223,8 @@ TEST(CircularBuffer, PrintWrappedAndFullOverwriteOldest) buffer->Put(9999); buffer->Print(&mock); - const char* expected = "Circular buffer content:\n" + const char* expected = + "Circular buffer content:\n" "<201, 202, 203, 204, 9999>\n"; STRCMP_EQUAL(expected, mock.getOutput().c_str()); @@ -240,7 +240,8 @@ TEST(CircularBuffer, PrintBoundary) fillTheQueue(300, buffer->Capacity() - 1); buffer->Print(&mock); - const char* expected = "Circular buffer content:\n" + const char* expected = + "Circular buffer content:\n" "<888, 300, 301, 302, 303>\n"; STRCMP_EQUAL(expected, mock.getOutput().c_str()); @@ -253,7 +254,8 @@ TEST(CircularBuffer, FillEmptyThenPrint) fillTheQueue(200, buffer->Capacity()); removeFromQueue(buffer->Capacity()); buffer->Print(&mock); - const char* expected = "Circular buffer content:\n" + const char* expected = + "Circular buffer content:\n" "<>\n"; STRCMP_EQUAL(expected, mock.getOutput().c_str()); diff --git a/examples/AllTests/EventDispatcherTest.cpp b/examples/AllTests/EventDispatcherTest.cpp index e414bc759..7ea4b52a4 100644 --- a/examples/AllTests/EventDispatcherTest.cpp +++ b/examples/AllTests/EventDispatcherTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -25,18 +25,32 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#if CPPUTEST_USE_NEW_MACROS + #undef realloc + #undef new +#endif + +#include "EventDispatcher.h" + +#if CPPUTEST_USE_NEW_MACROS + #include "CppUTest/MemoryLeakDetectorNewMacros.h" +#endif + #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" -#include "EventDispatcher.h" class ObserverMock : public EventObserver { public: - virtual void notify(const Event& event, int timeOutInSeconds) + virtual void notify(const Event& event, int timeOutInSeconds) CPPUTEST_OVERRIDE { - mock().actualCall("notify").onObject(this).withParameterOfType("Event", "event", (void*) &event).withParameter("timeOutInSeconds", timeOutInSeconds); + mock() + .actualCall("notify") + .onObject(this) + .withParameterOfType("Event", "event", (void*)&event) + .withParameter("timeOutInSeconds", timeOutInSeconds); } - virtual void notifyRegistration(EventObserver* newObserver) + virtual void notifyRegistration(EventObserver* newObserver) CPPUTEST_OVERRIDE { mock().actualCall("notifyRegistration").onObject(this).withParameter("newObserver", newObserver); } @@ -45,17 +59,16 @@ class ObserverMock : public EventObserver class EventComparator : public MockNamedValueComparator { public: - virtual bool isEqual(const void* object1, const void* object2) + virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { - return ((Event*)object1)->type == ((Event*)object2)->type; + return ((const Event*)object1)->type == ((const Event*)object2)->type; } - virtual SimpleString valueToString(const void* object) + virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { - return StringFrom(((Event*)object)->type); + return StringFrom(((const Event*)object)->type); } }; - TEST_GROUP(EventDispatcher) { Event event; @@ -64,19 +77,18 @@ TEST_GROUP(EventDispatcher) ObserverMock observer2; EventComparator eventComparator; - void setup() + void setup() CPPUTEST_OVERRIDE { dispatcher = new EventDispatcher; mock().installComparator("Event", eventComparator); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete dispatcher; mock().removeAllComparatorsAndCopiers(); } }; - TEST(EventDispatcher, EventWithoutRegistrationsResultsIntoNoCalls) { dispatcher->dispatchEvent(event, 10); @@ -84,7 +96,11 @@ TEST(EventDispatcher, EventWithoutRegistrationsResultsIntoNoCalls) TEST(EventDispatcher, EventWithRegistrationForEventResultsIntoCallback) { - mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10); + mock() + .expectOneCall("notify") + .onObject(&observer) + .withParameterOfType("Event", "event", &event) + .withParameter("timeOutInSeconds", 10); event.type = IMPORTANT_EVENT; dispatcher->registerObserver(IMPORTANT_EVENT, &observer); @@ -100,8 +116,16 @@ TEST(EventDispatcher, DifferentEventWithRegistrationDoesNotResultIntoCallback) TEST(EventDispatcher, RegisterTwoObserversResultIntoTwoCallsAndARegistrationNotification) { - mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10); - mock().expectOneCall("notify").onObject(&observer2).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10); + mock() + .expectOneCall("notify") + .onObject(&observer) + .withParameterOfType("Event", "event", &event) + .withParameter("timeOutInSeconds", 10); + mock() + .expectOneCall("notify") + .onObject(&observer2) + .withParameterOfType("Event", "event", &event) + .withParameter("timeOutInSeconds", 10); mock().expectOneCall("notifyRegistration").onObject(&observer).withParameter("newObserver", &observer2); event.type = IMPORTANT_EVENT; diff --git a/examples/AllTests/FEDemoTest.cpp b/examples/AllTests/FEDemoTest.cpp index 7259c4ec6..c2f6c17f2 100644 --- a/examples/AllTests/FEDemoTest.cpp +++ b/examples/AllTests/FEDemoTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -28,9 +28,9 @@ #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" -#include "CppUTestExt/IEEE754ExceptionsPlugin.h" -#ifdef CPPUTEST_HAVE_FENV +#if CPPUTEST_HAVE_FENV + #include "CppUTestExt/IEEE754ExceptionsPlugin.h" /* * To see a demonstration of tests failing as a result of IEEE754ExceptionsPlugin @@ -42,43 +42,43 @@ extern "C" { #include } -#include - -static volatile float f; + #include TEST_GROUP(FE_Demo) { - void setup() + void setup() CPPUTEST_OVERRIDE { IEEE754ExceptionsPlugin::disableInexact(); } }; -IGNORE_TEST(FE_Demo, should_fail_when__FE_DIVBYZERO__is_set) +IGNORE_TEST(FE_Demo, should_fail_when_FE_DIVBYZERO_is_set) { - f = 1.0f; + float f = 1.0f; CHECK((f /= 0.0f) >= std::numeric_limits::infinity()); } -IGNORE_TEST(FE_Demo, should_fail_when__FE_UNDERFLOW__is_set) +IGNORE_TEST(FE_Demo, should_fail_when_FE_UNDERFLOW_is_set) { - f = 0.01f; - while (f > 0.0f) f *= f; + volatile float f = 0.01f; + while (f > 0.0f) + f = f * f; CHECK(f == 0.0f); } -IGNORE_TEST(FE_Demo, should_fail_when__FE_OVERFLOW__is_set) +IGNORE_TEST(FE_Demo, should_fail_when_FE_OVERFLOW_is_set) { - f = 1000.0f; - while (f < std::numeric_limits::infinity()) f *= f; + volatile float f = 1000.0f; + while (f < std::numeric_limits::infinity()) + f = f * f; CHECK(f >= std::numeric_limits::infinity()); } -IGNORE_TEST(FE_Demo, should_fail_when__FE_INEXACT____is_set) +IGNORE_TEST(FE_Demo, should_fail_when_FE_INEXACT_is_set) { IEEE754ExceptionsPlugin::enableInexact(); - f = 10.0f; - DOUBLES_EQUAL((double) (f / 3.0f), (double) 3.333f, (double) 0.001f); + float f = 10.0f; + DOUBLES_EQUAL((double)(f / 3.0f), (double)3.333f, (double)0.001f); } TEST(FE_Demo, should_succeed_when_no_flags_are_set) diff --git a/examples/AllTests/HelloTest.cpp b/examples/AllTests/HelloTest.cpp index 84407906d..7bc644e0e 100644 --- a/examples/AllTests/HelloTest.cpp +++ b/examples/AllTests/HelloTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,23 +34,24 @@ static SimpleString* buffer; TEST_GROUP(HelloWorld) -{ static int output_method(const char* output, ...) { - va_list arguments; - va_start(arguments, output); - *buffer = VStringFromFormat(output, arguments); - va_end(arguments); - return 1; -} -void setup() -{ - buffer = new SimpleString(); - UT_PTR_SET(PrintFormated, &output_method); -} -void teardown() -{ - delete buffer; -} + static int output_method(const char* output, ...) + { + va_list arguments; + va_start(arguments, output); + *buffer = VStringFromFormat(output, arguments); + va_end(arguments); + return 1; + } + void setup() CPPUTEST_OVERRIDE + { + buffer = new SimpleString(); + UT_PTR_SET(PrintFormated, &output_method); + } + void teardown() CPPUTEST_OVERRIDE + { + delete buffer; + } }; TEST(HelloWorld, PrintOk) diff --git a/examples/AllTests/MockDocumentationTest.cpp b/examples/AllTests/MockDocumentationTest.cpp index e2b79d726..0bd578ea8 100644 --- a/examples/AllTests/MockDocumentationTest.cpp +++ b/examples/AllTests/MockDocumentationTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -25,7 +25,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" #include "CppUTestExt/MockSupport_c.h" @@ -36,15 +35,14 @@ TEST_GROUP(FirstTestGroup) TEST(FirstTestGroup, FirsTest) { -// FAIL("Fail me!"); + // FAIL("Fail me!"); } TEST(FirstTestGroup, SecondTest) { -// STRCMP_EQUAL("hello", "world"); + // STRCMP_EQUAL("hello", "world"); } - TEST_GROUP(MockDocumentation) { }; @@ -64,14 +62,14 @@ TEST(MockDocumentation, SimpleScenario) class ClassFromProductionCode { public: - virtual void importantFunction(){} + virtual void importantFunction() {} virtual ~ClassFromProductionCode() {} }; class ClassFromProductionCodeMock : public ClassFromProductionCode { public: - virtual void importantFunction() + virtual void importantFunction() CPPUTEST_OVERRIDE { mock().actualCall("importantFunction").onObject(this); } @@ -90,13 +88,13 @@ TEST(MockDocumentation, SimpleScenarioObject) static void parameters_function(int p1, const char* p2) { - void* object = (void*) 1; + void* object = (void*)1; mock().actualCall("function").onObject(object).withParameter("p1", p1).withParameter("p2", p2); } TEST(MockDocumentation, parameters) { - void* object = (void*) 1; + void* object = (void*)1; mock().expectOneCall("function").onObject(object).withParameter("p1", 2).withParameter("p2", "hah"); parameters_function(2, "hah"); } @@ -104,11 +102,11 @@ TEST(MockDocumentation, parameters) class MyTypeComparator : public MockNamedValueComparator { public: - virtual bool isEqual(const void* object1, const void* object2) + virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { return object1 == object2; } - virtual SimpleString valueToString(const void* object) + virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { return StringFrom(object); } @@ -116,7 +114,7 @@ class MyTypeComparator : public MockNamedValueComparator TEST(MockDocumentation, ObjectParameters) { - void* object = (void*) 1; + void* object = (void*)1; MyTypeComparator comparator; mock().installComparator("myType", comparator); mock().expectOneCall("function").withParameterOfType("myType", "parameterName", object); @@ -127,8 +125,8 @@ TEST(MockDocumentation, ObjectParameters) TEST(MockDocumentation, returnValue) { mock().expectOneCall("function").andReturnValue(10); - int value = mock().actualCall("function").returnValue().getIntValue(); - value = mock().returnValue().getIntValue(); + mock().actualCall("function").returnValue().getIntValue(); + int value = mock().returnValue().getIntValue(); LONGS_EQUAL(10, value); } @@ -138,22 +136,20 @@ TEST(MockDocumentation, setData) mock().setData("importantValue", 10); mock().setDataObject("importantObject", "ClassFromProductionCode", &object); - ClassFromProductionCode * pobject; + ClassFromProductionCode* pobject; int value = mock().getData("importantValue").getIntValue(); - pobject = (ClassFromProductionCode*) mock().getData("importantObject").getObjectPointer(); + pobject = (ClassFromProductionCode*)mock().getData("importantObject").getObjectPointer(); LONGS_EQUAL(10, value); POINTERS_EQUAL(pobject, &object); } -static void doSomethingThatWouldOtherwiseBlowUpTheMockingFramework() -{ -} +static void doSomethingThatWouldOtherwiseBlowUpTheMockingFramework() {} TEST(MockDocumentation, otherMockSupport) { mock().crashOnFailure(); -// mock().actualCall("unex"); + // mock().actualCall("unex"); mock().expectOneCall("foo"); mock().ignoreOtherCalls(); @@ -163,7 +159,6 @@ TEST(MockDocumentation, otherMockSupport) mock().enable(); mock().clear(); - } TEST(MockDocumentation, scope) @@ -174,7 +169,7 @@ TEST(MockDocumentation, scope) mock("xmlparser").actualCall("open"); } -static int equalMethod(const void* object1, const void* object2) +static int equalMethod(const void* object1, const void* object2) { return object1 == object2; } @@ -186,13 +181,12 @@ static const char* toStringMethod(const void*) TEST(MockDocumentation, CInterface) { - void* object = (void*) 0x1; + void* object = (void*)0x1; mock_c()->expectOneCall("foo")->withIntParameters("integer", 10)->andReturnDoubleValue(1.11); double d = mock_c()->actualCall("foo")->withIntParameters("integer", 10)->returnValue().value.doubleValue; DOUBLES_EQUAL(1.11, d, 0.00001); - mock_c()->installComparator("type", equalMethod, toStringMethod); mock_scope_c("scope")->expectOneCall("bar")->withParameterOfType("type", "name", object); mock_scope_c("scope")->actualCall("bar")->withParameterOfType("type", "name", object); @@ -205,12 +199,12 @@ TEST(MockDocumentation, CInterface) TEST_GROUP(FooTestGroup) { - void setup() + void setup() CPPUTEST_OVERRIDE { // Init stuff } - void teardown() + void teardown() CPPUTEST_OVERRIDE { // Uninit stuff } @@ -228,7 +222,7 @@ TEST(FooTestGroup, MoreFoo) TEST_GROUP(BarTestGroup) { - void setup() + void setup() CPPUTEST_OVERRIDE { // Init Bar } diff --git a/examples/AllTests/MockPrinter.h b/examples/AllTests/MockPrinter.h index 90dd435d5..1df48962f 100644 --- a/examples/AllTests/MockPrinter.h +++ b/examples/AllTests/MockPrinter.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -40,22 +40,18 @@ #include #include -class MockPrinter: public Printer +class MockPrinter : public Printer { public: - explicit MockPrinter() - { - } - virtual ~MockPrinter() - { - } + explicit MockPrinter() {} + virtual ~MockPrinter() CPPUTEST_DESTRUCTOR_OVERRIDE {} - virtual void Print(const char* s) + virtual void Print(const char* s) CPPUTEST_OVERRIDE { savedOutput.append(s); } - virtual void Print(long int value) + virtual void Print(long int value) CPPUTEST_OVERRIDE { SimpleString buffer; buffer = StringFromFormat("%ld", value); @@ -68,12 +64,10 @@ class MockPrinter: public Printer } private: - std::string savedOutput; MockPrinter(const MockPrinter&); MockPrinter& operator=(const MockPrinter&); - }; -#endif // D_MockPrinter_H +#endif // D_MockPrinter_H diff --git a/examples/AllTests/PrinterTest.cpp b/examples/AllTests/PrinterTest.cpp index 1f872597a..88a5d1ca3 100644 --- a/examples/AllTests/PrinterTest.cpp +++ b/examples/AllTests/PrinterTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,18 +30,19 @@ #include "MockPrinter.h" TEST_GROUP(Printer) -{ Printer* printer; -MockPrinter* mockPrinter; - -void setup() -{ - mockPrinter = new MockPrinter(); - printer = mockPrinter; -} -void teardown() { - delete printer; -} + Printer* printer; + MockPrinter* mockPrinter; + + void setup() CPPUTEST_OVERRIDE + { + mockPrinter = new MockPrinter(); + printer = mockPrinter; + } + void teardown() CPPUTEST_OVERRIDE + { + delete printer; + } }; TEST(Printer, PrintConstCharStar) @@ -65,4 +66,3 @@ TEST(Printer, StreamOperators) const char* expected = "n=1234"; CHECK_EQUAL(expected, mockPrinter->getOutput()); } - diff --git a/examples/ApplicationLib/ApplicationLib.dsp b/examples/ApplicationLib/ApplicationLib.dsp deleted file mode 100644 index a0887d230..000000000 --- a/examples/ApplicationLib/ApplicationLib.dsp +++ /dev/null @@ -1,124 +0,0 @@ -# Microsoft Developer Studio Project File - Name="ApplicationLib" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Static Library" 0x0104 - -CFG=ApplicationLib - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "ApplicationLib.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "ApplicationLib.mak" CFG="ApplicationLib - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "ApplicationLib - Win32 Release" (based on "Win32 (x86) Static Library") -!MESSAGE "ApplicationLib - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "ApplicationLib - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c -# ADD CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ELSEIF "$(CFG)" == "ApplicationLib - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c -# ADD CPP /nologo /MDd /W3 /GX /ZI /Od /I "../../include" /I "../../include/Platforms/VisualCpp" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ENDIF - -# Begin Target - -# Name "ApplicationLib - Win32 Release" -# Name "ApplicationLib - Win32 Debug" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\CircularBuffer.cpp -# End Source File -# Begin Source File - -SOURCE=.\EventDispatcher.cpp -# End Source File -# Begin Source File - -SOURCE=.\hello.c -# End Source File -# Begin Source File - -SOURCE=.\Printer.cpp -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=.\CircularBuffer.h -# End Source File -# Begin Source File - -SOURCE=.\ExamplesNewOverrides.h -# End Source File -# Begin Source File - -SOURCE=.\hello.h -# End Source File -# Begin Source File - -SOURCE=.\Printer.h -# End Source File -# End Group -# End Target -# End Project diff --git a/examples/ApplicationLib/ApplicationLib.vcproj b/examples/ApplicationLib/ApplicationLib.vcproj index bf83e4718..f7b054bbe 100644 --- a/examples/ApplicationLib/ApplicationLib.vcproj +++ b/examples/ApplicationLib/ApplicationLib.vcproj @@ -42,7 +42,7 @@ BE LIABLE FOR ANY @@ -27,11 +27,11 @@ #include "CircularBuffer.h" #include "Printer.h" +#include -CircularBuffer::CircularBuffer(int _capacity) : - index(0), outdex(0), capacity(_capacity), empty(true), full(false) +CircularBuffer::CircularBuffer(int _capacity) : index(0), outdex(0), capacity(_capacity), empty(true), full(false) { - buffer = new int[this->capacity]; + buffer = new int[(size_t)this->capacity]; } CircularBuffer::~CircularBuffer() @@ -54,8 +54,10 @@ void CircularBuffer::Put(int i) empty = false; buffer[index] = i; index = Next(index); - if (full) outdex = Next(outdex); - else if (index == outdex) full = true; + if (full) + outdex = Next(outdex); + else if (index == outdex) + full = true; } int CircularBuffer::Get() @@ -66,7 +68,8 @@ int CircularBuffer::Get() if (!empty) { result = buffer[outdex]; outdex = Next(outdex); - if (outdex == index) empty = true; + if (outdex == index) + empty = true; } return result; } @@ -78,7 +81,8 @@ int CircularBuffer::Capacity() int CircularBuffer::Next(int i) { - if (++i >= capacity) i = 0; + if (++i >= capacity) + i = 0; return i; } @@ -89,12 +93,14 @@ void CircularBuffer::Print(Printer* p) int printIndex = outdex; int count = index - outdex; - if (!empty && (index <= outdex)) count = capacity - (outdex - index); + if (!empty && (index <= outdex)) + count = capacity - (outdex - index); for (int i = 0; i < count; i++) { p->Print(buffer[printIndex]); printIndex = Next(printIndex); - if (i + 1 != count) p->Print(", "); + if (i + 1 != count) + p->Print(", "); } p->Print(">\n"); } diff --git a/examples/ApplicationLib/CircularBuffer.h b/examples/ApplicationLib/CircularBuffer.h index e804c29ba..e9634f10a 100644 --- a/examples/ApplicationLib/CircularBuffer.h +++ b/examples/ApplicationLib/CircularBuffer.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -52,7 +52,6 @@ class CircularBuffer void Print(Printer*); private: - int index; int outdex; int* buffer; @@ -66,7 +65,6 @@ class CircularBuffer CircularBuffer(const CircularBuffer&); CircularBuffer& operator=(const CircularBuffer&); - }; -#endif // D_CircularBuffer_H +#endif // D_CircularBuffer_H diff --git a/examples/ApplicationLib/EventDispatcher.cpp b/examples/ApplicationLib/EventDispatcher.cpp index ef5ebbcba..140be3547 100644 --- a/examples/ApplicationLib/EventDispatcher.cpp +++ b/examples/ApplicationLib/EventDispatcher.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -28,9 +28,7 @@ #include "EventDispatcher.h" using namespace std; -EventDispatcher::EventDispatcher() -{ -} +EventDispatcher::EventDispatcher() {} void EventDispatcher::registerObserver(EventType type, EventObserver* observer) { @@ -42,8 +40,7 @@ void EventDispatcher::registerObserver(EventType type, EventObserver* observer) void EventDispatcher::dispatchEvent(const Event& event, int timeoutSeconds) { - for (list >::iterator i = observerList_.begin(); i != observerList_.end(); i++) - { + for (list >::iterator i = observerList_.begin(); i != observerList_.end(); i++) { if (i->first == event.type) i->second->notify(event, timeoutSeconds); } diff --git a/examples/ApplicationLib/EventDispatcher.h b/examples/ApplicationLib/EventDispatcher.h index 06e2c687c..a27eb056f 100644 --- a/examples/ApplicationLib/EventDispatcher.h +++ b/examples/ApplicationLib/EventDispatcher.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -25,8 +25,8 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef EVENTDISPATCHER__H -#define EVENTDISPATCHER__H +#ifndef EVENTDISPATCHER_H +#define EVENTDISPATCHER_H #include @@ -45,14 +45,15 @@ class Event class EventObserver { public: - virtual void notify(const Event& event, int timeOutInSeconds)=0; - virtual void notifyRegistration(EventObserver* newObserver)=0; + virtual void notify(const Event& event, int timeOutInSeconds) = 0; + virtual void notifyRegistration(EventObserver* newObserver) = 0; virtual ~EventObserver() {} }; class EventDispatcher { std::list > observerList_; + public: EventDispatcher(); diff --git a/examples/ApplicationLib/ExamplesNewOverrides.h b/examples/ApplicationLib/ExamplesNewOverrides.h index ad108fc7a..86cb0219b 100644 --- a/examples/ApplicationLib/ExamplesNewOverrides.h +++ b/examples/ApplicationLib/ExamplesNewOverrides.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/examples/ApplicationLib/Printer.cpp b/examples/ApplicationLib/Printer.cpp index af9c9266d..893ae1a40 100644 --- a/examples/ApplicationLib/Printer.cpp +++ b/examples/ApplicationLib/Printer.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -28,13 +28,9 @@ #include "Printer.h" #include -Printer::Printer() -{ -} +Printer::Printer() {} -Printer::~Printer() -{ -} +Printer::~Printer() {} void Printer::Print(const char* s) { @@ -44,7 +40,7 @@ void Printer::Print(const char* s) void Printer::Print(long int n) { - printf("%ld", n); + printf("%ld", n); } Printer& operator<<(Printer& p, const char* s) diff --git a/examples/ApplicationLib/Printer.h b/examples/ApplicationLib/Printer.h index dcfc59ccd..51aa63313 100644 --- a/examples/ApplicationLib/Printer.h +++ b/examples/ApplicationLib/Printer.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -44,13 +44,11 @@ class Printer virtual void Print(long int); private: - Printer(const Printer&); Printer& operator=(const Printer&); - }; Printer& operator<<(Printer&, const char*); Printer& operator<<(Printer&, long int); -#endif // D_Printer_H +#endif // D_Printer_H diff --git a/examples/ApplicationLib/hello.c b/examples/ApplicationLib/hello.c index 6cbe03f44..2ab67a69c 100644 --- a/examples/ApplicationLib/hello.c +++ b/examples/ApplicationLib/hello.c @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -28,7 +28,7 @@ #include #include "hello.h" -void printHelloWorld() +void printHelloWorld(void) { PrintFormated("Hello World!\n"); } diff --git a/examples/ApplicationLib/hello.h b/examples/ApplicationLib/hello.h index 5154b3cf1..83524a5c0 100644 --- a/examples/ApplicationLib/hello.h +++ b/examples/ApplicationLib/hello.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt new file mode 100644 index 000000000..98244cee6 --- /dev/null +++ b/examples/CMakeLists.txt @@ -0,0 +1,20 @@ +cmake_minimum_required(VERSION 3.8...3.31) + +project(CppUTestExample) + +if (CMAKE_VERSION GREATER_EQUAL "3.21") + # PROJECT_IS_TOP_LEVEL is defined automatically +elseif(CMAKE_CURRENT_BINARY_DIR STREQUAL CMAKE_BINARY_DIR) + set(PROJECT_IS_TOP_LEVEL TRUE) +else() + set(PROJECT_IS_TOP_LEVEL FALSE) +endif() + +if(PROJECT_IS_TOP_LEVEL) + find_package(CppUTest 4.0 REQUIRED) +endif() + +include(CTest) + +add_subdirectory(AllTests) +add_subdirectory(ApplicationLib) diff --git a/examples/CppUTestExample.dsw b/examples/CppUTestExample.dsw deleted file mode 100644 index 98f732660..000000000 --- a/examples/CppUTestExample.dsw +++ /dev/null @@ -1,44 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "AllTests"=.\AllTests\AllTests.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ - Begin Project Dependency - Project_Dep_Name ApplicationLib - End Project Dependency -}}} - -############################################################################### - -Project: "ApplicationLib"=.\ApplicationLib\ApplicationLib.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/examples/Makefile_ExamplesWithCppUTestInstalled.mk b/examples/Makefile_ExamplesWithCppUTestInstalled.mk new file mode 100644 index 000000000..e42992fb9 --- /dev/null +++ b/examples/Makefile_ExamplesWithCppUTestInstalled.mk @@ -0,0 +1,26 @@ + +CPPFLAGS += -I /usr/local/include +LD_LIBRARIES = -L/usr/local/lib -lCppUTest -lCppUTestExt + +VPATH = ApplicationLib AllTests + +APPLIB_OBJECTS = CircularBuffer.o EventDispatcher.o hello.o Printer.o +TEST_OBJECTS = AllTests.o CircularBufferTest.o EventDispatcherTest.o FEDemoTest.o HelloTest.o MockDocumentationTest.o PrinterTest.o + +CPPFLAGS += -I ApplicationLib + +TEST_TARGET = CppUTestExamples +APPLIB = applicationLib.a + +$(TEST_TARGET): $(TEST_OBJECTS) applicationLib.a + $(CXX) -o $@ $^ $(LD_LIBRARIES) $(LDFLAGS) + ./$(TEST_TARGET) + +$(APPLIB): $(APPLIB_OBJECTS) + $(AR) $(ARFLAGS) $@ $^ + +clean: + rm -f -rf *.o + rm -f $(TEST_TARGET) + rm -f $(APPLIB) + diff --git a/gcovr.cfg b/gcovr.cfg new file mode 100644 index 000000000..1f027724a --- /dev/null +++ b/gcovr.cfg @@ -0,0 +1,6 @@ +filter = src/ +filter = include/ +html = yes +html-details = yes +output = coverage.html +print-summary = yes diff --git a/include/CppUTest/CommandLineArguments.h b/include/CppUTest/CommandLineArguments.h old mode 100755 new mode 100644 index 95cc0d7bb..d162a5e2f --- a/include/CppUTest/CommandLineArguments.h +++ b/include/CppUTest/CommandLineArguments.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -37,16 +37,24 @@ class TestPlugin; class CommandLineArguments { public: - explicit CommandLineArguments(int ac, const char** av); + explicit CommandLineArguments(int ac, const char *const *av); virtual ~CommandLineArguments(); bool parse(TestPlugin* plugin); + bool needHelp() const; bool isVerbose() const; + bool isVeryVerbose() const; bool isColor() const; bool isListingTestGroupNames() const; bool isListingTestGroupAndCaseNames() const; + bool isListingTestLocations() const; bool isRunIgnored() const; - int getRepeatCount() const; + size_t getRepeatCount() const; + bool isShuffling() const; + bool isReversing() const; + bool isCrashingOnFail() const; + bool isRethrowingExceptions() const; + size_t getShuffleSeed() const; const TestFilter* getGroupFilters() const; const TestFilter* getNameFilters() const; bool isJUnitOutput() const; @@ -55,6 +63,7 @@ class CommandLineArguments bool runTestsInSeperateProcess() const; const SimpleString& getPackageName() const; const char* usage() const; + const char* help() const; private: @@ -62,34 +71,46 @@ class CommandLineArguments { OUTPUT_ECLIPSE, OUTPUT_JUNIT, OUTPUT_TEAMCITY }; + int ac_; - const char** av_; + const char *const *av_; + bool needHelp_; bool verbose_; + bool veryVerbose_; bool color_; bool runTestsAsSeperateProcess_; bool listTestGroupNames_; bool listTestGroupAndCaseNames_; + bool listTestLocations_; bool runIgnored_; - int repeat_; + bool reversing_; + bool crashOnFail_; + bool rethrowExceptions_; + bool shuffling_; + bool shufflingPreSeeded_; + size_t repeat_; + size_t shuffleSeed_; TestFilter* groupFilters_; TestFilter* nameFilters_; OutputType outputType_; SimpleString packageName_; - SimpleString getParameterField(int ac, const char** av, int& i, const SimpleString& parameterName); - void SetRepeatCount(int ac, const char** av, int& index); - void AddGroupFilter(int ac, const char** av, int& index); - void AddStrictGroupFilter(int ac, const char** av, int& index); - void AddExcludeGroupFilter(int ac, const char** av, int& index); - void AddExcludeStrictGroupFilter(int ac, const char** av, int& index); - void AddNameFilter(int ac, const char** av, int& index); - void AddStrictNameFilter(int ac, const char** av, int& index); - void AddExcludeNameFilter(int ac, const char** av, int& index); - void AddExcludeStrictNameFilter(int ac, const char** av, int& index); - void AddTestToRunBasedOnVerboseOutput(int ac, const char** av, int& index, const char* parameterName); - bool SetOutputType(int ac, const char** av, int& index); - void SetPackageName(int ac, const char** av, int& index); + SimpleString getParameterField(int ac, const char *const *av, int& i, const SimpleString& parameterName); + void setRepeatCount(int ac, const char *const *av, int& index); + bool setShuffle(int ac, const char *const *av, int& index); + void addGroupFilter(int ac, const char *const *av, int& index); + bool addGroupDotNameFilter(int ac, const char *const *av, int& index, const SimpleString& parameterName, bool strict, bool exclude); + void addStrictGroupFilter(int ac, const char *const *av, int& index); + void addExcludeGroupFilter(int ac, const char *const *av, int& index); + void addExcludeStrictGroupFilter(int ac, const char *const *av, int& index); + void addNameFilter(int ac, const char *const *av, int& index); + void addStrictNameFilter(int ac, const char *const *av, int& index); + void addExcludeNameFilter(int ac, const char *const *av, int& index); + void addExcludeStrictNameFilter(int ac, const char *const *av, int& index); + void addTestToRunBasedOnVerboseOutput(int ac, const char *const *av, int& index, const char* parameterName); + bool setOutputType(int ac, const char *const *av, int& index); + void setPackageName(int ac, const char *const *av, int& index); CommandLineArguments(const CommandLineArguments&); CommandLineArguments& operator=(const CommandLineArguments&); diff --git a/include/CppUTest/CommandLineTestRunner.h b/include/CppUTest/CommandLineTestRunner.h index 8cf99d170..91c52d177 100644 --- a/include/CppUTest/CommandLineTestRunner.h +++ b/include/CppUTest/CommandLineTestRunner.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -41,10 +41,10 @@ class TestRegistry; class CommandLineTestRunner { public: - static int RunAllTests(int ac, const char** av); + static int RunAllTests(int ac, const char *const *av); static int RunAllTests(int ac, char** av); - CommandLineTestRunner(int ac, const char** av, TestRegistry* registry); + CommandLineTestRunner(int ac, const char *const *av, TestRegistry* registry); virtual ~CommandLineTestRunner(); int runAllTestsMain(); diff --git a/include/CppUTest/CppUTestConfig.h b/include/CppUTest/CppUTestConfig.h index 9be2585ec..435ea74d2 100644 --- a/include/CppUTest/CppUTestConfig.h +++ b/include/CppUTest/CppUTestConfig.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -29,7 +29,17 @@ #define CPPUTESTCONFIG_H_ #ifndef CPPUTEST_USE_OWN_CONFIGURATION -#include "CppUTestGeneratedConfig.h" + // The autotools generated header uses reserved names in macros + #ifdef __clang__ + #pragma clang diagnostic push + #if __clang_major__ >= 13 + #pragma clang diagnostic ignored "-Wreserved-identifier" + #endif + #endif + #include "CppUTestGeneratedConfig.h" + #ifdef __clang__ + #pragma clang diagnostic pop + #endif #endif /* @@ -40,13 +50,6 @@ * */ -#ifdef __clang__ - #pragma clang diagnostic push - #if __clang_major__ >= 3 && __clang_minor__ >= 6 - #pragma clang diagnostic ignored "-Wreserved-id-macro" - #endif -#endif - /* * Lib C dependencies that are currently still left: * @@ -94,56 +97,35 @@ /* Should be the only #include here. Standard C library wrappers */ #include "StandardCLibrary.h" -/* Create a __no_return__ macro, which is used to flag a function as not returning. +/* Create a CPPUTEST_NORETURN macro, which is used to flag a function as not returning. * Used for functions that always throws for instance. * * This is needed for compiling with clang, without breaking other compilers. */ #ifndef __has_attribute - #define __has_attribute(x) 0 -#endif - -#if __has_attribute(noreturn) - #define __no_return__ __attribute__((noreturn)) + #define CPPUTEST_HAS_ATTRIBUTE(x) 0 #else - #define __no_return__ + #define CPPUTEST_HAS_ATTRIBUTE(x) __has_attribute(x) #endif -#if __has_attribute(format) - #define __check_format__(type, format_parameter, other_parameters) __attribute__ ((format (type, format_parameter, other_parameters))) +#if defined (__cplusplus) && __cplusplus >= 201103L + #define CPPUTEST_NORETURN [[noreturn]] +#elif CPPUTEST_HAS_ATTRIBUTE(noreturn) + #define CPPUTEST_NORETURN __attribute__((noreturn)) #else - #define __check_format__(type, format_parameter, other_parameters) /* type, format_parameter, other_parameters */ + #define CPPUTEST_NORETURN #endif -/* - * When we don't link Standard C++, then we won't throw exceptions as we assume the compiler might not support that! - */ - -#if CPPUTEST_USE_STD_CPP_LIB - #if defined(__cplusplus) && __cplusplus >= 201103L - #define UT_THROW(exception) - #define UT_NOTHROW noexcept - #else - #define UT_THROW(exception) throw (exception) - #define UT_NOTHROW throw() - #endif +#if defined(__MINGW32__) +#define CPPUTEST_CHECK_FORMAT_TYPE __MINGW_PRINTF_FORMAT #else - #define UT_THROW(exception) - #ifdef __clang__ - #define UT_NOTHROW throw() - #else - #define UT_NOTHROW - #endif +#define CPPUTEST_CHECK_FORMAT_TYPE printf #endif -/* - * Visual C++ doesn't define __cplusplus as C++11 yet (201103), however it doesn't want the throw(exception) either, but - * it does want throw(). - */ - -#ifdef _MSC_VER - #undef UT_THROW - #define UT_THROW(exception) +#if CPPUTEST_HAS_ATTRIBUTE(format) + #define CPPUTEST_CHECK_FORMAT(type, format_parameter, other_parameters) __attribute__ ((format (type, format_parameter, other_parameters))) +#else + #define CPPUTEST_CHECK_FORMAT(type, format_parameter, other_parameters) /* type, format_parameter, other_parameters */ #endif #if defined(__cplusplus) && __cplusplus >= 201103L @@ -153,32 +135,123 @@ #endif /* - * g++-4.7 with stdc++11 enabled On MacOSX! will have a different exception specifier for operator new (and thank you!) - * I assume they'll fix this in the future, but for now, we'll change that here. - * (This should perhaps also be done in the configure.ac) - */ - -#ifdef __GXX_EXPERIMENTAL_CXX0X__ -#ifdef __APPLE__ -#ifdef _GLIBCXX_THROW -#undef UT_THROW -#define UT_THROW(exception) _GLIBCXX_THROW(exception) + * Address sanitizer is a good thing... and it causes some conflicts with the CppUTest tests + * To check whether it is on or off, we create a CppUTest define here. +*/ +#if defined(__has_feature) + #if __has_feature(address_sanitizer) + #define CPPUTEST_SANITIZE_ADDRESS 1 + #endif +#elif defined(__SANITIZE_ADDRESS__) + #define CPPUTEST_SANITIZE_ADDRESS 1 #endif + +#ifndef CPPUTEST_SANITIZE_ADDRESS + #define CPPUTEST_SANITIZE_ADDRESS 0 #endif + +#if CPPUTEST_SANITIZE_ADDRESS + #if defined(__linux__) && defined(__clang__) && CPPUTEST_USE_STD_CPP_LIB && CPPUTEST_USE_MEM_LEAK_DETECTION + #warning Compiling with Address Sanitizer with clang on linux may cause duplicate symbols for operator new. Turning off memory leak detection. Compile with -DCPPUTEST_MEM_LEAK_DETECTION_DISABLED to get rid of this warning. + #endif + #define CPPUTEST_DO_NOT_SANITIZE_ADDRESS __attribute__((no_sanitize_address)) +#else + #define CPPUTEST_DO_NOT_SANITIZE_ADDRESS #endif /* - * Handling of IEEE754 floating point exceptions via fenv.h - * Works on non-Visual C++ compilers and Visual C++ 2008 and newer + * Handling of IEEE754 (IEC559) floating point exceptions via fenv.h + * Predominantly works on non-Visual C++ compilers and Visual C++ 2008 and newer */ - -#if CPPUTEST_USE_STD_C_LIB && (!defined(_MSC_VER) || (_MSC_VER >= 1800)) -#define CPPUTEST_HAVE_FENV -#if defined(__WATCOMC__) -#define CPPUTEST_FENV_IS_WORKING_PROPERLY 0 -#else -#define CPPUTEST_FENV_IS_WORKING_PROPERLY 1 +#ifndef CPPUTEST_HAVE_FENV + #if (defined(__STDC_IEC_559__) && __STDC_IEC_559__) && CPPUTEST_USE_STD_C_LIB + #define CPPUTEST_HAVE_FENV 1 + #else + #define CPPUTEST_HAVE_FENV 0 + #endif #endif + +#ifdef __cplusplus + /* + * Detection of run-time type information (RTTI) presence. Since it's a + * standard language feature, assume it is enabled unless we see otherwise. + */ + #ifndef CPPUTEST_HAVE_RTTI + #if ((__cplusplus >= 202002L) && !__cpp_rtti) || \ + (defined(_MSC_VER) && !_CPPRTTI) || \ + (defined(__GNUC__) && !__GXX_RTTI) || \ + (defined(__ghs__) && !__RTTI) || \ + (defined(__WATCOMC__) && !_CPPRTTI) + #define CPPUTEST_HAVE_RTTI 0 + #else + #define CPPUTEST_HAVE_RTTI 1 + #endif + #endif + + /* + * Detection of exception support. Since it's a standard language feature, + * assume it is enabled unless we see otherwise. + */ + #ifndef CPPUTEST_HAVE_EXCEPTIONS + #if ((__cplusplus >= 202002L) && !__cpp_exceptions) || \ + (defined(_MSC_VER) && !_CPPUNWIND) || \ + (defined(__GNUC__) && !__EXCEPTIONS) || \ + (defined(__ghs__) && !__EXCEPTION_HANDLING) || \ + (defined(__WATCOMC__) && !_CPPUNWIND) + #define CPPUTEST_HAVE_EXCEPTIONS 0 + #else + #define CPPUTEST_HAVE_EXCEPTIONS 1 + #endif + #endif + + #if CPPUTEST_HAVE_EXCEPTIONS + #if defined(__cplusplus) && __cplusplus >= 201103L + #define UT_THROW(exception) + #define UT_NOTHROW noexcept + #else + #define UT_THROW(exception) throw (exception) + #define UT_NOTHROW throw() + #endif + #else + #define UT_THROW(exception) + #if defined(__clang__) || defined(__GNUC__) + #if defined(__cplusplus) && __cplusplus >= 201103L + #define UT_NOTHROW noexcept + #else + #define UT_NOTHROW throw() + #endif + #else + #define UT_NOTHROW + #endif + #endif + + /* + * Visual C++ doesn't define __cplusplus as C++11 yet (201103), however it doesn't want the throw(exception) either, but + * it does want throw(). + */ + #ifdef _MSC_VER + #undef UT_THROW + #define UT_THROW(exception) + #endif + + /* + * g++-4.7 with stdc++11 enabled On MacOSX! will have a different exception specifier for operator new (and thank you!) + * I assume they'll fix this in the future, but for now, we'll change that here. + * (This should perhaps also be done in the configure.ac) + */ + #if defined(__GXX_EXPERIMENTAL_CXX0X__) && \ + defined(__APPLE__) && \ + defined(_GLIBCXX_THROW) + #undef UT_THROW + #define UT_THROW(exception) _GLIBCXX_THROW(exception) + #endif + + #if CPPUTEST_USE_STD_CPP_LIB + #define CPPUTEST_BAD_ALLOC std::bad_alloc + #else + class CppUTestBadAlloc {}; + #define CPPUTEST_BAD_ALLOC CppUTestBadAlloc + #endif #endif /* @@ -192,33 +265,43 @@ #endif #endif -/* Handling of systems with a different byte-width (e.g. 16 bit). - * Since CHAR_BIT is defined in limits.h (ANSI C), use default of 8 when building without Std C library. +/* Handling of systems with a different byte-width (e.g. 16 bit). Since + * CHAR_BIT is defined in limits.h (ANSI C), the user must provide a definition + * when building without Std C library. */ -#if CPPUTEST_USE_STD_C_LIB -#define CPPUTEST_CHAR_BIT CHAR_BIT -#else -#define CPPUTEST_CHAR_BIT 8 +#ifndef CPPUTEST_CHAR_BIT + #if defined(CHAR_BIT) + #define CPPUTEST_CHAR_BIT CHAR_BIT + #else + #error "Provide a definition for CPPUTEST_CHAR_BIT" + #endif +#endif + +/* Handling of systems with a different int-width (e.g. 16 bit). + */ +#if CPPUTEST_USE_STD_C_LIB && (INT_MAX == 0x7fff) +#define CPPUTEST_16BIT_INTS #endif /* * Support for "long long" type. * - * Not supported when CPUTEST_LONG_LONG_DISABLED is set. + * Not supported when CPPUTEST_LONG_LONG_DISABLED is set. * Can be overridden by using CPPUTEST_USE_LONG_LONG * - * CPPUTEST_HAVE_LONG_LONG_INT is set by configure + * CPPUTEST_HAVE_LONG_LONG_INT is set by configure or CMake. * LLONG_MAX is set in limits.h. This is a crude attempt to detect long long support when no configure is used * */ - -#if !defined(CPPUTEST_LONG_LONG_DISABLED) && !defined(CPPUTEST_USE_LONG_LONG) -#if defined(CPPUTEST_HAVE_LONG_LONG_INT) || defined(LLONG_MAX) +#ifndef CPPUTEST_USE_LONG_LONG +#if !defined(CPPUTEST_LONG_LONG_DISABLED) && (defined(CPPUTEST_HAVE_LONG_LONG_INT) || defined(LLONG_MAX)) #define CPPUTEST_USE_LONG_LONG 1 +#else +#define CPPUTEST_USE_LONG_LONG 0 #endif #endif -#ifdef CPPUTEST_USE_LONG_LONG +#if CPPUTEST_USE_LONG_LONG typedef long long cpputest_longlong; typedef unsigned long long cpputest_ulonglong; #else @@ -232,40 +315,44 @@ typedef unsigned long long cpputest_ulonglong; #define CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE 8 #endif -struct cpputest_longlong -{ #if defined(__cplusplus) - cpputest_longlong() {} - cpputest_longlong(int) {} +extern "C" { #endif + +typedef struct +{ char dummy[CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE]; -}; +} cpputest_longlong; -struct cpputest_ulonglong +typedef struct { -#if defined(__cplusplus) - cpputest_ulonglong() {} - cpputest_ulonglong(int) {} -#endif char dummy[CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE]; -}; +} cpputest_ulonglong; +#if defined(__cplusplus) +} /* extern "C" */ #endif -/* Visual C++ 10.0+ (2010+) supports the override keyword, but doesn't define the C++ version as C++11 */ -#if defined(__cplusplus) && ((__cplusplus >= 201103L) || (defined(_MSC_VER) && (_MSC_VER >= 1600))) -#define CPPUTEST_COMPILER_FULLY_SUPPORTS_CXX11 -#define _override override -#else -#define _override #endif -/* MinGW-w64 prefers to act like Visual C++, but we want the ANSI behaviors instead */ -#undef __USE_MINGW_ANSI_STDIO -#define __USE_MINGW_ANSI_STDIO 1 +#ifdef __cplusplus + /* Visual C++ 10.0+ (2010+) supports the override keyword, but doesn't define the C++ version as C++11 */ + #if (__cplusplus >= 201103L) || (defined(_MSC_VER) && (_MSC_VER >= 1600)) + #define CPPUTEST_OVERRIDE override + #define NULLPTR nullptr + #else + #define CPPUTEST_OVERRIDE + #define NULLPTR NULL + #endif +#endif -#ifdef __clang__ - #pragma clang diagnostic pop +#ifdef __cplusplus + /* Visual C++ 11.0+ (2012+) supports the override keyword on destructors */ + #if (__cplusplus >= 201103L) || (defined(_MSC_VER) && (_MSC_VER >= 1700)) + #define CPPUTEST_DESTRUCTOR_OVERRIDE override + #else + #define CPPUTEST_DESTRUCTOR_OVERRIDE + #endif #endif #endif diff --git a/include/CppUTest/CppUTestGeneratedConfig.h b/include/CppUTest/CppUTestGeneratedConfig.h index 94e293f9c..5bcd53768 100644 --- a/include/CppUTest/CppUTestGeneratedConfig.h +++ b/include/CppUTest/CppUTestGeneratedConfig.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/include/CppUTest/JUnitTestOutput.h b/include/CppUTest/JUnitTestOutput.h index d2a349b31..5e5746f56 100644 --- a/include/CppUTest/JUnitTestOutput.h +++ b/include/CppUTest/JUnitTestOutput.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -38,21 +38,22 @@ class JUnitTestOutput: public TestOutput { public: JUnitTestOutput(); - virtual ~JUnitTestOutput(); + virtual ~JUnitTestOutput() CPPUTEST_DESTRUCTOR_OVERRIDE; - virtual void printTestsStarted() _override; - virtual void printTestsEnded(const TestResult& result) _override; - virtual void printCurrentTestStarted(const UtestShell& test) _override; - virtual void printCurrentTestEnded(const TestResult& res) _override; - virtual void printCurrentGroupStarted(const UtestShell& test) _override; - virtual void printCurrentGroupEnded(const TestResult& res) _override; + virtual void printTestsStarted() CPPUTEST_OVERRIDE; + virtual void printTestsEnded(const TestResult& result) CPPUTEST_OVERRIDE; + virtual void printCurrentTestStarted(const UtestShell& test) CPPUTEST_OVERRIDE; + virtual void printCurrentTestEnded(const TestResult& res) CPPUTEST_OVERRIDE; + virtual void printCurrentGroupStarted(const UtestShell& test) CPPUTEST_OVERRIDE; + virtual void printCurrentGroupEnded(const TestResult& res) CPPUTEST_OVERRIDE; - virtual void printBuffer(const char*) _override; - virtual void print(const char*) _override; - virtual void print(long) _override; - virtual void printFailure(const TestFailure& failure) _override; + virtual void printBuffer(const char*) CPPUTEST_OVERRIDE; + virtual void print(const char*) CPPUTEST_OVERRIDE; + virtual void print(long) CPPUTEST_OVERRIDE; + virtual void print(size_t) CPPUTEST_OVERRIDE; + virtual void printFailure(const TestFailure& failure) CPPUTEST_OVERRIDE; - virtual void flush() _override; + virtual void flush() CPPUTEST_OVERRIDE; virtual SimpleString createFileName(const SimpleString& group); void setPackageName(const SimpleString &package); @@ -71,9 +72,10 @@ class JUnitTestOutput: public TestOutput virtual void writeTestSuiteSummary(); virtual void writeProperties(); virtual void writeTestCases(); + virtual SimpleString encodeXmlText(const SimpleString& textbody); + virtual SimpleString encodeFileName(const SimpleString& fileName); virtual void writeFailure(JUnitTestCaseResultNode* node); virtual void writeFileEnding(); - }; #endif diff --git a/include/CppUTest/MemoryLeakDetector.h b/include/CppUTest/MemoryLeakDetector.h index 48cb16ada..195a3384a 100644 --- a/include/CppUTest/MemoryLeakDetector.h +++ b/include/CppUTest/MemoryLeakDetector.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -58,7 +58,7 @@ struct SimpleStringBuffer SimpleStringBuffer(); void clear(); - void add(const char* format, ...) __check_format__(printf, 2, 3); + void add(const char* format, ...) CPPUTEST_CHECK_FORMAT(CPPUTEST_CHECK_FORMAT_TYPE, 2, 3); void addMemoryDump(const void* memory, size_t memorySize); char* toString(); @@ -86,30 +86,30 @@ class MemoryLeakOutputStringBuffer void reportMemoryLeak(MemoryLeakDetectorNode* leak); - void reportDeallocateNonAllocatedMemoryFailure(const char* freeFile, int freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); - void reportMemoryCorruptionFailure(MemoryLeakDetectorNode* node, const char* freeFile, int freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); - void reportAllocationDeallocationMismatchFailure(MemoryLeakDetectorNode* node, const char* freeFile, int freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); + void reportDeallocateNonAllocatedMemoryFailure(const char* freeFile, size_t freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); + void reportMemoryCorruptionFailure(MemoryLeakDetectorNode* node, const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); + void reportAllocationDeallocationMismatchFailure(MemoryLeakDetectorNode* node, const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); char* toString(); private: - void addAllocationLocation(const char* allocationFile, int allocationLineNumber, size_t allocationSize, TestMemoryAllocator* allocator); - void addDeallocationLocation(const char* freeFile, int freeLineNumber, TestMemoryAllocator* allocator); + void addAllocationLocation(const char* allocationFile, size_t allocationLineNumber, size_t allocationSize, TestMemoryAllocator* allocator); + void addDeallocationLocation(const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* allocator); void addMemoryLeakHeader(); - void addMemoryLeakFooter(int totalAmountOfLeaks); + void addMemoryLeakFooter(size_t totalAmountOfLeaks); void addWarningForUsingMalloc(); void addNoMemoryLeaksMessage(); void addErrorMessageForTooMuchLeaks(); private: - int total_leaks_; + size_t total_leaks_; bool giveWarningOnUsingMalloc_; void reportFailure(const char* message, const char* allocFile, - int allocLine, size_t allocSize, + size_t allocLine, size_t allocSize, TestMemoryAllocator* allocAllocator, const char* freeFile, - int freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); + size_t freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); SimpleStringBuffer outputBuffer_; }; @@ -117,19 +117,20 @@ class MemoryLeakOutputStringBuffer struct MemoryLeakDetectorNode { MemoryLeakDetectorNode() : - size_(0), number_(0), memory_(0), file_(0), line_(0), allocator_(0), period_(mem_leak_period_enabled), next_(0) + size_(0), number_(0), memory_(NULLPTR), file_(NULLPTR), line_(0), allocator_(NULLPTR), period_(mem_leak_period_enabled), allocation_stage_(0), next_(NULLPTR) { } - void init(char* memory, unsigned number, size_t size, TestMemoryAllocator* allocator, MemLeakPeriod period, const char* file, int line); + void init(char* memory, unsigned number, size_t size, TestMemoryAllocator* allocator, MemLeakPeriod period, unsigned char allocation_stage, const char* file, size_t line); size_t size_; unsigned number_; char* memory_; const char* file_; - int line_; + size_t line_; TestMemoryAllocator* allocator_; MemLeakPeriod period_; + unsigned char allocation_stage_; private: friend struct MemoryLeakDetectorList; @@ -139,7 +140,7 @@ struct MemoryLeakDetectorNode struct MemoryLeakDetectorList { MemoryLeakDetectorList() : - head_(0) + head_(NULLPTR) {} void addNewNode(MemoryLeakDetectorNode* node); @@ -147,15 +148,19 @@ struct MemoryLeakDetectorList MemoryLeakDetectorNode* removeNode(char* memory); MemoryLeakDetectorNode* getFirstLeak(MemLeakPeriod period); - MemoryLeakDetectorNode* getNextLeak(MemoryLeakDetectorNode* node, - MemLeakPeriod period); - MemoryLeakDetectorNode* getLeakFrom(MemoryLeakDetectorNode* node, - MemLeakPeriod period); + MemoryLeakDetectorNode* getFirstLeakForAllocationStage(unsigned char allocation_stage); - int getTotalLeaks(MemLeakPeriod period); + MemoryLeakDetectorNode* getNextLeak(MemoryLeakDetectorNode* node, MemLeakPeriod period); + MemoryLeakDetectorNode* getNextLeakForAllocationStage(MemoryLeakDetectorNode* node, unsigned char allocation_stage); + + MemoryLeakDetectorNode* getLeakFrom(MemoryLeakDetectorNode* node, MemLeakPeriod period); + MemoryLeakDetectorNode* getLeakForAllocationStageFrom(MemoryLeakDetectorNode* node, unsigned char allocation_stage); + + size_t getTotalLeaks(MemLeakPeriod period); void clearAllAccounting(MemLeakPeriod period); bool isInPeriod(MemoryLeakDetectorNode* node, MemLeakPeriod period); + bool isInAllocationStage(MemoryLeakDetectorNode* node, unsigned char allocation_stage); private: MemoryLeakDetectorNode* head_; @@ -169,11 +174,12 @@ struct MemoryLeakDetectorTable MemoryLeakDetectorNode* retrieveNode(char* memory); MemoryLeakDetectorNode* removeNode(char* memory); - int getTotalLeaks(MemLeakPeriod period); + size_t getTotalLeaks(MemLeakPeriod period); MemoryLeakDetectorNode* getFirstLeak(MemLeakPeriod period); - MemoryLeakDetectorNode* getNextLeak(MemoryLeakDetectorNode* leak, - MemLeakPeriod period); + MemoryLeakDetectorNode* getFirstLeakForAllocationStage(unsigned char allocation_stage); + MemoryLeakDetectorNode* getNextLeak(MemoryLeakDetectorNode* leak, MemLeakPeriod period); + MemoryLeakDetectorNode* getNextLeakForAllocationStage(MemoryLeakDetectorNode* leak, unsigned char allocation_stage); private: unsigned long hash(char* memory); @@ -200,23 +206,32 @@ class MemoryLeakDetector void startChecking(); void stopChecking(); + unsigned char getCurrentAllocationStage() const; + void increaseAllocationStage(); + void decreaseAllocationStage(); + const char* report(MemLeakPeriod period); void markCheckingPeriodLeaksAsNonCheckingPeriod(); - int totalMemoryLeaks(MemLeakPeriod period); + size_t totalMemoryLeaks(MemLeakPeriod period); void clearAllAccounting(MemLeakPeriod period); char* allocMemory(TestMemoryAllocator* allocator, size_t size, bool allocatNodesSeperately = false); char* allocMemory(TestMemoryAllocator* allocator, size_t size, - const char* file, int line, bool allocatNodesSeperately = false); + const char* file, size_t line, bool allocatNodesSeperately = false); void deallocMemory(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately = false); - void deallocMemory(TestMemoryAllocator* allocator, void* memory, const char* file, int line, bool allocatNodesSeperately = false); - char* reallocMemory(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately = false); + void deallocMemory(TestMemoryAllocator* allocator, void* memory, const char* file, size_t line, bool allocatNodesSeperately = false); + void deallocAllMemoryInCurrentAllocationStage(); + char* reallocMemory(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, size_t line, bool allocatNodesSeperately = false); void invalidateMemory(char* memory); void removeMemoryLeakInformationWithoutCheckingOrDeallocatingTheMemoryButDeallocatingTheAccountInformation(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately); enum { +#ifdef CPPUTEST_DISABLE_MEM_CORRUPTION_CHECK + memory_corruption_buffer_size = 0 +#else memory_corruption_buffer_size = 3 +#endif }; unsigned getCurrentAllocationNumber(); @@ -229,26 +244,27 @@ class MemoryLeakDetector MemoryLeakDetectorTable memoryTable_; bool doAllocationTypeChecking_; unsigned allocationSequenceNumber_; + unsigned char current_allocation_stage_; SimpleMutex* mutex_; - char* allocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, size_t size, const char* file, int line, bool allocatNodesSeperately); - char* reallocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately); + char* allocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, size_t size, const char* file, size_t line, bool allocatNodesSeperately); + char* reallocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, size_t line, bool allocatNodesSeperately); MemoryLeakDetectorNode* createMemoryLeakAccountingInformation(TestMemoryAllocator* allocator, size_t size, char* memory, bool allocatNodesSeperately); bool validMemoryCorruptionInformation(char* memory); bool matchingAllocation(TestMemoryAllocator *alloc_allocator, TestMemoryAllocator *free_allocator); - void storeLeakInformation(MemoryLeakDetectorNode * node, char *new_memory, size_t size, TestMemoryAllocator *allocator, const char *file, int line); + void storeLeakInformation(MemoryLeakDetectorNode * node, char *new_memory, size_t size, TestMemoryAllocator *allocator, const char *file, size_t line); void ConstructMemoryLeakReport(MemLeakPeriod period); size_t sizeOfMemoryWithCorruptionInfo(size_t size); MemoryLeakDetectorNode* getNodeFromMemoryPointer(char* memory, size_t size); - char* reallocateMemoryAndLeakInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately); + char* reallocateMemoryAndLeakInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, size_t line, bool allocatNodesSeperately); void addMemoryCorruptionInformation(char* memory); - void checkForCorruption(MemoryLeakDetectorNode* node, const char* file, int line, TestMemoryAllocator* allocator, bool allocateNodesSeperately); + void checkForCorruption(MemoryLeakDetectorNode* node, const char* file, size_t line, TestMemoryAllocator* allocator, bool allocateNodesSeperately); }; #endif diff --git a/include/CppUTest/MemoryLeakDetectorForceInclude.h b/include/CppUTest/MemoryLeakDetectorForceInclude.h new file mode 100644 index 000000000..6de90e177 --- /dev/null +++ b/include/CppUTest/MemoryLeakDetectorForceInclude.h @@ -0,0 +1,4 @@ +// Not all toolchains support multiple force includes (namely IAR), +// so we wrap the two in a single header. +#include "MemoryLeakDetectorMallocMacros.h" +#include "MemoryLeakDetectorNewMacros.h" diff --git a/include/CppUTest/MemoryLeakDetectorMallocMacros.h b/include/CppUTest/MemoryLeakDetectorMallocMacros.h index c858fa8ea..42c324796 100644 --- a/include/CppUTest/MemoryLeakDetectorMallocMacros.h +++ b/include/CppUTest/MemoryLeakDetectorMallocMacros.h @@ -21,10 +21,10 @@ extern "C" { #endif -extern void* cpputest_malloc_location(size_t size, const char* file, int line); -extern void* cpputest_calloc_location(size_t count, size_t size, const char* file, int line); -extern void* cpputest_realloc_location(void *, size_t, const char* file, int line); -extern void cpputest_free_location(void* buffer, const char* file, int line); +extern void* cpputest_malloc_location(size_t size, const char* file, size_t line); +extern void* cpputest_calloc_location(size_t count, size_t size, const char* file, size_t line); +extern void* cpputest_realloc_location(void *, size_t, const char* file, size_t line); +extern void cpputest_free_location(void* buffer, const char* file, size_t line); #ifdef __cplusplus } @@ -32,20 +32,6 @@ extern void cpputest_free_location(void* buffer, const char* file, int line); extern void crash_on_allocation_number(unsigned number); -#endif - -/* NOTE on strdup! - * - * strdup was implemented earlier, however it is *not* an Standard C function but a POSIX function. - * Because of that, it can lead to portability issues by providing more than is available on the local platform. - * For that reason, strdup is *not* implemented as a macro. If you still want to use it, an easy implementation would be: - * - * size_t length = 1 + strlen(str); - * char* result = (char*) cpputest_malloc_location(length, file, line); - * memcpy(result, str, length); - * return result; - * - */ #define malloc(a) cpputest_malloc_location(a, __FILE__, __LINE__) #define calloc(a, b) cpputest_calloc_location(a, b, __FILE__, __LINE__) @@ -53,4 +39,30 @@ extern void crash_on_allocation_number(unsigned number); #define free(a) cpputest_free_location(a, __FILE__, __LINE__) #define CPPUTEST_USE_MALLOC_MACROS 1 +#endif /* CPPUTEST_USE_MALLOC_MACROS */ + +/* This prevents strdup macros to get defined, unless it has been enabled by the user or generated config */ +#ifdef CPPUTEST_HAVE_STRDUP + +/* This prevents the declaration from done twice and makes sure the file only #defines strdup, so it can be included anywhere */ +#ifndef CPPUTEST_USE_STRDUP_MACROS + +#ifdef __cplusplus +extern "C" +{ #endif + +extern char* cpputest_strdup_location(const char* str, const char* file, size_t line); +extern char* cpputest_strndup_location(const char* str, size_t n, const char* file, size_t line); + +#ifdef __cplusplus +} +#endif + +#define strdup(str) cpputest_strdup_location(str, __FILE__, __LINE__) +#define strndup(str, n) cpputest_strndup_location(str, n, __FILE__, __LINE__) + +#define CPPUTEST_USE_STRDUP_MACROS 1 +#endif /* CPPUTEST_USE_STRDUP_MACROS */ +#endif /* CPPUTEST_HAVE_STRDUP */ +#endif /* CPPUTEST_USE_MEM_LEAK_DETECTION */ diff --git a/include/CppUTest/MemoryLeakDetectorNewMacros.h b/include/CppUTest/MemoryLeakDetectorNewMacros.h index 02798e9f8..eb2bff29d 100644 --- a/include/CppUTest/MemoryLeakDetectorNewMacros.h +++ b/include/CppUTest/MemoryLeakDetectorNewMacros.h @@ -24,43 +24,82 @@ /* Make sure that mem leak detection is on and that this is being included from a C++ file */ #if CPPUTEST_USE_MEM_LEAK_DETECTION && defined(__cplusplus) -/* This #ifndef prevents from being included twice and enables the file to be included anywhere */ +/* Default to enabling macros (when memory leak detection is enabled), unless the user defines CPPUTEST_USE_NEW_MACROS as 0 */ #ifndef CPPUTEST_USE_NEW_MACROS + #define CPPUTEST_USE_NEW_MACROS 1 +#endif +/* This #ifndef prevents from being included twice and enables the file to be included anywhere */ +#ifndef CPPUTEST_HAVE_ALREADY_DECLARED_NEW_DELETE_OVERLOADS + #define CPPUTEST_HAVE_ALREADY_DECLARED_NEW_DELETE_OVERLOADS 1 #if CPPUTEST_USE_STD_CPP_LIB + #ifdef CPPUTEST_USE_STRDUP_MACROS + #if CPPUTEST_USE_STRDUP_MACROS == 1 + /* + * Some platforms (OSx, i.e.) will get or included when using header, + * in order to avoid conflicts with strdup and strndup macros defined by MemoryLeakDetectorMallocMacros.h + * we will undefined those macros, include the C++ headers and then reinclude MemoryLeakDetectorMallocMacros.h. + * The check '#if CPPUTEST_USE_STRDUP_MACROS' will ensure we only include MemoryLeakDetectorMallocMacros.h if + * it has already been includeded earlier. + */ + #undef strdup + #undef strndup + #undef CPPUTEST_USE_STRDUP_MACROS + #define CPPUTEST_REINCLUDE_MALLOC_MEMORY_LEAK_DETECTOR + #endif + #endif + #include #include #include - #endif - void* operator new(size_t size, const char* file, int line) UT_THROW (std::bad_alloc); - void* operator new[](size_t size, const char* file, int line) UT_THROW (std::bad_alloc); - void* operator new(size_t size) UT_THROW(std::bad_alloc); - void* operator new[](size_t size) UT_THROW(std::bad_alloc); + #ifdef CPPUTEST_REINCLUDE_MALLOC_MEMORY_LEAK_DETECTOR + #undef CPPUTEST_REINCLUDE_MALLOC_MEMORY_LEAK_DETECTOR + #include "MemoryLeakDetectorMallocMacros.h" + #endif + #endif /* CPPUTEST_USE_STD_CPP_LIB */ + + /* Some toolkits, e.g. MFC, provide their own new overloads with signature (size_t, const char *, int). + * If we don't provide them, in addition to the (size_t, const char *, size_t) version, we don't get to + * know about all allocations and report freeing of unallocated blocks. Hence, provide both overloads. + */ + + void* operator new(size_t size, const char* file, int line) UT_THROW (CPPUTEST_BAD_ALLOC); + void* operator new(size_t size, const char* file, size_t line) UT_THROW (CPPUTEST_BAD_ALLOC); + void* operator new[](size_t size, const char* file, int line) UT_THROW (CPPUTEST_BAD_ALLOC); + void* operator new[](size_t size, const char* file, size_t line) UT_THROW (CPPUTEST_BAD_ALLOC); + void* operator new(size_t size) UT_THROW(CPPUTEST_BAD_ALLOC); + void* operator new[](size_t size) UT_THROW(CPPUTEST_BAD_ALLOC); void operator delete(void* mem, const char* file, int line) UT_NOTHROW; + void operator delete(void* mem, const char* file, size_t line) UT_NOTHROW; void operator delete[](void* mem, const char* file, int line) UT_NOTHROW; + void operator delete[](void* mem, const char* file, size_t line) UT_NOTHROW; void operator delete(void* mem) UT_NOTHROW; void operator delete[](void* mem) UT_NOTHROW; - void operator delete (void* mem, size_t size) UT_NOTHROW; - void operator delete[] (void* mem, size_t size) UT_NOTHROW; -#endif + #if __cplusplus >= 201402L + void operator delete (void* mem, size_t size) UT_NOTHROW; + void operator delete[] (void* mem, size_t size) UT_NOTHROW; + #endif +#endif /* CPPUTEST_HAVE_ALREADY_DECLARED_NEW_DELETE_OVERLOADS */ -#ifdef __clang__ - #pragma clang diagnostic push - #if __clang_major__ >= 3 && __clang_minor__ >= 6 - #pragma clang diagnostic ignored "-Wkeyword-macro" - #endif -#endif +#if CPPUTEST_USE_NEW_MACROS != 0 -#define new new(__FILE__, __LINE__) + #ifdef __clang__ + #pragma clang diagnostic push + #if (__clang_major__ == 3 && __clang_minor__ >= 6) || __clang_major__ >= 4 + #pragma clang diagnostic ignored "-Wkeyword-macro" + #endif + #endif -#ifdef __clang__ - #pragma clang diagnostic pop -#endif + #define new new(__FILE__, __LINE__) -#define CPPUTEST_USE_NEW_MACROS 1 + #ifdef __clang__ + #pragma clang diagnostic pop + #endif -#endif +#endif /* CPPUTEST_USE_NEW_MACROS != 0 */ + +#endif /* CPPUTEST_USE_MEM_LEAK_DETECTION && defined(__cplusplus) */ diff --git a/include/CppUTest/MemoryLeakWarningPlugin.h b/include/CppUTest/MemoryLeakWarningPlugin.h index efca7f74f..01ae95be7 100644 --- a/include/CppUTest/MemoryLeakWarningPlugin.h +++ b/include/CppUTest/MemoryLeakWarningPlugin.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -31,8 +31,8 @@ #include "TestPlugin.h" #include "MemoryLeakDetectorNewMacros.h" -#define IGNORE_ALL_LEAKS_IN_TEST() MemoryLeakWarningPlugin::getFirstPlugin()->ignoreAllLeaksInTest(); -#define EXPECT_N_LEAKS(n) MemoryLeakWarningPlugin::getFirstPlugin()->expectLeaksInTest(n); +#define IGNORE_ALL_LEAKS_IN_TEST() if (MemoryLeakWarningPlugin::getFirstPlugin()) MemoryLeakWarningPlugin::getFirstPlugin()->ignoreAllLeaksInTest() +#define EXPECT_N_LEAKS(n) if (MemoryLeakWarningPlugin::getFirstPlugin()) MemoryLeakWarningPlugin::getFirstPlugin()->expectLeaksInTest(n) extern void crash_on_allocation_number(unsigned alloc_number); @@ -42,16 +42,16 @@ class MemoryLeakFailure; class MemoryLeakWarningPlugin: public TestPlugin { public: - MemoryLeakWarningPlugin(const SimpleString& name, MemoryLeakDetector* localDetector = 0); - virtual ~MemoryLeakWarningPlugin(); + MemoryLeakWarningPlugin(const SimpleString& name, MemoryLeakDetector* localDetector = NULLPTR); + virtual ~MemoryLeakWarningPlugin() CPPUTEST_DESTRUCTOR_OVERRIDE; - virtual void preTestAction(UtestShell& test, TestResult& result) _override; - virtual void postTestAction(UtestShell& test, TestResult& result) _override; + virtual void preTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; + virtual void postTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; - virtual const char* FinalReport(int toBeDeletedLeaks = 0); + virtual const char* FinalReport(size_t toBeDeletedLeaks = 0); void ignoreAllLeaksInTest(); - void expectLeaksInTest(int n); + void expectLeaksInTest(size_t n); void destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(bool des); @@ -65,21 +65,25 @@ class MemoryLeakWarningPlugin: public TestPlugin static void destroyGlobalDetector(); static void turnOffNewDeleteOverloads(); - static void turnOnNewDeleteOverloads(); + static void turnOnDefaultNotThreadSafeNewDeleteOverloads(); static void turnOnThreadSafeNewDeleteOverloads(); static bool areNewDeleteOverloaded(); + + static void saveAndDisableNewDeleteOverloads(); + static void restoreNewDeleteOverloads(); + private: MemoryLeakDetector* memLeakDetector_; bool ignoreAllWarnings_; bool destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_; - int expectedLeaks_; - int failureCount_; + size_t expectedLeaks_; + size_t failureCount_; static MemoryLeakWarningPlugin* firstPlugin_; }; -extern void* cpputest_malloc_location_with_leak_detection(size_t size, const char* file, int line); -extern void* cpputest_realloc_location_with_leak_detection(void* memory, size_t size, const char* file, int line); -extern void cpputest_free_location_with_leak_detection(void* buffer, const char* file, int line); +extern void* cpputest_malloc_location_with_leak_detection(size_t size, const char* file, size_t line); +extern void* cpputest_realloc_location_with_leak_detection(void* memory, size_t size, const char* file, size_t line); +extern void cpputest_free_location_with_leak_detection(void* buffer, const char* file, size_t line); #endif diff --git a/include/CppUTest/PlatformSpecificFunctions.h b/include/CppUTest/PlatformSpecificFunctions.h index 6737f582a..3b2f983cc 100644 --- a/include/CppUTest/PlatformSpecificFunctions.h +++ b/include/CppUTest/PlatformSpecificFunctions.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/include/CppUTest/PlatformSpecificFunctions_c.h b/include/CppUTest/PlatformSpecificFunctions_c.h index fedb34fad..36700818b 100644 --- a/include/CppUTest/PlatformSpecificFunctions_c.h +++ b/include/CppUTest/PlatformSpecificFunctions_c.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -47,7 +47,7 @@ extern void (*PlatformSpecificLongJmp)(void); extern void (*PlatformSpecificRestoreJumpBuffer)(void); /* Time operations */ -extern long (*GetPlatformSpecificTimeInMillis)(void); +extern unsigned long (*GetPlatformSpecificTimeInMillis)(void); extern const char* (*GetPlatformSpecificTimeString)(void); /* String operations */ @@ -62,13 +62,18 @@ extern int (*PlatformSpecificAtExit)(void(*func)(void)); /* IO operations */ typedef void* PlatformSpecificFile; +extern PlatformSpecificFile PlatformSpecificStdOut; + extern PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag); extern void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file); extern void (*PlatformSpecificFClose)(PlatformSpecificFile file); -extern int (*PlatformSpecificPutchar)(int c); extern void (*PlatformSpecificFlush)(void); +/* Random operations */ +extern void (*PlatformSpecificSrand)(unsigned int); +extern int (*PlatformSpecificRand)(void); + /* Dynamic Memory operations */ extern void* (*PlatformSpecificMalloc)(size_t size); extern void* (*PlatformSpecificRealloc)(void* memory, size_t size); @@ -78,9 +83,12 @@ extern void* (*PlatformSpecificMemset)(void* mem, int c, size_t size); typedef void* PlatformSpecificMutex; extern PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void); +extern void (*PlatformSpecificSrand)(unsigned int); +extern int (*PlatformSpecificRand)(void); extern void (*PlatformSpecificMutexLock)(PlatformSpecificMutex mtx); extern void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex mtx); extern void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex mtx); +extern void (*PlatformSpecificAbort)(void); #ifdef __cplusplus } diff --git a/include/CppUTest/SimpleMutex.h b/include/CppUTest/SimpleMutex.h index eb4990054..8bb59fb69 100644 --- a/include/CppUTest/SimpleMutex.h +++ b/include/CppUTest/SimpleMutex.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/include/CppUTest/SimpleString.h b/include/CppUTest/SimpleString.h index 79293b3ac..63e7684d0 100644 --- a/include/CppUTest/SimpleString.h +++ b/include/CppUTest/SimpleString.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -83,6 +83,8 @@ class SimpleString SimpleString subStringFromTill(char startChar, char lastExcludedChar) const; void copyToBuffer(char* buffer, size_t bufferSize) const; + SimpleString printable() const; + const char *asCharString() const; size_t size() const; bool isEmpty() const; @@ -93,25 +95,42 @@ class SimpleString static void setStringAllocator(TestMemoryAllocator* allocator); static int AtoI(const char*str); + static unsigned AtoU(const char*str); static int StrCmp(const char* s1, const char* s2); static size_t StrLen(const char*); static int StrNCmp(const char* s1, const char* s2, size_t n); static char* StrNCpy(char* s1, const char* s2, size_t n); - static char* StrStr(const char* s1, const char* s2); + static const char* StrStr(const char* s1, const char* s2); static char ToLower(char ch); static int MemCmp(const void* s1, const void *s2, size_t n); - static char* allocStringBuffer(size_t size, const char* file, int line); - static void deallocStringBuffer(char* str, const char* file, int line); + static char* allocStringBuffer(size_t size, const char* file, size_t line); + static void deallocStringBuffer(char* str, size_t size, const char* file, size_t line); private: + + const char* getBuffer() const; + + void deallocateInternalBuffer(); + void setInternalBufferAsEmptyString(); + void setInternalBufferToNewBuffer(size_t bufferSize); + void setInternalBufferTo(char* buffer, size_t bufferSize); + void copyBufferToNewInternalBuffer(const char* otherBuffer); + void copyBufferToNewInternalBuffer(const char* otherBuffer, size_t bufferSize); + void copyBufferToNewInternalBuffer(const SimpleString& otherBuffer); + char *buffer_; + size_t bufferSize_; static TestMemoryAllocator* stringAllocator_; char* getEmptyString() const; - static char* copyToNewBuffer(const char* bufferToCopy, size_t bufferSize=0); + static char* copyToNewBuffer(const char* bufferToCopy, size_t bufferSize); static bool isDigit(char ch); static bool isSpace(char ch); static bool isUpper(char ch); + static bool isControl(char ch); + static bool isControlWithShortEscapeSequence(char ch); + + size_t getPrintableSize() const; }; class SimpleStringCollection @@ -134,6 +153,39 @@ class SimpleStringCollection SimpleStringCollection(SimpleStringCollection&); }; +class GlobalSimpleStringAllocatorStash +{ +public: + GlobalSimpleStringAllocatorStash(); + void save(); + void restore(); +private: + TestMemoryAllocator* originalAllocator_; +}; + +class MemoryAccountant; +class AccountingTestMemoryAllocator; + +class GlobalSimpleStringMemoryAccountant +{ +public: + GlobalSimpleStringMemoryAccountant(); + ~GlobalSimpleStringMemoryAccountant(); + + void useCacheSizes(size_t cacheSizes[], size_t length); + + void start(); + void stop(); + SimpleString report(); + + AccountingTestMemoryAllocator* getAllocator(); +private: + void restoreAllocator(); + + AccountingTestMemoryAllocator* allocator_; + MemoryAccountant* accountant_; +}; + SimpleString StringFrom(bool value); SimpleString StringFrom(const void* value); SimpleString StringFrom(void (*value)()); @@ -146,6 +198,8 @@ SimpleString StringFrom(long value); SimpleString StringFrom(unsigned long value); SimpleString StringFrom(cpputest_longlong value); SimpleString StringFrom(cpputest_ulonglong value); +SimpleString HexStringFrom(unsigned int value); +SimpleString HexStringFrom(int value); SimpleString HexStringFrom(signed char value); SimpleString HexStringFrom(long value); SimpleString HexStringFrom(unsigned long value); @@ -155,7 +209,7 @@ SimpleString HexStringFrom(const void* value); SimpleString HexStringFrom(void (*value)()); SimpleString StringFrom(double value, int precision = 6); SimpleString StringFrom(const SimpleString& other); -SimpleString StringFromFormat(const char* format, ...) __check_format__(printf, 1, 2); +SimpleString StringFromFormat(const char* format, ...) CPPUTEST_CHECK_FORMAT(CPPUTEST_CHECK_FORMAT_TYPE, 1, 2); SimpleString VStringFromFormat(const char* format, va_list args); SimpleString StringFromBinary(const unsigned char* value, size_t size); SimpleString StringFromBinaryOrNull(const unsigned char* value, size_t size); @@ -163,10 +217,25 @@ SimpleString StringFromBinaryWithSize(const unsigned char* value, size_t size); SimpleString StringFromBinaryWithSizeOrNull(const unsigned char* value, size_t size); SimpleString StringFromMaskedBits(unsigned long value, unsigned long mask, size_t byteCount); SimpleString StringFromOrdinalNumber(unsigned int number); +SimpleString BracketsFormattedHexStringFrom(int value); +SimpleString BracketsFormattedHexStringFrom(unsigned int value); +SimpleString BracketsFormattedHexStringFrom(long value); +SimpleString BracketsFormattedHexStringFrom(unsigned long value); +SimpleString BracketsFormattedHexStringFrom(cpputest_longlong value); +SimpleString BracketsFormattedHexStringFrom(cpputest_ulonglong value); +SimpleString BracketsFormattedHexStringFrom(signed char value); +SimpleString BracketsFormattedHexString(SimpleString hexString); +SimpleString PrintableStringFromOrNull(const char * expected); -#if CPPUTEST_USE_STD_CPP_LIB +/* + * ARM compiler has only partial support for C++11. + * Specifically nullptr_t is not officially supported + */ +#if __cplusplus > 199711L && !defined __arm__ && CPPUTEST_USE_STD_CPP_LIB +SimpleString StringFrom(const std::nullptr_t value); +#endif -#include +#if CPPUTEST_USE_STD_CPP_LIB SimpleString StringFrom(const std::string& other); diff --git a/include/CppUTest/SimpleStringInternalCache.h b/include/CppUTest/SimpleStringInternalCache.h new file mode 100644 index 000000000..ebbd30f6b --- /dev/null +++ b/include/CppUTest/SimpleStringInternalCache.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef D_SimpleStringInternalCache_h +#define D_SimpleStringInternalCache_h + +#include "CppUTest/TestMemoryAllocator.h" + +struct SimpleStringMemoryBlock; +struct SimpleStringInternalCacheNode; + +class SimpleStringInternalCache +{ +public: + SimpleStringInternalCache(); + ~SimpleStringInternalCache(); + + void setAllocator(TestMemoryAllocator* allocator); + + char* alloc(size_t size); + void dealloc(char* memory, size_t size); + + bool hasFreeBlocksOfSize(size_t size); + + void clearCache(); + void clearAllIncludingCurrentlyUsedMemory(); +private: + void printDeallocatingUnknownMemory(char* memory); + + enum { amountOfInternalCacheNodes = 5}; + bool isCached(size_t size); + size_t getIndexForCache(size_t size); + SimpleStringInternalCacheNode* getCacheNodeFromSize(size_t size); + + SimpleStringInternalCacheNode* createInternalCacheNodes(); + void destroyInternalCacheNode(SimpleStringInternalCacheNode * node); + SimpleStringMemoryBlock* createSimpleStringMemoryBlock(size_t sizeOfString, SimpleStringMemoryBlock* next); + void destroySimpleStringMemoryBlock(SimpleStringMemoryBlock * block, size_t size); + void destroySimpleStringMemoryBlockList(SimpleStringMemoryBlock * block, size_t size); + + SimpleStringMemoryBlock* reserveCachedBlockFrom(SimpleStringInternalCacheNode* node); + void releaseCachedBlockFrom(char* memory, SimpleStringInternalCacheNode* node); + void releaseNonCachedMemory(char* memory, size_t size); + + SimpleStringMemoryBlock* allocateNewCacheBlockFrom(SimpleStringInternalCacheNode* node); + SimpleStringMemoryBlock* addToSimpleStringMemoryBlockList(SimpleStringMemoryBlock* newBlock, SimpleStringMemoryBlock* previousHead); + + TestMemoryAllocator* allocator_; + SimpleStringInternalCacheNode* cache_; + SimpleStringMemoryBlock* nonCachedAllocations_; + bool hasWarnedAboutDeallocations; +}; + +class SimpleStringCacheAllocator : public TestMemoryAllocator +{ +public: + SimpleStringCacheAllocator(SimpleStringInternalCache& cache, TestMemoryAllocator* previousAllocator); + virtual ~SimpleStringCacheAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; + + virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; + virtual void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; + + virtual const char* name() const CPPUTEST_OVERRIDE; + virtual const char* alloc_name() const CPPUTEST_OVERRIDE; + virtual const char* free_name() const CPPUTEST_OVERRIDE; + + virtual TestMemoryAllocator* actualAllocator() CPPUTEST_OVERRIDE; + TestMemoryAllocator* originalAllocator(); +private: + SimpleStringInternalCache& cache_; + TestMemoryAllocator* originalAllocator_; +}; + +class GlobalSimpleStringCache +{ + SimpleStringCacheAllocator* allocator_; + SimpleStringInternalCache cache_; + +public: + GlobalSimpleStringCache(); + ~GlobalSimpleStringCache(); + + TestMemoryAllocator* getAllocator(); +}; + +#endif diff --git a/include/CppUTest/StandardCLibrary.h b/include/CppUTest/StandardCLibrary.h index 37333879d..c549ef5c6 100644 --- a/include/CppUTest/StandardCLibrary.h +++ b/include/CppUTest/StandardCLibrary.h @@ -5,7 +5,6 @@ #ifndef STANDARDCLIBRARY_H_ #define STANDARDCLIBRARY_H_ - #if CPPUTEST_USE_STD_C_LIB /* Needed for size_t */ @@ -15,18 +14,42 @@ #ifdef __cplusplus #if CPPUTEST_USE_STD_CPP_LIB #include + #include + #include + #include #endif #endif /* Needed for malloc */ #include +/* Needed for std::nullptr */ +#ifdef __cplusplus + #if CPPUTEST_USE_STD_CPP_LIB + #include + #endif +#endif + /* Needed for ... */ #include +/* Kludge to get a va_copy in VC++ V6 and in GCC 98 */ +#ifndef va_copy +#ifdef __GNUC__ +#define va_copy __va_copy +#else +#define va_copy(copy, original) copy = original; +#endif +#endif + /* Needed for some detection of long long and 64 bit */ #include +/* Needed to ensure that string.h is included prior to strdup redefinition */ +#ifdef CPPUTEST_HAVE_STRDUP +#include +#endif + #else #ifdef __KERNEL__ @@ -57,14 +80,23 @@ typedef __SIZE_TYPE__ size_t; typedef long unsigned int size_t; #endif -typedef char* va_list; #define NULL (0) +#ifdef __cplusplus +extern "C" { +#endif extern void* malloc(size_t); extern void free(void *); +#ifdef __cplusplus +} +#endif + #define _bnd(X, bnd) (((sizeof (X)) + (bnd)) & (~(bnd))) -#define va_start(ap, A) (void) ((ap) = (((char *) &(A)) + (_bnd (A,sizeof(int)-1)))) -#define va_end(ap) (void) 0 + +#define va_list __builtin_va_list +#define va_copy __builtin_va_copy +#define va_start __builtin_va_start +#define va_end __builtin_va_end #endif diff --git a/include/CppUTest/TeamCityTestOutput.h b/include/CppUTest/TeamCityTestOutput.h index 76708b188..caf67d586 100644 --- a/include/CppUTest/TeamCityTestOutput.h +++ b/include/CppUTest/TeamCityTestOutput.h @@ -8,14 +8,14 @@ class TeamCityTestOutput: public ConsoleTestOutput { public: TeamCityTestOutput(void); - virtual ~TeamCityTestOutput(void); + virtual ~TeamCityTestOutput(void) CPPUTEST_DESTRUCTOR_OVERRIDE; - virtual void printCurrentTestStarted(const UtestShell& test) _override; - virtual void printCurrentTestEnded(const TestResult& res) _override; - virtual void printCurrentGroupStarted(const UtestShell& test) _override; - virtual void printCurrentGroupEnded(const TestResult& res) _override; + virtual void printCurrentTestStarted(const UtestShell& test) CPPUTEST_OVERRIDE; + virtual void printCurrentTestEnded(const TestResult& res) CPPUTEST_OVERRIDE; + virtual void printCurrentGroupStarted(const UtestShell& test) CPPUTEST_OVERRIDE; + virtual void printCurrentGroupEnded(const TestResult& res) CPPUTEST_OVERRIDE; - virtual void printFailure(const TestFailure& failure) _override; + virtual void printFailure(const TestFailure& failure) CPPUTEST_OVERRIDE; protected: diff --git a/include/CppUTest/TestFailure.h b/include/CppUTest/TestFailure.h index f13714f51..7dc816f2c 100644 --- a/include/CppUTest/TestFailure.h +++ b/include/CppUTest/TestFailure.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -38,6 +38,10 @@ #include "SimpleString.h" +#if CPPUTEST_USE_STD_CPP_LIB +#include +#endif + class UtestShell; class TestOutput; @@ -45,40 +49,34 @@ class TestFailure { public: - TestFailure(UtestShell*, const char* fileName, int lineNumber, - const SimpleString& theMessage); + TestFailure(UtestShell*, const char* fileName, size_t lineNumber, const SimpleString& theMessage); TestFailure(UtestShell*, const SimpleString& theMessage); - TestFailure(UtestShell*, const char* fileName, int lineNumber); + TestFailure(UtestShell*, const char* fileName, size_t lineNumber); TestFailure(const TestFailure&); virtual ~TestFailure(); virtual SimpleString getFileName() const; virtual SimpleString getTestName() const; virtual SimpleString getTestNameOnly() const; - virtual int getFailureLineNumber() const; + virtual size_t getFailureLineNumber() const; virtual SimpleString getMessage() const; virtual SimpleString getTestFileName() const; - virtual int getTestLineNumber() const; + virtual size_t getTestLineNumber() const; bool isOutsideTestFile() const; bool isInHelperFunction() const; protected: - enum DifferenceFormat - { - DIFFERENCE_STRING, DIFFERENCE_BINARY - }; - SimpleString createButWasString(const SimpleString& expected, const SimpleString& actual); - SimpleString createDifferenceAtPosString(const SimpleString& actual, size_t position, DifferenceFormat format = DIFFERENCE_STRING); + SimpleString createDifferenceAtPosString(const SimpleString& actual, size_t offset, size_t reportedPosition); SimpleString createUserText(const SimpleString& text); SimpleString testName_; SimpleString testNameOnly_; SimpleString fileName_; - int lineNumber_; + size_t lineNumber_; SimpleString testFileName_; - int testLineNumber_; + size_t testLineNumber_; SimpleString message_; TestFailure& operator=(const TestFailure&); @@ -88,99 +86,115 @@ class TestFailure class EqualsFailure: public TestFailure { public: - EqualsFailure(UtestShell*, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text); - EqualsFailure(UtestShell*, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); + EqualsFailure(UtestShell*, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text); + EqualsFailure(UtestShell*, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); }; class DoublesEqualFailure: public TestFailure { public: - DoublesEqualFailure(UtestShell*, const char* fileName, int lineNumber, double expected, double actual, double threshold, const SimpleString& text); + DoublesEqualFailure(UtestShell*, const char* fileName, size_t lineNumber, double expected, double actual, double threshold, const SimpleString& text); }; class CheckEqualFailure : public TestFailure { public: - CheckEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); + CheckEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); }; -class ContainsFailure: public TestFailure +class ComparisonFailure : public TestFailure { public: - ContainsFailure(UtestShell*, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); + ComparisonFailure(UtestShell* test, const char *fileName, size_t lineNumber, const SimpleString& checkString, const SimpleString& comparisonString, const SimpleString& text); +}; +class ContainsFailure: public TestFailure +{ +public: + ContainsFailure(UtestShell*, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); }; class CheckFailure : public TestFailure { public: - CheckFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& checkString, const SimpleString& conditionString, const SimpleString& textString = ""); + CheckFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& checkString, const SimpleString& conditionString, const SimpleString& textString = ""); }; class FailFailure : public TestFailure { public: - FailFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& message); + FailFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& message); }; class LongsEqualFailure : public TestFailure { public: - LongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, long expected, long actual, const SimpleString& text); + LongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, long expected, long actual, const SimpleString& text); }; class UnsignedLongsEqualFailure : public TestFailure { public: - UnsignedLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, unsigned long expected, unsigned long actual, const SimpleString& text); + UnsignedLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, unsigned long expected, unsigned long actual, const SimpleString& text); }; class LongLongsEqualFailure : public TestFailure { public: - LongLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, cpputest_longlong expected, cpputest_longlong actual, const SimpleString& text); + LongLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, cpputest_longlong expected, cpputest_longlong actual, const SimpleString& text); }; class UnsignedLongLongsEqualFailure : public TestFailure { public: - UnsignedLongLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, cpputest_ulonglong expected, cpputest_ulonglong actual, const SimpleString& text); + UnsignedLongLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, cpputest_ulonglong expected, cpputest_ulonglong actual, const SimpleString& text); }; class SignedBytesEqualFailure : public TestFailure { public: - SignedBytesEqualFailure (UtestShell* test, const char* fileName, int lineNumber, signed char expected, signed char actual, const SimpleString& text); + SignedBytesEqualFailure (UtestShell* test, const char* fileName, size_t lineNumber, signed char expected, signed char actual, const SimpleString& text); }; class StringEqualFailure : public TestFailure { public: - StringEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text); + StringEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text); }; class StringEqualNoCaseFailure : public TestFailure { public: - StringEqualNoCaseFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text); + StringEqualNoCaseFailure(UtestShell* test, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text); }; class BinaryEqualFailure : public TestFailure { public: - BinaryEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const unsigned char* expected, const unsigned char* actual, size_t size, const SimpleString& text); + BinaryEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const unsigned char* expected, const unsigned char* actual, size_t size, const SimpleString& text); }; class BitsEqualFailure : public TestFailure { public: - BitsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const SimpleString& text); + BitsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const SimpleString& text); }; class FeatureUnsupportedFailure : public TestFailure { public: - FeatureUnsupportedFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& featureName, const SimpleString& text); + FeatureUnsupportedFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& featureName, const SimpleString& text); }; +#if CPPUTEST_HAVE_EXCEPTIONS +class UnexpectedExceptionFailure : public TestFailure +{ +public: + UnexpectedExceptionFailure(UtestShell* test); +#if CPPUTEST_USE_STD_CPP_LIB + UnexpectedExceptionFailure(UtestShell* test, const std::exception &e); +#endif +}; +#endif + #endif diff --git a/include/CppUTest/TestFilter.h b/include/CppUTest/TestFilter.h index 6f92a00bd..730f52e14 100644 --- a/include/CppUTest/TestFilter.h +++ b/include/CppUTest/TestFilter.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/include/CppUTest/TestHarness.h b/include/CppUTest/TestHarness.h index 8eb5b29bf..a4f1a8f71 100644 --- a/include/CppUTest/TestHarness.h +++ b/include/CppUTest/TestHarness.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/include/CppUTest/TestHarness_c.h b/include/CppUTest/TestHarness_c.h index 50c6cd218..f3a64cf83 100644 --- a/include/CppUTest/TestHarness_c.h +++ b/include/CppUTest/TestHarness_c.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -36,29 +36,95 @@ #include "CppUTestConfig.h" +#define CHECK_EQUAL_C_BOOL(expected,actual) \ + CHECK_EQUAL_C_BOOL_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_BOOL_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_BOOL_LOCATION(expected,actual,text,__FILE__,__LINE__) + #define CHECK_EQUAL_C_INT(expected,actual) \ - CHECK_EQUAL_C_INT_LOCATION(expected,actual,__FILE__,__LINE__) + CHECK_EQUAL_C_INT_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_INT_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_INT_LOCATION(expected,actual,text,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_UINT(expected,actual) \ + CHECK_EQUAL_C_UINT_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_UINT_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_UINT_LOCATION(expected,actual,text,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_LONG(expected,actual) \ + CHECK_EQUAL_C_LONG_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_LONG_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_LONG_LOCATION(expected,actual,text,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_ULONG(expected,actual) \ + CHECK_EQUAL_C_ULONG_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_ULONG_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_ULONG_LOCATION(expected,actual,text,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_LONGLONG(expected,actual) \ + CHECK_EQUAL_C_LONGLONG_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_LONGLONG_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_LONGLONG_LOCATION(expected,actual,text,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_ULONGLONG(expected,actual) \ + CHECK_EQUAL_C_ULONGLONG_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_ULONGLONG_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_ULONGLONG_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_REAL(expected,actual,threshold) \ - CHECK_EQUAL_C_REAL_LOCATION(expected,actual,threshold,__FILE__,__LINE__) + CHECK_EQUAL_C_REAL_LOCATION(expected,actual,threshold,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_REAL_TEXT(expected,actual,threshold,text) \ + CHECK_EQUAL_C_REAL_LOCATION(expected,actual,threshold,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_CHAR(expected,actual) \ - CHECK_EQUAL_C_CHAR_LOCATION(expected,actual,__FILE__,__LINE__) + CHECK_EQUAL_C_CHAR_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_CHAR_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_CHAR_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_UBYTE(expected,actual) \ - CHECK_EQUAL_C_UBYTE_LOCATION(expected,actual,__FILE__,__LINE__) + CHECK_EQUAL_C_UBYTE_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_UBYTE_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_UBYTE_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_SBYTE(expected,actual) \ - CHECK_EQUAL_C_SBYTE_LOCATION(expected,actual,__FILE__,__LINE__) + CHECK_EQUAL_C_SBYTE_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_SBYTE_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_SBYTE_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_STRING(expected,actual) \ - CHECK_EQUAL_C_STRING_LOCATION(expected,actual,__FILE__,__LINE__) + CHECK_EQUAL_C_STRING_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_STRING_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_STRING_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_POINTER(expected,actual) \ - CHECK_EQUAL_C_POINTER_LOCATION(expected,actual,__FILE__,__LINE__) + CHECK_EQUAL_C_POINTER_LOCATION(expected,actual,NULL,__FILE__,__LINE__) + +#define CHECK_EQUAL_C_POINTER_TEXT(expected,actual,text) \ + CHECK_EQUAL_C_POINTER_LOCATION(expected,actual,text,__FILE__,__LINE__) -#define CHECK_EQUAL_C_BITS(expected, actual, mask)\ - CHECK_EQUAL_C_BITS_LOCATION(expected, actual, mask, sizeof(actual), __FILE__, __LINE__) +#define CHECK_EQUAL_C_MEMCMP(expected, actual, size) \ + CHECK_EQUAL_C_MEMCMP_LOCATION(expected, actual, size, NULL, __FILE__, __LINE__) + +#define CHECK_EQUAL_C_MEMCMP_TEXT(expected, actual, size, text) \ + CHECK_EQUAL_C_MEMCMP_LOCATION(expected, actual, size, text, __FILE__, __LINE__) + +#define CHECK_EQUAL_C_BITS(expected, actual, mask) \ + CHECK_EQUAL_C_BITS_LOCATION(expected, actual, mask, sizeof(actual), NULL, __FILE__, __LINE__) + +#define CHECK_EQUAL_C_BITS_TEXT(expected, actual, mask, text) \ + CHECK_EQUAL_C_BITS_LOCATION(expected, actual, mask, sizeof(actual), text, __FILE__, __LINE__) #define FAIL_TEXT_C(text) \ FAIL_TEXT_C_LOCATION(text,__FILE__,__LINE__) @@ -67,8 +133,10 @@ FAIL_C_LOCATION(__FILE__,__LINE__) #define CHECK_C(condition) \ - CHECK_C_LOCATION(condition, #condition, __FILE__,__LINE__) + CHECK_C_LOCATION(condition, #condition, NULL, __FILE__,__LINE__) +#define CHECK_C_TEXT(condition, text) \ + CHECK_C_LOCATION(condition, #condition, text, __FILE__, __LINE__) /****************************************************************************** * @@ -79,15 +147,19 @@ /* For use in C file */ #define TEST_GROUP_C_SETUP(group_name) \ extern void group_##group_name##_setup_wrapper_c(void); \ - void group_##group_name##_setup_wrapper_c() + void group_##group_name##_setup_wrapper_c(void) #define TEST_GROUP_C_TEARDOWN(group_name) \ extern void group_##group_name##_teardown_wrapper_c(void); \ - void group_##group_name##_teardown_wrapper_c() + void group_##group_name##_teardown_wrapper_c(void) #define TEST_C(group_name, test_name) \ extern void test_##group_name##_##test_name##_wrapper_c(void);\ - void test_##group_name##_##test_name##_wrapper_c() + void test_##group_name##_##test_name##_wrapper_c(void) + +#define IGNORE_TEST_C(group_name, test_name) \ + extern void ignore_##group_name##_##test_name##_wrapper_c(void);\ + void ignore_##group_name##_##test_name##_wrapper_c(void) /* For use in C++ file */ @@ -98,12 +170,12 @@ TEST_GROUP(group_name) #define TEST_GROUP_C_SETUP_WRAPPER(group_name) \ - void setup() { \ + void setup() CPPUTEST_OVERRIDE { \ group_##group_name##_setup_wrapper_c(); \ } #define TEST_GROUP_C_TEARDOWN_WRAPPER(group_name) \ - void teardown() { \ + void teardown() CPPUTEST_OVERRIDE { \ group_##group_name##_teardown_wrapper_c(); \ } @@ -113,6 +185,12 @@ test_##group_name##_##test_name##_wrapper_c(); \ } +#define IGNORE_TEST_C_WRAPPER(group_name, test_name) \ + extern "C" void ignore_##group_name##_##test_name##_wrapper_c(); \ + IGNORE_TEST(group_name, test_name) { \ + ignore_##group_name##_##test_name##_wrapper_c(); \ + } + #ifdef __cplusplus extern "C" { @@ -120,39 +198,38 @@ extern "C" /* CHECKS that can be used from C code */ -extern void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, - const char* fileName, int lineNumber); -extern void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, - double threshold, const char* fileName, int lineNumber); -extern void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, - const char* fileName, int lineNumber); -extern void CHECK_EQUAL_C_UBYTE_LOCATION(unsigned char expected, unsigned char actual, - const char* fileName, int lineNumber); -extern void CHECK_EQUAL_C_SBYTE_LOCATION(signed char expected, signed char actual, - const char* fileName, int lineNumber); -extern void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, - const char* actual, const char* fileName, int lineNumber); -extern void CHECK_EQUAL_C_POINTER_LOCATION(const void* expected, - const void* actual, const char* fileName, int lineNumber); -extern void CHECK_EQUAL_C_BITS_LOCATION(unsigned int expected, unsigned int actual, - unsigned int mask, size_t size, const char* fileName, int lineNumber); -extern void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, - int lineNumber); -extern void FAIL_C_LOCATION(const char* fileName, int lineNumber); -extern void CHECK_C_LOCATION(int condition, const char* conditionString, - const char* fileName, int lineNumber); +extern void CHECK_EQUAL_C_BOOL_LOCATION(int expected, int actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_UINT_LOCATION(unsigned int expected, unsigned int actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_LONG_LOCATION(long expected, long actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_ULONG_LOCATION(unsigned long expected, unsigned long actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_LONGLONG_LOCATION(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_ULONGLONG_LOCATION(cpputest_ulonglong expected, cpputest_ulonglong actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_UBYTE_LOCATION(unsigned char expected, unsigned char actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_SBYTE_LOCATION(signed char expected, signed char actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_POINTER_LOCATION(const void* expected, const void* actual, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_MEMCMP_LOCATION(const void* expected, const void* actual, size_t size, const char* text, const char* fileName, size_t lineNumber); +extern void CHECK_EQUAL_C_BITS_LOCATION(unsigned int expected, unsigned int actual, unsigned int mask, size_t size, const char* text, const char* fileName, size_t lineNumber); +extern void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, size_t lineNumber); +extern void FAIL_C_LOCATION(const char* fileName, size_t lineNumber); +extern void CHECK_C_LOCATION(int condition, const char* conditionString, const char* text, const char* fileName, size_t lineNumber); extern void* cpputest_malloc(size_t size); +extern char* cpputest_strdup(const char* str); +extern char* cpputest_strndup(const char* str, size_t n); extern void* cpputest_calloc(size_t num, size_t size); extern void* cpputest_realloc(void* ptr, size_t size); extern void cpputest_free(void* buffer); -extern void* cpputest_malloc_location(size_t size, const char* file, int line); -extern void* cpputest_calloc_location(size_t num, size_t size, - const char* file, int line); -extern void* cpputest_realloc_location(void* memory, size_t size, - const char* file, int line); -extern void cpputest_free_location(void* buffer, const char* file, int line); +extern void* cpputest_malloc_location(size_t size, const char* file, size_t line); +extern char* cpputest_strdup_location(const char* str, const char* file, size_t line); +extern char* cpputest_strndup_location(const char* str, size_t n, const char* file, size_t line); +extern void* cpputest_calloc_location(size_t num, size_t size, const char* file, size_t line); +extern void* cpputest_realloc_location(void* memory, size_t size, const char* file, size_t line); +extern void cpputest_free_location(void* buffer, const char* file, size_t line); void cpputest_malloc_set_out_of_memory(void); void cpputest_malloc_set_not_out_of_memory(void); @@ -171,7 +248,7 @@ int cpputest_malloc_get_count(void); */ #ifndef PUNUSED -#if defined(__GNUC__) +#if defined(__GNUC__) || defined(__clang__) # define PUNUSED(x) PUNUSED_ ##x __attribute__((unused)) #else # define PUNUSED(x) x diff --git a/include/CppUTest/TestMemoryAllocator.h b/include/CppUTest/TestMemoryAllocator.h index e81a9ac5f..8f65bf508 100644 --- a/include/CppUTest/TestMemoryAllocator.h +++ b/include/CppUTest/TestMemoryAllocator.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -46,6 +46,19 @@ extern TestMemoryAllocator* getCurrentMallocAllocator(); extern void setCurrentMallocAllocatorToDefault(); extern TestMemoryAllocator* defaultMallocAllocator(); +class GlobalMemoryAllocatorStash +{ +public: + GlobalMemoryAllocatorStash(); + void save(); + void restore(); + +private: + TestMemoryAllocator* originalMallocAllocator; + TestMemoryAllocator* originalNewAllocator; + TestMemoryAllocator* originalNewArrayAllocator; +}; + class TestMemoryAllocator { public: @@ -53,18 +66,20 @@ class TestMemoryAllocator virtual ~TestMemoryAllocator(); bool hasBeenDestroyed(); - virtual char* alloc_memory(size_t size, const char* file, int line); - virtual void free_memory(char* memory, const char* file, int line); + virtual char* alloc_memory(size_t size, const char* file, size_t line); + virtual void free_memory(char* memory, size_t size, const char* file, size_t line); - virtual const char* name(); - virtual const char* alloc_name(); - virtual const char* free_name(); + virtual const char* name() const; + virtual const char* alloc_name() const; + virtual const char* free_name() const; virtual bool isOfEqualType(TestMemoryAllocator* allocator); virtual char* allocMemoryLeakNode(size_t size); virtual void freeMemoryLeakNode(char* memory); + virtual TestMemoryAllocator* actualAllocator(); + protected: const char* name_; @@ -74,15 +89,34 @@ class TestMemoryAllocator bool hasBeenDestroyed_; }; +class MemoryLeakAllocator : public TestMemoryAllocator +{ +public: + MemoryLeakAllocator(TestMemoryAllocator* originalAllocator); + virtual ~MemoryLeakAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; + + virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; + virtual void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; + + virtual const char* name() const CPPUTEST_OVERRIDE; + virtual const char* alloc_name() const CPPUTEST_OVERRIDE; + virtual const char* free_name() const CPPUTEST_OVERRIDE; + + virtual TestMemoryAllocator* actualAllocator() CPPUTEST_OVERRIDE; +private: + TestMemoryAllocator* originalAllocator_; +}; + class CrashOnAllocationAllocator : public TestMemoryAllocator { unsigned allocationToCrashOn_; public: CrashOnAllocationAllocator(); + virtual ~CrashOnAllocationAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void setNumberToCrashOn(unsigned allocationToCrashOn); - virtual char* alloc_memory(size_t size, const char* file, int line) _override; + virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; }; @@ -90,8 +124,10 @@ class NullUnknownAllocator: public TestMemoryAllocator { public: NullUnknownAllocator(); - virtual char* alloc_memory(size_t size, const char* file, int line) _override; - virtual void free_memory(char* memory, const char* file, int line) _override; + virtual ~NullUnknownAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; + + virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; + virtual void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; static TestMemoryAllocator* defaultAllocator(); }; @@ -102,12 +138,13 @@ class FailableMemoryAllocator: public TestMemoryAllocator { public: FailableMemoryAllocator(const char* name_str = "failable alloc", const char* alloc_name_str = "alloc", const char* free_name_str = "free"); + virtual ~FailableMemoryAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; - virtual char* alloc_memory(size_t size, const char* file, int line); - virtual char* allocMemoryLeakNode(size_t size); + virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; + virtual char* allocMemoryLeakNode(size_t size) CPPUTEST_OVERRIDE; virtual void failAllocNumber(int number); - virtual void failNthAllocAt(int allocationNumber, const char* file, int line); + virtual void failNthAllocAt(int allocationNumber, const char* file, size_t line); virtual void checkAllFailedAllocsWereDone(); virtual void clearFailedAllocs(); @@ -118,5 +155,107 @@ class FailableMemoryAllocator: public TestMemoryAllocator int currentAllocNumber_; }; +struct MemoryAccountantAllocationNode; + +class MemoryAccountant +{ +public: + MemoryAccountant(); + ~MemoryAccountant(); + + void useCacheSizes(size_t sizes[], size_t length); + + void clear(); + + void alloc(size_t size); + void dealloc(size_t size); + + size_t totalAllocationsOfSize(size_t size) const; + size_t totalDeallocationsOfSize(size_t size) const; + size_t maximumAllocationAtATimeOfSize(size_t size) const; + + size_t totalAllocations() const; + size_t totalDeallocations() const; + + SimpleString report() const; + + void setAllocator(TestMemoryAllocator* allocator); +private: + MemoryAccountantAllocationNode* findOrCreateNodeOfSize(size_t size); + MemoryAccountantAllocationNode* findNodeOfSize(size_t size) const; + + MemoryAccountantAllocationNode* createNewAccountantAllocationNode(size_t size, MemoryAccountantAllocationNode* next) const; + void destroyAccountantAllocationNode(MemoryAccountantAllocationNode* node) const; + + void createCacheSizeNodes(size_t sizes[], size_t length); + + MemoryAccountantAllocationNode* head_; + TestMemoryAllocator* allocator_; + bool useCacheSizes_; + + SimpleString reportNoAllocations() const; + SimpleString reportTitle() const; + SimpleString reportHeader() const; + SimpleString reportFooter() const; + SimpleString stringSize(size_t size) const; + +}; + +struct AccountingTestMemoryAllocatorMemoryNode; + +class AccountingTestMemoryAllocator : public TestMemoryAllocator +{ +public: + AccountingTestMemoryAllocator(MemoryAccountant& accountant, TestMemoryAllocator* originalAllocator); + virtual ~AccountingTestMemoryAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; + + virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; + virtual void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; + + virtual TestMemoryAllocator* actualAllocator() CPPUTEST_OVERRIDE; + TestMemoryAllocator* originalAllocator(); + + virtual const char* alloc_name() const CPPUTEST_OVERRIDE; + virtual const char* free_name() const CPPUTEST_OVERRIDE; +private: + + void addMemoryToMemoryTrackingToKeepTrackOfSize(char* memory, size_t size); + size_t removeMemoryFromTrackingAndReturnAllocatedSize(char* memory); + + size_t removeNextNodeAndReturnSize(AccountingTestMemoryAllocatorMemoryNode* node); + size_t removeHeadAndReturnSize(); + + MemoryAccountant& accountant_; + TestMemoryAllocator* originalAllocator_; + AccountingTestMemoryAllocatorMemoryNode* head_; +}; + +class GlobalMemoryAccountant +{ +public: + GlobalMemoryAccountant(); + ~GlobalMemoryAccountant(); + + void useCacheSizes(size_t sizes[], size_t length); + + void start(); + void stop(); + SimpleString report(); + SimpleString reportWithCacheSizes(size_t sizes[], size_t length); + + TestMemoryAllocator* getMallocAllocator(); + TestMemoryAllocator* getNewAllocator(); + TestMemoryAllocator* getNewArrayAllocator(); + +private: + + void restoreMemoryAllocators(); + + MemoryAccountant accountant_; + AccountingTestMemoryAllocator* mallocAllocator_; + AccountingTestMemoryAllocator* newAllocator_; + AccountingTestMemoryAllocator* newArrayAllocator_; +}; + #endif diff --git a/include/CppUTest/TestOutput.h b/include/CppUTest/TestOutput.h index 9f758acc5..47fbe02ea 100644 --- a/include/CppUTest/TestOutput.h +++ b/include/CppUTest/TestOutput.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -46,6 +46,9 @@ class TestResult; class TestOutput { public: + enum WorkingEnvironment {visualStudio, eclipse, detectEnvironment}; + enum VerbosityLevel {level_quiet, level_verbose, level_veryVerbose}; + explicit TestOutput(); virtual ~TestOutput(); @@ -56,40 +59,41 @@ class TestOutput virtual void printCurrentGroupStarted(const UtestShell& test); virtual void printCurrentGroupEnded(const TestResult& res); - virtual void verbose(); + virtual void verbose(VerbosityLevel level); virtual void color(); virtual void printBuffer(const char*)=0; virtual void print(const char*); virtual void print(long); + virtual void print(size_t); virtual void printDouble(double); virtual void printFailure(const TestFailure& failure); - virtual void printTestRun(int number, int total); + virtual void printTestRun(size_t number, size_t total); virtual void setProgressIndicator(const char*); - virtual void flush()=0; + virtual void printVeryVerbose(const char*); - enum WorkingEnvironment {visualStudio, eclipse, detectEnvironment}; + virtual void flush()=0; static void setWorkingEnvironment(WorkingEnvironment workEnvironment); static WorkingEnvironment getWorkingEnvironment(); protected: - virtual void printEclipseErrorInFileOnLine(SimpleString file, int lineNumber); - virtual void printVisualStudioErrorInFileOnLine(SimpleString file, int lineNumber); + virtual void printEclipseErrorInFileOnLine(SimpleString file, size_t lineNumber); + virtual void printVisualStudioErrorInFileOnLine(SimpleString file, size_t lineNumber); virtual void printProgressIndicator(); void printFileAndLineForTestAndFailure(const TestFailure& failure); void printFileAndLineForFailure(const TestFailure& failure); void printFailureInTest(SimpleString testName); void printFailureMessage(SimpleString reason); - void printErrorInFileOnLineFormattedForWorkingEnvironment(SimpleString testFile, int lineNumber); + void printErrorInFileOnLineFormattedForWorkingEnvironment(SimpleString testFile, size_t lineNumber); TestOutput(const TestOutput&); TestOutput& operator=(const TestOutput&); int dotCount_; - bool verbose_; + VerbosityLevel verbose_; bool color_; const char* progressIndication_; @@ -113,12 +117,12 @@ class ConsoleTestOutput: public TestOutput explicit ConsoleTestOutput() { } - virtual ~ConsoleTestOutput() + virtual ~ConsoleTestOutput() CPPUTEST_DESTRUCTOR_OVERRIDE { } - virtual void printBuffer(const char* s) _override; - virtual void flush() _override; + virtual void printBuffer(const char* s) CPPUTEST_OVERRIDE; + virtual void flush() CPPUTEST_OVERRIDE; private: ConsoleTestOutput(const ConsoleTestOutput&); @@ -141,14 +145,14 @@ class StringBufferTestOutput: public TestOutput { } - virtual ~StringBufferTestOutput(); + virtual ~StringBufferTestOutput() CPPUTEST_DESTRUCTOR_OVERRIDE; - void printBuffer(const char* s) _override + void printBuffer(const char* s) CPPUTEST_OVERRIDE { output += s; } - void flush() _override + void flush() CPPUTEST_OVERRIDE { output = ""; } @@ -174,26 +178,29 @@ class CompositeTestOutput : public TestOutput virtual void setOutputTwo(TestOutput* output); CompositeTestOutput(); - virtual ~CompositeTestOutput(); + virtual ~CompositeTestOutput() CPPUTEST_DESTRUCTOR_OVERRIDE; - virtual void printTestsStarted(); - virtual void printTestsEnded(const TestResult& result); + virtual void printTestsStarted() CPPUTEST_OVERRIDE; + virtual void printTestsEnded(const TestResult& result) CPPUTEST_OVERRIDE; - virtual void printCurrentTestStarted(const UtestShell& test); - virtual void printCurrentTestEnded(const TestResult& res); - virtual void printCurrentGroupStarted(const UtestShell& test); - virtual void printCurrentGroupEnded(const TestResult& res); + virtual void printCurrentTestStarted(const UtestShell& test) CPPUTEST_OVERRIDE; + virtual void printCurrentTestEnded(const TestResult& res) CPPUTEST_OVERRIDE; + virtual void printCurrentGroupStarted(const UtestShell& test) CPPUTEST_OVERRIDE; + virtual void printCurrentGroupEnded(const TestResult& res) CPPUTEST_OVERRIDE; - virtual void verbose(); - virtual void color(); - virtual void printBuffer(const char*); - virtual void print(const char*); - virtual void print(long); - virtual void printDouble(double); - virtual void printFailure(const TestFailure& failure); - virtual void setProgressIndicator(const char*); + virtual void verbose(VerbosityLevel level) CPPUTEST_OVERRIDE; + virtual void color() CPPUTEST_OVERRIDE; + virtual void printBuffer(const char*) CPPUTEST_OVERRIDE; + virtual void print(const char*) CPPUTEST_OVERRIDE; + virtual void print(long) CPPUTEST_OVERRIDE; + virtual void print(size_t) CPPUTEST_OVERRIDE; + virtual void printDouble(double) CPPUTEST_OVERRIDE; + virtual void printFailure(const TestFailure& failure) CPPUTEST_OVERRIDE; + virtual void setProgressIndicator(const char*) CPPUTEST_OVERRIDE; + + virtual void printVeryVerbose(const char*) CPPUTEST_OVERRIDE; - virtual void flush(); + virtual void flush() CPPUTEST_OVERRIDE; protected: CompositeTestOutput(const TestOutput&); diff --git a/include/CppUTest/TestPlugin.h b/include/CppUTest/TestPlugin.h index b3f85ee74..d0b3c41b3 100644 --- a/include/CppUTest/TestPlugin.h +++ b/include/CppUTest/TestPlugin.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -28,6 +28,8 @@ #ifndef D_TestPlugin_h #define D_TestPlugin_h +#include "SimpleString.h" + class UtestShell; class TestResult; @@ -46,14 +48,14 @@ class TestPlugin { } - virtual bool parseArguments(int /* ac */, const char** /* av */, int /* index */ ) + virtual bool parseArguments(int /* ac */, const char *const * /* av */, int /* index */ ) { return false; } virtual void runAllPreTestAction(UtestShell&, TestResult&); virtual void runAllPostTestAction(UtestShell&, TestResult&); - virtual bool parseAllArguments(int ac, const char** av, int index); + virtual bool parseAllArguments(int ac, const char *const *av, int index); virtual bool parseAllArguments(int ac, char** av, int index); virtual TestPlugin* addPlugin(TestPlugin*); @@ -90,7 +92,7 @@ class SetPointerPlugin: public TestPlugin { public: SetPointerPlugin(const SimpleString& name); - virtual void postTestAction(UtestShell&, TestResult&) _override; + virtual void postTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE; enum { @@ -98,7 +100,11 @@ class SetPointerPlugin: public TestPlugin }; }; -#define UT_PTR_SET(a, b) { CppUTestStore( (void**)&a ); a = b; } +#define UT_PTR_SET(a, b) \ + do { \ + CppUTestStore((void**)&(a)); \ + (a) = b; \ + } while (0) ///////////// Null Plugin @@ -108,8 +114,8 @@ class NullTestPlugin: public TestPlugin NullTestPlugin(); - virtual void runAllPreTestAction(UtestShell& test, TestResult& result) _override; - virtual void runAllPostTestAction(UtestShell& test, TestResult& result) _override; + virtual void runAllPreTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; + virtual void runAllPostTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; static NullTestPlugin* instance(); }; diff --git a/include/CppUTest/TestRegistry.h b/include/CppUTest/TestRegistry.h old mode 100755 new mode 100644 index c451d8467..20575dd5a --- a/include/CppUTest/TestRegistry.h +++ b/include/CppUTest/TestRegistry.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -33,6 +33,7 @@ #ifndef D_TestRegistry_h #define D_TestRegistry_h +#include "StandardCLibrary.h" #include "SimpleString.h" #include "TestFilter.h" @@ -48,10 +49,13 @@ class TestRegistry virtual void addTest(UtestShell *test); virtual void unDoLastAddTest(); - virtual int countTests(); + virtual size_t countTests(); virtual void runAllTests(TestResult& result); + virtual void shuffleTests(size_t seed); + virtual void reverseTests(); virtual void listTestGroupNames(TestResult& result); virtual void listTestGroupAndCaseNames(TestResult& result); + virtual void listTestLocations(TestResult& result); virtual void setNameFilters(const TestFilter* filters); virtual void setGroupFilters(const TestFilter* filters); virtual void installPlugin(TestPlugin* plugin); @@ -73,6 +77,7 @@ class TestRegistry virtual void setRunTestsInSeperateProcess(); int getCurrentRepetition(); void setRunIgnored(); + private: bool testShouldRun(UtestShell* test, TestResult& result); diff --git a/include/CppUTest/TestResult.h b/include/CppUTest/TestResult.h index f61194648..fc6e63fd6 100644 --- a/include/CppUTest/TestResult.h +++ b/include/CppUTest/TestResult.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -59,52 +59,58 @@ class TestResult virtual void countIgnored(); virtual void addFailure(const TestFailure& failure); virtual void print(const char* text); + virtual void printVeryVerbose(const char* text); - int getTestCount() const + size_t getTestCount() const { return testCount_; } - int getRunCount() const + size_t getRunCount() const { return runCount_; } - int getCheckCount() const + size_t getCheckCount() const { return checkCount_; } - int getFilteredOutCount() const + size_t getFilteredOutCount() const { return filteredOutCount_; } - int getIgnoredCount() const + size_t getIgnoredCount() const { return ignoredCount_; } - int getFailureCount() const + size_t getFailureCount() const { return failureCount_; } - long getTotalExecutionTime() const; - void setTotalExecutionTime(long exTime); + bool isFailure() const + { + return (getFailureCount() != 0) || (getRunCount() + getIgnoredCount() == 0); + } + + size_t getTotalExecutionTime() const; + void setTotalExecutionTime(size_t exTime); - long getCurrentTestTotalExecutionTime() const; - long getCurrentGroupTotalExecutionTime() const; + size_t getCurrentTestTotalExecutionTime() const; + size_t getCurrentGroupTotalExecutionTime() const; private: TestOutput& output_; - int testCount_; - int runCount_; - int checkCount_; - int failureCount_; - int filteredOutCount_; - int ignoredCount_; - long totalExecutionTime_; - long timeStarted_; - long currentTestTimeStarted_; - long currentTestTotalExecutionTime_; - long currentGroupTimeStarted_; - long currentGroupTotalExecutionTime_; + size_t testCount_; + size_t runCount_; + size_t checkCount_; + size_t failureCount_; + size_t filteredOutCount_; + size_t ignoredCount_; + size_t totalExecutionTime_; + size_t timeStarted_; + size_t currentTestTimeStarted_; + size_t currentTestTotalExecutionTime_; + size_t currentGroupTimeStarted_; + size_t currentGroupTotalExecutionTime_; }; #endif diff --git a/include/CppUTest/TestTestingFixture.h b/include/CppUTest/TestTestingFixture.h old mode 100755 new mode 100644 index 53874dd09..2c7cdd5ba --- a/include/CppUTest/TestTestingFixture.h +++ b/include/CppUTest/TestTestingFixture.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -35,106 +35,47 @@ class TestTestingFixture { public: - TestTestingFixture() - { - output_ = new StringBufferTestOutput(); - result_ = new TestResult(*output_); - genTest_ = new ExecFunctionTestShell(); - registry_ = new TestRegistry(); - - registry_->setCurrentRegistry(registry_); - registry_->addTest(genTest_); - - lineOfCodeExecutedAfterCheck = false; - } - - virtual ~TestTestingFixture() - { - registry_->setCurrentRegistry(0); - delete registry_; - delete result_; - delete output_; - delete genTest_; - } - - void addTest(UtestShell * test) - { - registry_->addTest(test); - } - - void setTestFunction(void(*testFunction)()) - { - genTest_->testFunction_ = testFunction; - } - - void setSetup(void(*setupFunction)()) - { - genTest_->setup_ = setupFunction; - } - - void setTeardown(void(*teardownFunction)()) - { - genTest_->teardown_ = teardownFunction; - } - - void runTestWithMethod(void(*method)()) - { - setTestFunction(method); - runAllTests(); - } + TestTestingFixture(); + virtual ~TestTestingFixture(); + void flushOutputAndResetResult(); - void runAllTests() - { - registry_->runAllTests(*result_); - } + void addTest(UtestShell * test); + void installPlugin(TestPlugin* plugin); - int getFailureCount() - { - return result_->getFailureCount(); - } + void setTestFunction(void(*testFunction)()); + void setTestFunction(ExecFunction* testFunction); + void setSetup(void(*setupFunction)()); + void setTeardown(void(*teardownFunction)()); - int getCheckCount() - { - return result_->getCheckCount(); - } - - int getIgnoreCount() - { - return result_->getIgnoredCount(); - } - - bool hasTestFailed() - { - return genTest_->hasFailed(); - } + void setOutputVerbose(); + void setRunTestsInSeperateProcess(); - void assertPrintContains(const SimpleString& contains) - { - assertPrintContains(getOutput(), contains); - } + void runTestWithMethod(void(*method)()); + void runAllTests(); - const SimpleString& getOutput() - { - return output_->getOutput(); - } + size_t getFailureCount(); + size_t getCheckCount(); + size_t getIgnoreCount(); + size_t getRunCount(); + size_t getTestCount(); + const SimpleString& getOutput(); + TestRegistry* getRegistry(); - static void assertPrintContains(const SimpleString& output, const SimpleString& contains) - { - STRCMP_CONTAINS(contains.asCharString(), output.asCharString()); - } + bool hasTestFailed(); + void assertPrintContains(const SimpleString& contains); + void assertPrintContainsNot(const SimpleString& contains); + void checkTestFailsWithProperTestLocation(const char* text, const char* file, size_t line); - int getRunCount() - { - return result_->getRunCount(); - } + static void lineExecutedAfterCheck(); - void checkTestFailsWithProperTestLocation(const char* text, const char* file, int line); +private: + void clearExecFunction(); - static void lineExecutedAfterCheck(); static bool lineOfCodeExecutedAfterCheck; TestRegistry* registry_; ExecFunctionTestShell* genTest_; + bool ownsExecFunction_; StringBufferTestOutput* output_; TestResult * result_; }; diff --git a/include/CppUTest/Utest.h b/include/CppUTest/Utest.h old mode 100755 new mode 100644 index 7bb560fd9..02e865b76 --- a/include/CppUTest/Utest.h +++ b/include/CppUTest/Utest.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -69,15 +69,29 @@ class TestTerminator class NormalTestTerminator : public TestTerminator { public: - virtual void exitCurrentTest() const _override; - virtual ~NormalTestTerminator(); + virtual void exitCurrentTest() const CPPUTEST_OVERRIDE; + virtual ~NormalTestTerminator() CPPUTEST_DESTRUCTOR_OVERRIDE; }; class TestTerminatorWithoutExceptions : public TestTerminator { public: - virtual void exitCurrentTest() const _override; - virtual ~TestTerminatorWithoutExceptions(); + virtual void exitCurrentTest() const CPPUTEST_OVERRIDE; + virtual ~TestTerminatorWithoutExceptions() CPPUTEST_DESTRUCTOR_OVERRIDE; +}; + +class CrashingTestTerminator : public NormalTestTerminator +{ +public: + virtual void exitCurrentTest() const CPPUTEST_OVERRIDE; + virtual ~CrashingTestTerminator() CPPUTEST_DESTRUCTOR_OVERRIDE; +}; + +class CrashingTestTerminatorWithoutExceptions : public TestTerminatorWithoutExceptions +{ +public: + virtual void exitCurrentTest() const CPPUTEST_OVERRIDE; + virtual ~CrashingTestTerminatorWithoutExceptions() CPPUTEST_DESTRUCTOR_OVERRIDE; }; //////////////////// UtestShell @@ -87,49 +101,60 @@ class UtestShell public: static UtestShell *getCurrent(); + static const TestTerminator &getCurrentTestTerminator(); + static const TestTerminator &getCurrentTestTerminatorWithoutExceptions(); + + static void setCrashOnFail(); + static void restoreDefaultTestTerminator(); + + static void setRethrowExceptions(bool rethrowExceptions); + static bool isRethrowingExceptions(); + public: - UtestShell(const char* groupName, const char* testName, const char* fileName, int lineNumber); + UtestShell(const char* groupName, const char* testName, const char* fileName, size_t lineNumber); virtual ~UtestShell(); virtual UtestShell* addTest(UtestShell* test); virtual UtestShell *getNext() const; - virtual int countTests(); + virtual size_t countTests(); bool shouldRun(const TestFilter* groupFilters, const TestFilter* nameFilters) const; const SimpleString getName() const; const SimpleString getGroup() const; virtual SimpleString getFormattedName() const; const SimpleString getFile() const; - int getLineNumber() const; + size_t getLineNumber() const; virtual bool willRun() const; virtual bool hasFailed() const; void countCheck(); - virtual void assertTrue(bool condition, const char *checkString, const char *conditionString, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertCstrEqual(const char *expected, const char *actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertCstrNEqual(const char *expected, const char *actual, size_t length, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertCstrNoCaseEqual(const char *expected, const char *actual, const char* text, const char *fileName, int lineNumber); - virtual void assertCstrContains(const char *expected, const char *actual, const char* text, const char *fileName, int lineNumber); - virtual void assertCstrNoCaseContains(const char *expected, const char *actual, const char* text, const char *fileName, int lineNumber); - virtual void assertLongsEqual(long expected, long actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertUnsignedLongsEqual(unsigned long expected, unsigned long actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertLongLongsEqual(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertUnsignedLongLongsEqual(cpputest_ulonglong expected, cpputest_ulonglong actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertSignedBytesEqual(signed char expected, signed char actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertPointersEqual(const void *expected, const void *actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertFunctionPointersEqual(void (*expected)(), void (*actual)(), const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertDoublesEqual(double expected, double actual, double threshold, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertEquals(bool failed, const char* expected, const char* actual, const char* text, const char* file, int line, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertBinaryEqual(const void *expected, const void *actual, size_t length, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void assertBitsEqual(unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void fail(const char *text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); - virtual void exitTest(const TestTerminator& testTerminator = NormalTestTerminator()); - - virtual void print(const char *text, const char *fileName, int lineNumber); - virtual void print(const SimpleString & text, const char *fileName, int lineNumber); + virtual void assertTrue(bool condition, const char *checkString, const char *conditionString, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertCstrEqual(const char *expected, const char *actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertCstrNEqual(const char *expected, const char *actual, size_t length, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertCstrNoCaseEqual(const char *expected, const char *actual, const char* text, const char *fileName, size_t lineNumber); + virtual void assertCstrContains(const char *expected, const char *actual, const char* text, const char *fileName, size_t lineNumber); + virtual void assertCstrNoCaseContains(const char *expected, const char *actual, const char* text, const char *fileName, size_t lineNumber); + virtual void assertLongsEqual(long expected, long actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertUnsignedLongsEqual(unsigned long expected, unsigned long actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertLongLongsEqual(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertUnsignedLongLongsEqual(cpputest_ulonglong expected, cpputest_ulonglong actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertSignedBytesEqual(signed char expected, signed char actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertPointersEqual(const void *expected, const void *actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertFunctionPointersEqual(void (*expected)(), void (*actual)(), const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertDoublesEqual(double expected, double actual, double threshold, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertEquals(bool failed, const char* expected, const char* actual, const char* text, const char* file, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertBinaryEqual(const void *expected, const void *actual, size_t length, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertBitsEqual(unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void assertCompare(bool comparison, const char *checkString, const char *comparisonString, const char *text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void fail(const char *text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); + virtual void exitTest(const TestTerminator& testTerminator = getCurrentTestTerminator()); + + virtual void print(const char *text, const char *fileName, size_t lineNumber); + virtual void print(const SimpleString & text, const char *fileName, size_t lineNumber); + virtual void printVeryVerbose(const char* text); void setFileName(const char *fileName); - void setLineNumber(int lineNumber); + void setLineNumber(size_t lineNumber); void setGroupName(const char *groupName); void setTestName(const char *testName); @@ -151,9 +176,11 @@ class UtestShell virtual void failWith(const TestFailure& failure); virtual void failWith(const TestFailure& failure, const TestTerminator& terminator); + virtual void addFailure(const TestFailure& failure); + protected: UtestShell(); - UtestShell(const char *groupName, const char *testName, const char *fileName, int lineNumber, UtestShell *nextTest); + UtestShell(const char *groupName, const char *testName, const char *fileName, size_t lineNumber, UtestShell *nextTest); virtual SimpleString getMacroName() const; TestResult *getTestResult(); @@ -161,7 +188,7 @@ class UtestShell const char *group_; const char *name_; const char *file_; - int lineNumber_; + size_t lineNumber_; UtestShell *next_; bool isRunAsSeperateProcess_; bool hasFailed_; @@ -173,6 +200,9 @@ class UtestShell static UtestShell* currentTest_; static TestResult* testResult_; + static const TestTerminator *currentTestTerminator_; + static const TestTerminator *currentTestTerminatorWithoutExceptions_; + static bool rethrowExceptions_; }; @@ -185,29 +215,51 @@ class ExecFunctionTest : public Utest { public: ExecFunctionTest(ExecFunctionTestShell* shell); - void testBody() _override; - virtual void setup() _override; - virtual void teardown() _override; + void testBody() CPPUTEST_OVERRIDE; + virtual void setup() CPPUTEST_OVERRIDE; + virtual void teardown() CPPUTEST_OVERRIDE; private: ExecFunctionTestShell* shell_; }; +//////////////////// ExecFunction + +class ExecFunction +{ +public: + ExecFunction(); + virtual ~ExecFunction(); + + virtual void exec()=0; +}; + +class ExecFunctionWithoutParameters : public ExecFunction +{ +public: + void (*testFunction_)(); + + ExecFunctionWithoutParameters(void(*testFunction)()); + virtual ~ExecFunctionWithoutParameters() CPPUTEST_DESTRUCTOR_OVERRIDE; + + virtual void exec() CPPUTEST_OVERRIDE; +}; + //////////////////// ExecFunctionTestShell -class ExecFunctionTestShell: public UtestShell +class ExecFunctionTestShell : public UtestShell { public: void (*setup_)(); void (*teardown_)(); - void (*testFunction_)(); + ExecFunction* testFunction_; - ExecFunctionTestShell(void(*set)() = 0, void(*tear)() = 0) : - UtestShell("Generic", "Generic", "Generic", 1), setup_(set), teardown_( - tear), testFunction_(0) + ExecFunctionTestShell(void(*set)() = NULLPTR, void(*tear)() = NULLPTR) : + UtestShell("ExecFunction", "ExecFunction", "ExecFunction", 1), setup_(set), teardown_(tear), testFunction_(NULLPTR) { } - Utest* createTest() { return new ExecFunctionTest(this); } - virtual ~ExecFunctionTestShell(); + + Utest* createTest() CPPUTEST_OVERRIDE { return new ExecFunctionTest(this); } + virtual ~ExecFunctionTestShell() CPPUTEST_DESTRUCTOR_OVERRIDE; }; //////////////////// CppUTestFailedException @@ -224,14 +276,14 @@ class IgnoredUtestShell : public UtestShell { public: IgnoredUtestShell(); - virtual ~IgnoredUtestShell(); + virtual ~IgnoredUtestShell() CPPUTEST_DESTRUCTOR_OVERRIDE; explicit IgnoredUtestShell(const char* groupName, const char* testName, - const char* fileName, int lineNumber); - virtual bool willRun() const _override; - virtual void setRunIgnored() _override; + const char* fileName, size_t lineNumber); + virtual bool willRun() const CPPUTEST_OVERRIDE; + virtual void setRunIgnored() CPPUTEST_OVERRIDE; protected: - virtual SimpleString getMacroName() const _override; - virtual void runOneTest(TestPlugin* plugin, TestResult& result) _override; + virtual SimpleString getMacroName() const CPPUTEST_OVERRIDE; + virtual void runOneTest(TestPlugin* plugin, TestResult& result) CPPUTEST_OVERRIDE; private: IgnoredUtestShell(const IgnoredUtestShell&); @@ -241,13 +293,36 @@ class IgnoredUtestShell : public UtestShell }; +//////////////////// UtestShellPointerArray + +class UtestShellPointerArray +{ +public: + UtestShellPointerArray(UtestShell* firstTest); + ~UtestShellPointerArray(); + + void shuffle(size_t seed); + void reverse(); + void relinkTestsInOrder(); + UtestShell* getFirstTest() const; + UtestShell* get(size_t index) const; + +private: + + void swap(size_t index1, size_t index2); + + UtestShell** arrayOfTests_; + size_t count_; +}; + + //////////////////// TestInstaller class TestInstaller { public: explicit TestInstaller(UtestShell& shell, const char* groupName, const char* testName, - const char* fileName, int lineNumber); + const char* fileName, size_t lineNumber); virtual ~TestInstaller(); void unDo(); diff --git a/include/CppUTest/UtestMacros.h b/include/CppUTest/UtestMacros.h old mode 100755 new mode 100644 index d38367d16..743bf069e --- a/include/CppUTest/UtestMacros.h +++ b/include/CppUTest/UtestMacros.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -50,10 +50,10 @@ TEST_GROUP_BASE(testGroup, Utest) #define TEST_SETUP() \ - virtual void setup() + virtual void setup() CPPUTEST_OVERRIDE #define TEST_TEARDOWN() \ - virtual void teardown() + virtual void teardown() CPPUTEST_OVERRIDE #define TEST(testGroup, testName) \ /* External declarations for strict compilers */ \ @@ -62,9 +62,9 @@ \ class TEST_##testGroup##_##testName##_Test : public TEST_GROUP_##CppUTestGroup##testGroup \ { public: TEST_##testGroup##_##testName##_Test () : TEST_GROUP_##CppUTestGroup##testGroup () {} \ - void testBody(); }; \ + void testBody() CPPUTEST_OVERRIDE; }; \ class TEST_##testGroup##_##testName##_TestShell : public UtestShell { \ - virtual Utest* createTest() _override { return new TEST_##testGroup##_##testName##_Test; } \ + virtual Utest* createTest() CPPUTEST_OVERRIDE { return new TEST_##testGroup##_##testName##_Test; } \ } TEST_##testGroup##_##testName##_TestShell_instance; \ static TestInstaller TEST_##testGroup##_##testName##_Installer(TEST_##testGroup##_##testName##_TestShell_instance, #testGroup, #testName, __FILE__,__LINE__); \ void TEST_##testGroup##_##testName##_Test::testBody() @@ -76,9 +76,9 @@ \ class IGNORE##testGroup##_##testName##_Test : public TEST_GROUP_##CppUTestGroup##testGroup \ { public: IGNORE##testGroup##_##testName##_Test () : TEST_GROUP_##CppUTestGroup##testGroup () {} \ - public: void testBody (); }; \ + public: void testBody() CPPUTEST_OVERRIDE; }; \ class IGNORE##testGroup##_##testName##_TestShell : public IgnoredUtestShell { \ - virtual Utest* createTest() _override { return new IGNORE##testGroup##_##testName##_Test; } \ + virtual Utest* createTest() CPPUTEST_OVERRIDE { return new IGNORE##testGroup##_##testName##_Test; } \ } IGNORE##testGroup##_##testName##_TestShell_instance; \ static TestInstaller TEST_##testGroup##testName##_Installer(IGNORE##testGroup##_##testName##_TestShell_instance, #testGroup, #testName, __FILE__,__LINE__); \ void IGNORE##testGroup##_##testName##_Test::testBody () @@ -99,38 +99,38 @@ // Different checking macros #define CHECK(condition)\ - CHECK_TRUE_LOCATION(condition, "CHECK", #condition, NULL, __FILE__, __LINE__) + CHECK_TRUE_LOCATION(condition, "CHECK", #condition, NULLPTR, __FILE__, __LINE__) #define CHECK_TEXT(condition, text) \ - CHECK_TRUE_LOCATION(condition, "CHECK", #condition, text, __FILE__, __LINE__) + CHECK_TRUE_LOCATION((bool)(condition), "CHECK", #condition, text, __FILE__, __LINE__) #define CHECK_TRUE(condition)\ - CHECK_TRUE_LOCATION(condition, "CHECK_TRUE", #condition, NULL, __FILE__, __LINE__) + CHECK_TRUE_LOCATION((bool) (condition), "CHECK_TRUE", #condition, NULLPTR, __FILE__, __LINE__) #define CHECK_TRUE_TEXT(condition, text)\ CHECK_TRUE_LOCATION(condition, "CHECK_TRUE", #condition, text, __FILE__, __LINE__) #define CHECK_FALSE(condition)\ - CHECK_FALSE_LOCATION(condition, "CHECK_FALSE", #condition, NULL, __FILE__, __LINE__) + CHECK_FALSE_LOCATION(condition, "CHECK_FALSE", #condition, NULLPTR, __FILE__, __LINE__) #define CHECK_FALSE_TEXT(condition, text)\ CHECK_FALSE_LOCATION(condition, "CHECK_FALSE", #condition, text, __FILE__, __LINE__) #define CHECK_TRUE_LOCATION(condition, checkString, conditionString, text, file, line)\ - { UtestShell::getCurrent()->assertTrue((condition) != 0, checkString, conditionString, text, file, line); } + do { UtestShell::getCurrent()->assertTrue((condition), checkString, conditionString, text, file, line); } while(0) #define CHECK_FALSE_LOCATION(condition, checkString, conditionString, text, file, line)\ - { UtestShell::getCurrent()->assertTrue((condition) == 0, checkString, conditionString, text, file, line); } + do { UtestShell::getCurrent()->assertTrue(!(condition), checkString, conditionString, text, file, line); } while(0) //This check needs the operator!=(), and a StringFrom(YourType) function #define CHECK_EQUAL(expected, actual)\ - CHECK_EQUAL_LOCATION(expected, actual, NULL, __FILE__, __LINE__) + CHECK_EQUAL_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define CHECK_EQUAL_TEXT(expected, actual, text)\ CHECK_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define CHECK_EQUAL_LOCATION(expected, actual, text, file, line)\ - { if ((expected) != (actual)) { \ + do { if ((expected) != (actual)) { \ if ((actual) != (actual)) \ UtestShell::getCurrent()->print("WARNING:\n\tThe \"Actual Parameter\" parameter is evaluated multiple times resulting in different values.\n\tThus the value in the error message is probably incorrect.", file, line); \ if ((expected) != (expected)) \ @@ -139,92 +139,116 @@ } \ else \ { \ - UtestShell::getCurrent()->assertLongsEqual((long)0, (long)0, NULL, file, line); \ - } } + UtestShell::getCurrent()->assertLongsEqual((long)0, (long)0, NULLPTR, file, line); \ + } } while(0) + +#define CHECK_EQUAL_ZERO(actual) CHECK_EQUAL(0, (actual)) + +#define CHECK_EQUAL_ZERO_TEXT(actual, text) CHECK_EQUAL_TEXT(0, (actual), (text)) + +#define CHECK_COMPARE(first, relop, second)\ + CHECK_COMPARE_TEXT(first, relop, second, NULLPTR) + +#define CHECK_COMPARE_TEXT(first, relop, second, text)\ + CHECK_COMPARE_LOCATION(first, relop, second, text, __FILE__, __LINE__) + +#define CHECK_COMPARE_LOCATION(first, relop, second, text, file, line)\ + do {\ + bool success = (first) relop (second);\ + if (!success) {\ + SimpleString conditionString;\ + conditionString += StringFrom(first); conditionString += " ";\ + conditionString += #relop; conditionString += " ";\ + conditionString += StringFrom(second);\ + UtestShell::getCurrent()->assertCompare(false, "CHECK_COMPARE", conditionString.asCharString(), text, __FILE__, __LINE__);\ + }\ + } while(0) //This check checks for char* string equality using strcmp. //This makes up for the fact that CHECK_EQUAL only compares the pointers to char*'s #define STRCMP_EQUAL(expected, actual)\ - STRCMP_EQUAL_LOCATION(expected, actual, NULL, __FILE__, __LINE__) + STRCMP_EQUAL_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define STRCMP_EQUAL_TEXT(expected, actual, text)\ STRCMP_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_EQUAL_LOCATION(expected, actual, text, file, line)\ - { UtestShell::getCurrent()->assertCstrEqual(expected, actual, text, file, line); } + do { UtestShell::getCurrent()->assertCstrEqual(expected, actual, text, file, line); } while(0) #define STRNCMP_EQUAL(expected, actual, length)\ - STRNCMP_EQUAL_LOCATION(expected, actual, length, NULL, __FILE__, __LINE__) + STRNCMP_EQUAL_LOCATION(expected, actual, length, NULLPTR, __FILE__, __LINE__) #define STRNCMP_EQUAL_TEXT(expected, actual, length, text)\ STRNCMP_EQUAL_LOCATION(expected, actual, length, text, __FILE__, __LINE__) #define STRNCMP_EQUAL_LOCATION(expected, actual, length, text, file, line)\ - { UtestShell::getCurrent()->assertCstrNEqual(expected, actual, length, text, file, line); } + do { UtestShell::getCurrent()->assertCstrNEqual(expected, actual, length, text, file, line); } while(0) #define STRCMP_NOCASE_EQUAL(expected, actual)\ - STRCMP_NOCASE_EQUAL_LOCATION(expected, actual, NULL, __FILE__, __LINE__) + STRCMP_NOCASE_EQUAL_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define STRCMP_NOCASE_EQUAL_TEXT(expected, actual, text)\ STRCMP_NOCASE_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_NOCASE_EQUAL_LOCATION(expected, actual, text, file, line)\ - { UtestShell::getCurrent()->assertCstrNoCaseEqual(expected, actual, text, file, line); } + do { UtestShell::getCurrent()->assertCstrNoCaseEqual(expected, actual, text, file, line); } while(0) #define STRCMP_CONTAINS(expected, actual)\ - STRCMP_CONTAINS_LOCATION(expected, actual, NULL, __FILE__, __LINE__) + STRCMP_CONTAINS_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define STRCMP_CONTAINS_TEXT(expected, actual, text)\ STRCMP_CONTAINS_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_CONTAINS_LOCATION(expected, actual, text, file, line)\ - { UtestShell::getCurrent()->assertCstrContains(expected, actual, text, file, line); } + do { UtestShell::getCurrent()->assertCstrContains(expected, actual, text, file, line); } while(0) #define STRCMP_NOCASE_CONTAINS(expected, actual)\ - STRCMP_NOCASE_CONTAINS_LOCATION(expected, actual, NULL, __FILE__, __LINE__) + STRCMP_NOCASE_CONTAINS_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define STRCMP_NOCASE_CONTAINS_TEXT(expected, actual, text)\ STRCMP_NOCASE_CONTAINS_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_NOCASE_CONTAINS_LOCATION(expected, actual, text, file, line)\ - { UtestShell::getCurrent()->assertCstrNoCaseContains(expected, actual, text, file, line); } + do { UtestShell::getCurrent()->assertCstrNoCaseContains(expected, actual, text, file, line); } while(0) //Check two long integers for equality #define LONGS_EQUAL(expected, actual)\ - LONGS_EQUAL_LOCATION((expected), (actual), NULL, __FILE__, __LINE__) + LONGS_EQUAL_LOCATION((expected), (actual), "LONGS_EQUAL(" #expected ", " #actual ") failed", __FILE__, __LINE__) #define LONGS_EQUAL_TEXT(expected, actual, text)\ LONGS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define UNSIGNED_LONGS_EQUAL(expected, actual)\ - UNSIGNED_LONGS_EQUAL_LOCATION((expected), (actual), NULL, __FILE__, __LINE__) + UNSIGNED_LONGS_EQUAL_LOCATION((expected), (actual), NULLPTR, __FILE__, __LINE__) #define UNSIGNED_LONGS_EQUAL_TEXT(expected, actual, text)\ UNSIGNED_LONGS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define LONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ - { UtestShell::getCurrent()->assertLongsEqual((long)expected, (long)actual, text, file, line); } + do { UtestShell::getCurrent()->assertLongsEqual((long)(expected), (long)(actual), text, file, line); } while(0) #define UNSIGNED_LONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ - { UtestShell::getCurrent()->assertUnsignedLongsEqual((unsigned long)expected, (unsigned long)actual, text, file, line); } + do { UtestShell::getCurrent()->assertUnsignedLongsEqual((unsigned long)(expected), (unsigned long)(actual), text, file, line); } while(0) +#if CPPUTEST_USE_LONG_LONG #define LONGLONGS_EQUAL(expected, actual)\ - LONGLONGS_EQUAL_LOCATION(expected, actual, NULL, __FILE__, __LINE__) + LONGLONGS_EQUAL_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define LONGLONGS_EQUAL_TEXT(expected, actual, text)\ LONGLONGS_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define UNSIGNED_LONGLONGS_EQUAL(expected, actual)\ - UNSIGNED_LONGLONGS_EQUAL_LOCATION(expected, actual, NULL, __FILE__, __LINE__) + UNSIGNED_LONGLONGS_EQUAL_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define UNSIGNED_LONGLONGS_EQUAL_TEXT(expected, actual, text)\ UNSIGNED_LONGLONGS_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define LONGLONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ - { UtestShell::getCurrent()->assertLongLongsEqual(expected, actual, text, file, line); } + do { UtestShell::getCurrent()->assertLongLongsEqual((cpputest_longlong)(expected), (cpputest_longlong)(actual), text, file, line); } while(0) #define UNSIGNED_LONGLONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ - { UtestShell::getCurrent()->assertUnsignedLongLongsEqual(expected, actual, text, file, line); } + do { UtestShell::getCurrent()->assertUnsignedLongLongsEqual((cpputest_ulonglong)(expected), (cpputest_ulonglong)(actual), text, file, line); } while(0) +#endif // CPPUTEST_USE_LONG_LONG #define BYTES_EQUAL(expected, actual)\ LONGS_EQUAL((expected) & 0xff,(actual) & 0xff) @@ -236,59 +260,83 @@ SIGNED_BYTES_EQUAL_LOCATION(expected, actual, __FILE__, __LINE__) #define SIGNED_BYTES_EQUAL_LOCATION(expected, actual, file, line) \ - { UtestShell::getCurrent()->assertSignedBytesEqual(expected, actual, NULL, file, line); } + do { UtestShell::getCurrent()->assertSignedBytesEqual(expected, actual, NULLPTR, file, line); } while(0) #define SIGNED_BYTES_EQUAL_TEXT(expected, actual, text)\ SIGNED_BYTES_EQUAL_TEXT_LOCATION(expected, actual, text, __FILE__, __LINE__) #define SIGNED_BYTES_EQUAL_TEXT_LOCATION(expected, actual, text, file, line) \ - { UtestShell::getCurrent()->assertSignedBytesEqual(expected, actual, text, file, line); } + do { UtestShell::getCurrent()->assertSignedBytesEqual(expected, actual, text, file, line); } while(0) #define POINTERS_EQUAL(expected, actual)\ - POINTERS_EQUAL_LOCATION((expected), (actual), NULL, __FILE__, __LINE__) + POINTERS_EQUAL_LOCATION((expected), (actual), NULLPTR, __FILE__, __LINE__) #define POINTERS_EQUAL_TEXT(expected, actual, text)\ POINTERS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define POINTERS_EQUAL_LOCATION(expected, actual, text, file, line)\ - { UtestShell::getCurrent()->assertPointersEqual((void *)expected, (void *)actual, text, file, line); } + do { UtestShell::getCurrent()->assertPointersEqual((const void *)(expected), (const void *)(actual), text, file, line); } while(0) #define FUNCTIONPOINTERS_EQUAL(expected, actual)\ - FUNCTIONPOINTERS_EQUAL_LOCATION((expected), (actual), NULL, __FILE__, __LINE__) + FUNCTIONPOINTERS_EQUAL_LOCATION((expected), (actual), NULLPTR, __FILE__, __LINE__) #define FUNCTIONPOINTERS_EQUAL_TEXT(expected, actual, text)\ FUNCTIONPOINTERS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define FUNCTIONPOINTERS_EQUAL_LOCATION(expected, actual, text, file, line)\ - { UtestShell::getCurrent()->assertFunctionPointersEqual((void (*)())expected, (void (*)())actual, text, file, line); } + do { UtestShell::getCurrent()->assertFunctionPointersEqual((void (*)())(expected), (void (*)())(actual), text, file, line); } while(0) //Check two doubles for equality within a tolerance threshold #define DOUBLES_EQUAL(expected, actual, threshold)\ - DOUBLES_EQUAL_LOCATION(expected, actual, threshold, NULL, __FILE__, __LINE__) + DOUBLES_EQUAL_LOCATION(expected, actual, threshold, NULLPTR, __FILE__, __LINE__) #define DOUBLES_EQUAL_TEXT(expected, actual, threshold, text)\ DOUBLES_EQUAL_LOCATION(expected, actual, threshold, text, __FILE__, __LINE__) #define DOUBLES_EQUAL_LOCATION(expected, actual, threshold, text, file, line)\ - { UtestShell::getCurrent()->assertDoublesEqual(expected, actual, threshold, text, file, line); } + do { UtestShell::getCurrent()->assertDoublesEqual(expected, actual, threshold, text, file, line); } while(0) #define MEMCMP_EQUAL(expected, actual, size)\ - MEMCMP_EQUAL_LOCATION(expected, actual, size, NULL, __FILE__, __LINE__) + MEMCMP_EQUAL_LOCATION(expected, actual, size, NULLPTR, __FILE__, __LINE__) #define MEMCMP_EQUAL_TEXT(expected, actual, size, text)\ MEMCMP_EQUAL_LOCATION(expected, actual, size, text, __FILE__, __LINE__) #define MEMCMP_EQUAL_LOCATION(expected, actual, size, text, file, line)\ - { UtestShell::getCurrent()->assertBinaryEqual(expected, actual, size, text, file, line); } + do { UtestShell::getCurrent()->assertBinaryEqual(expected, actual, size, text, file, line); } while(0) #define BITS_EQUAL(expected, actual, mask)\ - BITS_LOCATION(expected, actual, mask, NULL, __FILE__, __LINE__) + BITS_LOCATION(expected, actual, mask, NULLPTR, __FILE__, __LINE__) #define BITS_EQUAL_TEXT(expected, actual, mask, text)\ BITS_LOCATION(expected, actual, mask, text, __FILE__, __LINE__) #define BITS_LOCATION(expected, actual, mask, text, file, line)\ - { UtestShell::getCurrent()->assertBitsEqual(expected, actual, mask, sizeof(actual), text, file, line); } + do { UtestShell::getCurrent()->assertBitsEqual(expected, actual, mask, sizeof(actual), text, file, line); } while(0) // NOLINT(bugprone-sizeof-expression) + +#define ENUMS_EQUAL_INT(expected, actual)\ + ENUMS_EQUAL_TYPE(int, expected, actual) + +#define ENUMS_EQUAL_INT_TEXT(expected, actual, text)\ + ENUMS_EQUAL_TYPE_TEXT(int, expected, actual, text) + +#define ENUMS_EQUAL_TYPE(underlying_type, expected, actual)\ + ENUMS_EQUAL_TYPE_LOCATION(underlying_type, expected, actual, NULLPTR, __FILE__, __LINE__) + +#define ENUMS_EQUAL_TYPE_TEXT(underlying_type, expected, actual, text)\ + ENUMS_EQUAL_TYPE_LOCATION(underlying_type, expected, actual, text, __FILE__, __LINE__) + +#define ENUMS_EQUAL_TYPE_LOCATION(underlying_type, expected, actual, text, file, line)\ + do { underlying_type expected_underlying_value = (underlying_type)(expected); \ + underlying_type actual_underlying_value = (underlying_type)(actual); \ + if (expected_underlying_value != actual_underlying_value) { \ + UtestShell::getCurrent()->assertEquals(true, StringFrom(expected_underlying_value).asCharString(), StringFrom(actual_underlying_value).asCharString(), text, file, line); \ + } \ + else \ + { \ + UtestShell::getCurrent()->assertLongsEqual((long)0, long(0), NULLPTR, file, line); \ + } \ + } while(0) //Fail if you get to this macro //The macro FAIL may already be taken, so allow FAIL_TEST too @@ -297,27 +345,27 @@ FAIL_LOCATION(text, __FILE__,__LINE__) #define FAIL_LOCATION(text, file, line)\ - { UtestShell::getCurrent()->fail(text, file, line); } + do { UtestShell::getCurrent()->fail(text, file, line); } while(0) #endif #define FAIL_TEST(text)\ FAIL_TEST_LOCATION(text, __FILE__,__LINE__) #define FAIL_TEST_LOCATION(text, file,line)\ - { UtestShell::getCurrent()->fail(text, file, line); } + do { UtestShell::getCurrent()->fail(text, file, line); } while(0) #define TEST_EXIT\ - { UtestShell::getCurrent()->exitTest(); } + do { UtestShell::getCurrent()->exitTest(); } while(0) #define UT_PRINT_LOCATION(text, file, line) \ - { UtestShell::getCurrent()->print(text, file, line); } + do { UtestShell::getCurrent()->print(text, file, line); } while(0) #define UT_PRINT(text) \ UT_PRINT_LOCATION(text, __FILE__, __LINE__) -#if CPPUTEST_USE_STD_CPP_LIB +#if CPPUTEST_HAVE_EXCEPTIONS #define CHECK_THROWS(expected, expression) \ - { \ + do { \ SimpleString failure_msg("expected to throw "#expected "\nbut threw nothing"); \ bool caught_expected = false; \ try { \ @@ -333,10 +381,10 @@ else { \ UtestShell::getCurrent()->countCheck(); \ } \ - } -#endif /* CPPUTEST_USE_STD_CPP_LIB */ + } while(0) +#endif /* CPPUTEST_HAVE_EXCEPTIONS */ -#define UT_CRASH() { UtestShell::crash(); } +#define UT_CRASH() do { UtestShell::crash(); } while(0) #define RUN_ALL_TESTS(ac, av) CommandLineTestRunner::RunAllTests(ac, av) #endif /*D_UTestMacros_h*/ diff --git a/include/CppUTestExt/CodeMemoryReportFormatter.h b/include/CppUTestExt/CodeMemoryReportFormatter.h index f73c2ac12..6e87fe302 100644 --- a/include/CppUTestExt/CodeMemoryReportFormatter.h +++ b/include/CppUTestExt/CodeMemoryReportFormatter.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -39,16 +39,16 @@ class CodeMemoryReportFormatter : public MemoryReportFormatter public: CodeMemoryReportFormatter(TestMemoryAllocator* internalAllocator); - virtual ~CodeMemoryReportFormatter(); + virtual ~CodeMemoryReportFormatter() CPPUTEST_DESTRUCTOR_OVERRIDE; - virtual void report_testgroup_start(TestResult* result, UtestShell& test) _override; - virtual void report_testgroup_end(TestResult* /*result*/, UtestShell& /*test*/) _override {} // LCOV_EXCL_LINE + virtual void report_testgroup_start(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE; + virtual void report_testgroup_end(TestResult* /*result*/, UtestShell& /*test*/) CPPUTEST_OVERRIDE {} // LCOV_EXCL_LINE - virtual void report_test_start(TestResult* result, UtestShell& test) _override; - virtual void report_test_end(TestResult* result, UtestShell& test) _override; + virtual void report_test_start(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE; + virtual void report_test_end(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE; - virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, int line) _override; - virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, int line) _override; + virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, size_t line) CPPUTEST_OVERRIDE; + virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, size_t line) CPPUTEST_OVERRIDE; private: @@ -58,10 +58,10 @@ class CodeMemoryReportFormatter : public MemoryReportFormatter void clearReporting(); bool isNewAllocator(TestMemoryAllocator* allocator); - SimpleString createVariableNameFromFileLineInfo(const char *file, int line); + SimpleString createVariableNameFromFileLineInfo(const char *file, size_t line); SimpleString getAllocationString(TestMemoryAllocator* allocator, const SimpleString& variableName, size_t size); - SimpleString getDeallocationString(TestMemoryAllocator* allocator, const SimpleString& variableName, const char* file, int line); + SimpleString getDeallocationString(TestMemoryAllocator* allocator, const SimpleString& variableName, const char* file, size_t line); }; #endif diff --git a/include/CppUTestExt/GMock.h b/include/CppUTestExt/GMock.h index 61b59afd6..131597371 100644 --- a/include/CppUTestExt/GMock.h +++ b/include/CppUTestExt/GMock.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -29,6 +29,8 @@ #define GMOCK_H_ #undef new +#undef strdup +#undef strndup #undef RUN_ALL_TESTS @@ -45,4 +47,8 @@ using testing::NiceMock; #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif +#ifdef CPPUTEST_USE_MALLOC_MACROS +#include "CppUTest/MemoryLeakDetectorMallocMacros.h" +#endif + #endif diff --git a/include/CppUTestExt/GTest.h b/include/CppUTestExt/GTest.h index 73da89d08..a2472d3c7 100644 --- a/include/CppUTestExt/GTest.h +++ b/include/CppUTestExt/GTest.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -25,10 +25,12 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef GTEST__H_ -#define GTEST__H_ +#ifndef GTEST_H_ +#define GTEST_H_ #undef new +#undef strdup +#undef strndup #undef RUN_ALL_TESTS @@ -38,6 +40,12 @@ #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif +#ifdef CPPUTEST_USE_MALLOC_MACROS +#include "CppUTest/MemoryLeakDetectorMallocMacros.h" +#endif + +#include "CppUTestExt/GTestSupport.h" + #ifndef RUN_ALL_TESTS #define GTEST_VERSION_GTEST_1_7 #else diff --git a/include/CppUTestExt/GTestConvertor.h b/include/CppUTestExt/GTestConvertor.h index d7853ff1a..c606d6c18 100644 --- a/include/CppUTestExt/GTestConvertor.h +++ b/include/CppUTestExt/GTestConvertor.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,8 +30,8 @@ #include "CppUTest/Utest.h" -#ifdef GTEST__H_ -#error "Please include this file before you include any other GTest files" +#ifdef GTEST_H_ + #error "Please include this file before you include any other GTest files" #endif /* @@ -63,10 +63,11 @@ class GTestShell : public UtestShell ::testing::TestInfo* testinfo_; GTestShell* next_; GTestFlagsThatAllocateMemory* flags_; + public: GTestShell(::testing::TestInfo* testinfo, GTestShell* next, GTestFlagsThatAllocateMemory* flags); - virtual Utest* createTest() _override; + virtual Utest* createTest() CPPUTEST_OVERRIDE; GTestShell* nextGTest() { @@ -101,7 +102,7 @@ class GTestShell : public UtestShell * */ #define GTEST_IMPLEMENTATION_ 1 -#include "src/gtest-internal-inl.h" +#include "../src/gtest-internal-inl.h" #include "CppUTest/TestRegistry.h" #include "CppUTest/TestFailure.h" @@ -121,7 +122,7 @@ class GTestShell : public UtestShell class GTestFlagsThatAllocateMemory { public: - void storeValuesOfGTestFLags() + void storeValuesOfGTestFlags() { GTestFlagcolor = ::testing::GTEST_FLAG(color); GTestFlagfilter = ::testing::GTEST_FLAG(filter); @@ -145,7 +146,7 @@ class GTestFlagsThatAllocateMemory #endif } - void setGTestFLagValuesToNULLToAvoidMemoryLeaks() + void setGTestFlagValuesToNULLToAvoidMemoryLeaks() { #ifndef GTEST_VERSION_GTEST_1_7 ::testing::GTEST_FLAG(color) = GTEST_NO_STRING_VALUE; @@ -207,7 +208,7 @@ class GMockTestTerminator : public TestTerminator virtual void exitCurrentTest() const { /* - * When using GMock, it throws an exception fromt he destructor leaving + * When using GMock, it throws an exception from the destructor leaving * the system in an unstable state. * Therefore, when the test fails because of failed gmock expectation * then don't throw the exception, but let it return. Usually this should @@ -300,7 +301,7 @@ class GTestUTest: public Utest { ::testing::UnitTest::GetInstance()->impl()->set_current_test_info(NULL); delete test_; - flags_->setGTestFLagValuesToNULLToAvoidMemoryLeaks(); + flags_->setGTestFlagValuesToNULLToAvoidMemoryLeaks(); ::testing::internal::DeathTest::set_last_death_test_message(GTEST_NO_STRING_VALUE); } @@ -366,7 +367,7 @@ inline void GTestConvertor::createDummyInSequenceToAndFailureReporterAvoidMemory inline void GTestConvertor::addAllGTestToTestRegistry() { createDummyInSequenceToAndFailureReporterAvoidMemoryLeakInGMock(); - flags_.storeValuesOfGTestFLags(); + flags_.storeValuesOfGTestFlags(); int argc = 2; const char * argv[] = {"NameOfTheProgram", "--gmock_catch_leaked_mocks=0"}; diff --git a/platforms/iar/tests/AllTests.cpp b/include/CppUTestExt/GTestSupport.h similarity index 70% rename from platforms/iar/tests/AllTests.cpp rename to include/CppUTestExt/GTestSupport.h index 5b9de6830..80892a0fa 100644 --- a/platforms/iar/tests/AllTests.cpp +++ b/include/CppUTestExt/GTestSupport.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde + * Copyright (c) 2011, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -25,21 +25,9 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "CppUTest/CommandLineTestRunner.h" +#ifndef GTESTSUPPORT_H_ +#define GTESTSUPPORT_H_ +extern void CppuTestGTestIgnoreLeaksInTest(); -int main(int ac, const char** av) -{ - /* These checks are here to make sure assertions outside test runs don't crash */ - CHECK(true); - LONGS_EQUAL(1, 1); - const char * av_override[] = {"exe", "-v"}; - - int rv = CommandLineTestRunner::RunAllTests(2, av_override); - - //Exiting from main causes IAR simulator to issue out-of-bounds memory access warnings. - volatile int wait = 1; - while (wait){} - return rv; -} - +#endif diff --git a/include/CppUTestExt/IEEE754ExceptionsPlugin.h b/include/CppUTestExt/IEEE754ExceptionsPlugin.h index 9d3f0cdc1..35a18181f 100644 --- a/include/CppUTestExt/IEEE754ExceptionsPlugin.h +++ b/include/CppUTestExt/IEEE754ExceptionsPlugin.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -35,8 +35,8 @@ class IEEE754ExceptionsPlugin: public TestPlugin public: IEEE754ExceptionsPlugin(const SimpleString& name = "IEEE754ExceptionsPlugin"); - virtual void preTestAction(UtestShell& test, TestResult& result) _override; - virtual void postTestAction(UtestShell& test, TestResult& result) _override; + virtual void preTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; + virtual void postTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; static void disableInexact(void); static void enableInexact(void); diff --git a/include/CppUTestExt/MemoryReportAllocator.h b/include/CppUTestExt/MemoryReportAllocator.h index 064c83514..2cca67e25 100644 --- a/include/CppUTestExt/MemoryReportAllocator.h +++ b/include/CppUTestExt/MemoryReportAllocator.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -40,7 +40,7 @@ class MemoryReportAllocator : public TestMemoryAllocator MemoryReportFormatter* formatter_; public: MemoryReportAllocator(); - virtual ~MemoryReportAllocator(); + virtual ~MemoryReportAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void setFormatter(MemoryReportFormatter* formatter); virtual void setTestResult(TestResult* result); @@ -48,12 +48,14 @@ class MemoryReportAllocator : public TestMemoryAllocator virtual TestMemoryAllocator* getRealAllocator(); - virtual char* alloc_memory(size_t size, const char* file, int line) _override; - virtual void free_memory(char* memory, const char* file, int line) _override; + virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; + virtual void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; - virtual const char* name() _override; - virtual const char* alloc_name() _override; - virtual const char* free_name() _override; + virtual const char* name() const CPPUTEST_OVERRIDE; + virtual const char* alloc_name() const CPPUTEST_OVERRIDE; + virtual const char* free_name() const CPPUTEST_OVERRIDE; + + virtual TestMemoryAllocator* actualAllocator() CPPUTEST_OVERRIDE; }; #endif diff --git a/include/CppUTestExt/MemoryReportFormatter.h b/include/CppUTestExt/MemoryReportFormatter.h index 750265b02..2c7af57aa 100644 --- a/include/CppUTestExt/MemoryReportFormatter.h +++ b/include/CppUTestExt/MemoryReportFormatter.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -42,24 +42,24 @@ class MemoryReportFormatter virtual void report_test_start(TestResult* result, UtestShell& test)=0; virtual void report_test_end(TestResult* result, UtestShell& test)=0; - virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, int line)=0; - virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, int line)=0; + virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, size_t line)=0; + virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, size_t line)=0; }; class NormalMemoryReportFormatter : public MemoryReportFormatter { public: NormalMemoryReportFormatter(); - virtual ~NormalMemoryReportFormatter(); + virtual ~NormalMemoryReportFormatter() CPPUTEST_DESTRUCTOR_OVERRIDE; - virtual void report_testgroup_start(TestResult* /*result*/, UtestShell& /*test*/) _override; - virtual void report_testgroup_end(TestResult* /*result*/, UtestShell& /*test*/) _override {} // LCOV_EXCL_LINE + virtual void report_testgroup_start(TestResult* /*result*/, UtestShell& /*test*/) CPPUTEST_OVERRIDE; + virtual void report_testgroup_end(TestResult* /*result*/, UtestShell& /*test*/) CPPUTEST_OVERRIDE {} // LCOV_EXCL_LINE - virtual void report_test_start(TestResult* result, UtestShell& test) _override; - virtual void report_test_end(TestResult* result, UtestShell& test) _override; + virtual void report_test_start(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE; + virtual void report_test_end(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE; - virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, int line) _override; - virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, int line) _override; + virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, size_t line) CPPUTEST_OVERRIDE; + virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, size_t line) CPPUTEST_OVERRIDE; }; #endif diff --git a/include/CppUTestExt/MemoryReporterPlugin.h b/include/CppUTestExt/MemoryReporterPlugin.h index 57733558c..5b1816f9b 100644 --- a/include/CppUTestExt/MemoryReporterPlugin.h +++ b/include/CppUTestExt/MemoryReporterPlugin.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -44,12 +44,15 @@ class MemoryReporterPlugin : public TestPlugin SimpleString currentTestGroup_; public: MemoryReporterPlugin(); - virtual ~MemoryReporterPlugin(); + virtual ~MemoryReporterPlugin() CPPUTEST_DESTRUCTOR_OVERRIDE; - virtual void preTestAction(UtestShell & test, TestResult & result) _override; - virtual void postTestAction(UtestShell & test, TestResult & result) _override; - virtual bool parseArguments(int, const char**, int) _override; + virtual void preTestAction(UtestShell & test, TestResult & result) CPPUTEST_OVERRIDE; + virtual void postTestAction(UtestShell & test, TestResult & result) CPPUTEST_OVERRIDE; + virtual bool parseArguments(int, const char *const *, int) CPPUTEST_OVERRIDE; + MemoryReportAllocator* getMallocAllocator(); + MemoryReportAllocator* getNewAllocator(); + MemoryReportAllocator* getNewArrayAllocator(); protected: virtual MemoryReportFormatter* createMemoryFormatter(const SimpleString& type); diff --git a/include/CppUTestExt/MockActualCall.h b/include/CppUTestExt/MockActualCall.h index 496a499a0..51f2fa7e5 100644 --- a/include/CppUTestExt/MockActualCall.h +++ b/include/CppUTestExt/MockActualCall.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -28,6 +28,7 @@ #ifndef D_MockActualCall_h #define D_MockActualCall_h +#include "CppUTest/CppUTestConfig.h" #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockNamedValue.h" #include "CppUTestExt/MockExpectedCallsList.h" @@ -42,12 +43,14 @@ class MockActualCall virtual ~MockActualCall(); virtual MockActualCall& withName(const SimpleString& name)=0; - virtual MockActualCall& withCallOrder(int callOrder)=0; + virtual MockActualCall& withCallOrder(unsigned int callOrder)=0; MockActualCall& withParameter(const SimpleString& name, bool value) { return withBoolParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, int value) { return withIntParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, unsigned int value) { return withUnsignedIntParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, long int value) { return withLongIntParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, unsigned long int value) { return withUnsignedLongIntParameter(name, value); } + MockActualCall& withParameter(const SimpleString& name, cpputest_longlong value) { return withLongLongIntParameter(name, value); } + MockActualCall& withParameter(const SimpleString& name, cpputest_ulonglong value) { return withUnsignedLongLongIntParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, double value) { return withDoubleParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, const char* value) { return withStringParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, void* value) { return withPointerParameter(name, value); } @@ -63,6 +66,8 @@ class MockActualCall virtual MockActualCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value)=0; virtual MockActualCall& withLongIntParameter(const SimpleString& name, long int value)=0; virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value)=0; + virtual MockActualCall& withLongLongIntParameter(const SimpleString& name, cpputest_longlong value)=0; + virtual MockActualCall& withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value)=0; virtual MockActualCall& withDoubleParameter(const SimpleString& name, double value)=0; virtual MockActualCall& withStringParameter(const SimpleString& name, const char* value)=0; virtual MockActualCall& withPointerParameter(const SimpleString& name, void* value)=0; @@ -85,6 +90,12 @@ class MockActualCall virtual long int returnLongIntValue()=0; virtual long int returnLongIntValueOrDefault(long int default_value)=0; + virtual cpputest_ulonglong returnUnsignedLongLongIntValue()=0; + virtual cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong default_value)=0; + + virtual cpputest_longlong returnLongLongIntValue()=0; + virtual cpputest_longlong returnLongLongIntValueOrDefault(cpputest_longlong default_value)=0; + virtual unsigned int returnUnsignedIntValue()=0; virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int default_value)=0; diff --git a/include/CppUTestExt/MockCheckedActualCall.h b/include/CppUTestExt/MockCheckedActualCall.h index f4606cf17..51b12e405 100644 --- a/include/CppUTestExt/MockCheckedActualCall.h +++ b/include/CppUTestExt/MockCheckedActualCall.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,60 +34,69 @@ class MockCheckedActualCall : public MockActualCall { public: - MockCheckedActualCall(int callOrder, MockFailureReporter* reporter, const MockExpectedCallsList& expectations); - virtual ~MockCheckedActualCall(); + MockCheckedActualCall(unsigned int callOrder, MockFailureReporter* reporter, const MockExpectedCallsList& expectations); + virtual ~MockCheckedActualCall() CPPUTEST_DESTRUCTOR_OVERRIDE; - virtual MockActualCall& withName(const SimpleString& name) _override; - virtual MockActualCall& withCallOrder(int) _override; - virtual MockActualCall& withBoolParameter(const SimpleString& name, bool value) _override; - virtual MockActualCall& withIntParameter(const SimpleString& name, int value) _override; - virtual MockActualCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) _override; - virtual MockActualCall& withLongIntParameter(const SimpleString& name, long int value) _override; - virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) _override; - virtual MockActualCall& withDoubleParameter(const SimpleString& name, double value) _override; - virtual MockActualCall& withStringParameter(const SimpleString& name, const char* value) _override; - virtual MockActualCall& withPointerParameter(const SimpleString& name, void* value) _override; - virtual MockActualCall& withConstPointerParameter(const SimpleString& name, const void* value) _override; - virtual MockActualCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) _override; - virtual MockActualCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) _override; - virtual MockActualCall& withParameterOfType(const SimpleString& type, const SimpleString& name, const void* value) _override; - virtual MockActualCall& withOutputParameter(const SimpleString& name, void* output) _override; - virtual MockActualCall& withOutputParameterOfType(const SimpleString& type, const SimpleString& name, void* output) _override; + virtual MockActualCall& withName(const SimpleString& name) CPPUTEST_OVERRIDE; + virtual MockActualCall& withCallOrder(unsigned int) CPPUTEST_OVERRIDE; + virtual MockActualCall& withBoolParameter(const SimpleString& name, bool value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withIntParameter(const SimpleString& name, int value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withLongIntParameter(const SimpleString& name, long int value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withLongLongIntParameter(const SimpleString& name, cpputest_longlong value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withDoubleParameter(const SimpleString& name, double value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withStringParameter(const SimpleString& name, const char* value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withPointerParameter(const SimpleString& name, void* value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withConstPointerParameter(const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) CPPUTEST_OVERRIDE; + virtual MockActualCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) CPPUTEST_OVERRIDE; + virtual MockActualCall& withParameterOfType(const SimpleString& type, const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withOutputParameter(const SimpleString& name, void* output) CPPUTEST_OVERRIDE; + virtual MockActualCall& withOutputParameterOfType(const SimpleString& type, const SimpleString& name, void* output) CPPUTEST_OVERRIDE; - virtual bool hasReturnValue() _override; - virtual MockNamedValue returnValue() _override; + virtual bool hasReturnValue() CPPUTEST_OVERRIDE; + virtual MockNamedValue returnValue() CPPUTEST_OVERRIDE; - virtual bool returnBoolValueOrDefault(bool default_value) _override; - virtual bool returnBoolValue() _override; + virtual bool returnBoolValueOrDefault(bool default_value) CPPUTEST_OVERRIDE; + virtual bool returnBoolValue() CPPUTEST_OVERRIDE; - virtual int returnIntValueOrDefault(int default_value) _override; - virtual int returnIntValue() _override; + virtual int returnIntValueOrDefault(int default_value) CPPUTEST_OVERRIDE; + virtual int returnIntValue() CPPUTEST_OVERRIDE; - virtual unsigned long int returnUnsignedLongIntValue() _override; - virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int) _override; + virtual unsigned long int returnUnsignedLongIntValue() CPPUTEST_OVERRIDE; + virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int) CPPUTEST_OVERRIDE; - virtual long int returnLongIntValue() _override; - virtual long int returnLongIntValueOrDefault(long int default_value) _override; + virtual long int returnLongIntValue() CPPUTEST_OVERRIDE; + virtual long int returnLongIntValueOrDefault(long int default_value) CPPUTEST_OVERRIDE; - virtual unsigned int returnUnsignedIntValue() _override; - virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int default_value) _override; + virtual cpputest_ulonglong returnUnsignedLongLongIntValue() CPPUTEST_OVERRIDE; + virtual cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong default_value) CPPUTEST_OVERRIDE; - virtual const char * returnStringValueOrDefault(const char * default_value) _override; - virtual const char * returnStringValue() _override; + virtual cpputest_longlong returnLongLongIntValue() CPPUTEST_OVERRIDE; + virtual cpputest_longlong returnLongLongIntValueOrDefault(cpputest_longlong default_value) CPPUTEST_OVERRIDE; - virtual double returnDoubleValue() _override; - virtual double returnDoubleValueOrDefault(double default_value) _override; + virtual unsigned int returnUnsignedIntValue() CPPUTEST_OVERRIDE; + virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int default_value) CPPUTEST_OVERRIDE; - virtual const void * returnConstPointerValue() _override; - virtual const void * returnConstPointerValueOrDefault(const void * default_value) _override; + virtual const char * returnStringValueOrDefault(const char * default_value) CPPUTEST_OVERRIDE; + virtual const char * returnStringValue() CPPUTEST_OVERRIDE; - virtual void * returnPointerValue() _override; - virtual void * returnPointerValueOrDefault(void *) _override; + virtual double returnDoubleValue() CPPUTEST_OVERRIDE; + virtual double returnDoubleValueOrDefault(double default_value) CPPUTEST_OVERRIDE; - virtual void (*returnFunctionPointerValue())() _override; - virtual void (*returnFunctionPointerValueOrDefault(void (*)()))() _override; + virtual const void * returnConstPointerValue() CPPUTEST_OVERRIDE; + virtual const void * returnConstPointerValueOrDefault(const void * default_value) CPPUTEST_OVERRIDE; - virtual MockActualCall& onObject(const void* objectPtr) _override; + virtual void * returnPointerValue() CPPUTEST_OVERRIDE; + virtual void * returnPointerValueOrDefault(void *) CPPUTEST_OVERRIDE; + + typedef void (*FunctionPointerReturnValue)(); + virtual FunctionPointerReturnValue returnFunctionPointerValue() CPPUTEST_OVERRIDE; + virtual FunctionPointerReturnValue returnFunctionPointerValueOrDefault(void (*)()) CPPUTEST_OVERRIDE; + + virtual MockActualCall& onObject(const void* objectPtr) CPPUTEST_OVERRIDE; virtual bool isFulfilled() const; virtual bool hasFailed() const; @@ -100,12 +109,12 @@ class MockCheckedActualCall : public MockActualCall SimpleString getName() const; virtual UtestShell* getTest() const; virtual void callHasSucceeded(); - virtual void finalizeOutputParameters(MockCheckedExpectedCall* call); - virtual void finalizeCallWhenFulfilled(); + virtual void copyOutputParameters(MockCheckedExpectedCall* call); + virtual void completeCallWhenMatchIsFound(); virtual void failTest(const MockFailure& failure); virtual void checkInputParameter(const MockNamedValue& actualParameter); virtual void checkOutputParameter(const MockNamedValue& outputParameter); - virtual void callIsInProgress(); + virtual void discardCurrentlyMatchingExpectations(); enum ActualCallState { CALL_IN_PROGRESS, @@ -116,13 +125,14 @@ class MockCheckedActualCall : public MockActualCall private: SimpleString functionName_; - int callOrder_; + unsigned int callOrder_; MockFailureReporter* reporter_; ActualCallState state_; - MockCheckedExpectedCall* fulfilledExpectation_; + bool expectationsChecked_; + MockCheckedExpectedCall* matchingExpectation_; - MockExpectedCallsList unfulfilledExpectations_; + MockExpectedCallsList potentiallyMatchingExpectations_; const MockExpectedCallsList& allExpectations_; class MockOutputParametersListNode @@ -134,137 +144,174 @@ class MockCheckedActualCall : public MockActualCall MockOutputParametersListNode* next_; MockOutputParametersListNode(const SimpleString& name, const SimpleString& type, void* ptr) - : name_(name), type_(type), ptr_(ptr), next_(NULL) {} + : name_(name), type_(type), ptr_(ptr), next_(NULLPTR) {} }; MockOutputParametersListNode* outputParameterExpectations_; virtual void addOutputParameter(const SimpleString& name, const SimpleString& type, void* ptr); - virtual void cleanUpOutputParameterList(); + void cleanUpOutputParameterList(); }; class MockActualCallTrace : public MockActualCall { public: MockActualCallTrace(); - virtual ~MockActualCallTrace(); + virtual ~MockActualCallTrace() CPPUTEST_DESTRUCTOR_OVERRIDE; + + virtual MockActualCall& withName(const SimpleString& name) CPPUTEST_OVERRIDE; + virtual MockActualCall& withCallOrder(unsigned int) CPPUTEST_OVERRIDE; + virtual MockActualCall& withBoolParameter(const SimpleString& name, bool value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withIntParameter(const SimpleString& name, int value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withLongIntParameter(const SimpleString& name, long int value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withLongLongIntParameter(const SimpleString& name, cpputest_longlong value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withDoubleParameter(const SimpleString& name, double value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withStringParameter(const SimpleString& name, const char* value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withPointerParameter(const SimpleString& name, void* value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withConstPointerParameter(const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) CPPUTEST_OVERRIDE; + virtual MockActualCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) CPPUTEST_OVERRIDE; + virtual MockActualCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; + virtual MockActualCall& withOutputParameter(const SimpleString& name, void* output) CPPUTEST_OVERRIDE; + virtual MockActualCall& withOutputParameterOfType(const SimpleString& typeName, const SimpleString& name, void* output) CPPUTEST_OVERRIDE; - virtual MockActualCall& withName(const SimpleString& name) _override; - virtual MockActualCall& withCallOrder(int) _override; - virtual MockActualCall& withBoolParameter(const SimpleString& name, bool value) _override; - virtual MockActualCall& withIntParameter(const SimpleString& name, int value) _override; - virtual MockActualCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) _override; - virtual MockActualCall& withLongIntParameter(const SimpleString& name, long int value) _override; - virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) _override; - virtual MockActualCall& withDoubleParameter(const SimpleString& name, double value) _override; - virtual MockActualCall& withStringParameter(const SimpleString& name, const char* value) _override; - virtual MockActualCall& withPointerParameter(const SimpleString& name, void* value) _override; - virtual MockActualCall& withConstPointerParameter(const SimpleString& name, const void* value) _override; - virtual MockActualCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) _override; - virtual MockActualCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) _override; - virtual MockActualCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value) _override; - virtual MockActualCall& withOutputParameter(const SimpleString& name, void* output) _override; - virtual MockActualCall& withOutputParameterOfType(const SimpleString& typeName, const SimpleString& name, void* output) _override; + virtual bool hasReturnValue() CPPUTEST_OVERRIDE; + virtual MockNamedValue returnValue() CPPUTEST_OVERRIDE; - virtual bool hasReturnValue() _override; - virtual MockNamedValue returnValue() _override; + virtual bool returnBoolValueOrDefault(bool default_value) CPPUTEST_OVERRIDE; + virtual bool returnBoolValue() CPPUTEST_OVERRIDE; - virtual bool returnBoolValueOrDefault(bool default_value) _override; - virtual bool returnBoolValue() _override; + virtual int returnIntValueOrDefault(int default_value) CPPUTEST_OVERRIDE; + virtual int returnIntValue() CPPUTEST_OVERRIDE; - virtual int returnIntValueOrDefault(int default_value) _override; - virtual int returnIntValue() _override; + virtual unsigned long int returnUnsignedLongIntValue() CPPUTEST_OVERRIDE; + virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int) CPPUTEST_OVERRIDE; - virtual unsigned long int returnUnsignedLongIntValue() _override; - virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int) _override; + virtual long int returnLongIntValue() CPPUTEST_OVERRIDE; + virtual long int returnLongIntValueOrDefault(long int default_value) CPPUTEST_OVERRIDE; - virtual long int returnLongIntValue() _override; - virtual long int returnLongIntValueOrDefault(long int default_value) _override; + virtual cpputest_ulonglong returnUnsignedLongLongIntValue() CPPUTEST_OVERRIDE; + virtual cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong default_value) CPPUTEST_OVERRIDE; - virtual unsigned int returnUnsignedIntValue() _override; - virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int default_value) _override; + virtual cpputest_longlong returnLongLongIntValue() CPPUTEST_OVERRIDE; + virtual cpputest_longlong returnLongLongIntValueOrDefault(cpputest_longlong default_value) CPPUTEST_OVERRIDE; - virtual const char * returnStringValueOrDefault(const char * default_value) _override; - virtual const char * returnStringValue() _override; + virtual unsigned int returnUnsignedIntValue() CPPUTEST_OVERRIDE; + virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int default_value) CPPUTEST_OVERRIDE; - virtual double returnDoubleValue() _override; - virtual double returnDoubleValueOrDefault(double default_value) _override; + virtual const char * returnStringValueOrDefault(const char * default_value) CPPUTEST_OVERRIDE; + virtual const char * returnStringValue() CPPUTEST_OVERRIDE; - virtual void * returnPointerValue() _override; - virtual void * returnPointerValueOrDefault(void *) _override; + virtual double returnDoubleValue() CPPUTEST_OVERRIDE; + virtual double returnDoubleValueOrDefault(double default_value) CPPUTEST_OVERRIDE; - virtual const void * returnConstPointerValue() _override; - virtual const void * returnConstPointerValueOrDefault(const void * default_value) _override; + virtual void * returnPointerValue() CPPUTEST_OVERRIDE; + virtual void * returnPointerValueOrDefault(void *) CPPUTEST_OVERRIDE; - virtual void (*returnFunctionPointerValue())() _override; - virtual void (*returnFunctionPointerValueOrDefault(void (*)()))() _override; + virtual const void * returnConstPointerValue() CPPUTEST_OVERRIDE; + virtual const void * returnConstPointerValueOrDefault(const void * default_value) CPPUTEST_OVERRIDE; - virtual MockActualCall& onObject(const void* objectPtr) _override; + virtual MockCheckedActualCall::FunctionPointerReturnValue returnFunctionPointerValue() CPPUTEST_OVERRIDE; + virtual MockCheckedActualCall::FunctionPointerReturnValue returnFunctionPointerValueOrDefault(void (*)()) CPPUTEST_OVERRIDE; + + virtual MockActualCall& onObject(const void* objectPtr) CPPUTEST_OVERRIDE; const char* getTraceOutput(); void clear(); static MockActualCallTrace& instance(); + static void clearInstance(); private: SimpleString traceBuffer_; + static MockActualCallTrace* instance_; + void addParameterName(const SimpleString& name); }; class MockIgnoredActualCall: public MockActualCall { public: - virtual MockActualCall& withName(const SimpleString&) _override { return *this;} - virtual MockActualCall& withCallOrder(int) _override { return *this; } - virtual MockActualCall& withBoolParameter(const SimpleString&, bool) _override { return *this; } - virtual MockActualCall& withIntParameter(const SimpleString&, int) _override { return *this; } - virtual MockActualCall& withUnsignedIntParameter(const SimpleString&, unsigned int) _override { return *this; } - virtual MockActualCall& withLongIntParameter(const SimpleString&, long int) _override { return *this; } - virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString&, unsigned long int) _override { return *this; } - virtual MockActualCall& withDoubleParameter(const SimpleString&, double) _override { return *this; } - virtual MockActualCall& withStringParameter(const SimpleString&, const char*) _override { return *this; } - virtual MockActualCall& withPointerParameter(const SimpleString& , void*) _override { return *this; } - virtual MockActualCall& withConstPointerParameter(const SimpleString& , const void*) _override { return *this; } - virtual MockActualCall& withFunctionPointerParameter(const SimpleString& , void (*)()) _override { return *this; } - virtual MockActualCall& withMemoryBufferParameter(const SimpleString&, const unsigned char*, size_t) _override { return *this; } - virtual MockActualCall& withParameterOfType(const SimpleString&, const SimpleString&, const void*) _override { return *this; } - virtual MockActualCall& withOutputParameter(const SimpleString&, void*) _override { return *this; } - virtual MockActualCall& withOutputParameterOfType(const SimpleString&, const SimpleString&, void*) _override { return *this; } - - virtual bool hasReturnValue() _override { return false; } - virtual MockNamedValue returnValue() _override { return MockNamedValue(""); } - - virtual bool returnBoolValueOrDefault(bool) _override { return false; } - virtual bool returnBoolValue() _override { return false; } + virtual MockActualCall& withName(const SimpleString&) CPPUTEST_OVERRIDE { return *this;} + virtual MockActualCall& withCallOrder(unsigned int) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withBoolParameter(const SimpleString&, bool) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withIntParameter(const SimpleString&, int) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withUnsignedIntParameter(const SimpleString&, unsigned int) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withLongIntParameter(const SimpleString&, long int) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString&, unsigned long int) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withLongLongIntParameter(const SimpleString&, cpputest_longlong) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withUnsignedLongLongIntParameter(const SimpleString&, cpputest_ulonglong) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withDoubleParameter(const SimpleString&, double) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withStringParameter(const SimpleString&, const char*) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withPointerParameter(const SimpleString& , void*) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withConstPointerParameter(const SimpleString& , const void*) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withFunctionPointerParameter(const SimpleString& , void (*)()) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withMemoryBufferParameter(const SimpleString&, const unsigned char*, size_t) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withParameterOfType(const SimpleString&, const SimpleString&, const void*) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withOutputParameter(const SimpleString&, void*) CPPUTEST_OVERRIDE { return *this; } + virtual MockActualCall& withOutputParameterOfType(const SimpleString&, const SimpleString&, void*) CPPUTEST_OVERRIDE { return *this; } + + virtual bool hasReturnValue() CPPUTEST_OVERRIDE { return false; } + virtual MockNamedValue returnValue() CPPUTEST_OVERRIDE { return MockNamedValue(""); } + + virtual bool returnBoolValueOrDefault(bool value) CPPUTEST_OVERRIDE { return value; } + virtual bool returnBoolValue() CPPUTEST_OVERRIDE { return false; } + + virtual int returnIntValue() CPPUTEST_OVERRIDE { return 0; } + virtual int returnIntValueOrDefault(int value) CPPUTEST_OVERRIDE { return value; } + + virtual unsigned long int returnUnsignedLongIntValue() CPPUTEST_OVERRIDE { return 0; } + virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int value) CPPUTEST_OVERRIDE { return value; } + + virtual long int returnLongIntValue() CPPUTEST_OVERRIDE { return 0; } + virtual long int returnLongIntValueOrDefault(long int value) CPPUTEST_OVERRIDE { return value; } + + virtual cpputest_ulonglong returnUnsignedLongLongIntValue() CPPUTEST_OVERRIDE + { +#if CPPUTEST_USE_LONG_LONG + return 0; +#else + cpputest_ulonglong ret = {}; + return ret; +#endif + } - virtual int returnIntValue() _override { return 0; } - virtual int returnIntValueOrDefault(int value) _override { return value; } + virtual cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong value) CPPUTEST_OVERRIDE { return value; } - virtual unsigned long int returnUnsignedLongIntValue() _override { return 0; } - virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int value) _override { return value; } + virtual cpputest_longlong returnLongLongIntValue() CPPUTEST_OVERRIDE + { +#if CPPUTEST_USE_LONG_LONG + return 0; +#else + cpputest_longlong ret = {}; + return ret; +#endif + } - virtual long int returnLongIntValue() _override { return 0; } - virtual long int returnLongIntValueOrDefault(long int value) _override { return value; } + virtual cpputest_longlong returnLongLongIntValueOrDefault(cpputest_longlong value) CPPUTEST_OVERRIDE { return value; } - virtual unsigned int returnUnsignedIntValue() _override { return 0; } - virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int value) _override { return value; } + virtual unsigned int returnUnsignedIntValue() CPPUTEST_OVERRIDE { return 0; } + virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int value) CPPUTEST_OVERRIDE { return value; } - virtual double returnDoubleValue() _override { return 0.0; } - virtual double returnDoubleValueOrDefault(double value) _override { return value; } + virtual double returnDoubleValue() CPPUTEST_OVERRIDE { return 0.0; } + virtual double returnDoubleValueOrDefault(double value) CPPUTEST_OVERRIDE { return value; } - virtual const char * returnStringValue() _override { return ""; } - virtual const char * returnStringValueOrDefault(const char * value) _override { return value; } + virtual const char * returnStringValue() CPPUTEST_OVERRIDE { return ""; } + virtual const char * returnStringValueOrDefault(const char * value) CPPUTEST_OVERRIDE { return value; } - virtual void * returnPointerValue() _override { return NULL; } - virtual void * returnPointerValueOrDefault(void * value) _override { return value; } + virtual void * returnPointerValue() CPPUTEST_OVERRIDE { return NULLPTR; } + virtual void * returnPointerValueOrDefault(void * value) CPPUTEST_OVERRIDE { return value; } - virtual const void * returnConstPointerValue() _override { return NULL; } - virtual const void * returnConstPointerValueOrDefault(const void * value) _override { return value; } + virtual const void * returnConstPointerValue() CPPUTEST_OVERRIDE { return NULLPTR; } + virtual const void * returnConstPointerValueOrDefault(const void * value) CPPUTEST_OVERRIDE { return value; } - virtual void (*returnFunctionPointerValue())() _override { return NULL; } - virtual void (*returnFunctionPointerValueOrDefault(void (*value)()))() _override { return value; } + virtual MockCheckedActualCall::FunctionPointerReturnValue returnFunctionPointerValue() CPPUTEST_OVERRIDE { return NULLPTR; } + virtual MockCheckedActualCall::FunctionPointerReturnValue returnFunctionPointerValueOrDefault(void (*value)()) CPPUTEST_OVERRIDE { return value; } - virtual MockActualCall& onObject(const void* ) _override { return *this; } + virtual MockActualCall& onObject(const void* ) CPPUTEST_OVERRIDE { return *this; } static MockIgnoredActualCall& instance(); }; diff --git a/include/CppUTestExt/MockCheckedExpectedCall.h b/include/CppUTestExt/MockCheckedExpectedCall.h index e3f3725af..a1a87fd6e 100644 --- a/include/CppUTestExt/MockCheckedExpectedCall.h +++ b/include/CppUTestExt/MockCheckedExpectedCall.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -36,40 +36,48 @@ class MockCheckedExpectedCall : public MockExpectedCall public: MockCheckedExpectedCall(); - virtual ~MockCheckedExpectedCall(); - - virtual MockExpectedCall& withName(const SimpleString& name) _override; - virtual MockExpectedCall& withCallOrder(int callOrder) _override; - virtual MockExpectedCall& withBoolParameter(const SimpleString& name, bool value) _override; - virtual MockExpectedCall& withIntParameter(const SimpleString& name, int value) _override; - virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) _override; - virtual MockExpectedCall& withLongIntParameter(const SimpleString& name, long int value) _override; - virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) _override; - virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value) _override; - virtual MockExpectedCall& withStringParameter(const SimpleString& name, const char* value) _override; - virtual MockExpectedCall& withPointerParameter(const SimpleString& name, void* value) _override; - virtual MockExpectedCall& withConstPointerParameter(const SimpleString& name, const void* value) _override; - virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) _override; - virtual MockExpectedCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) _override; - virtual MockExpectedCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value) _override; - virtual MockExpectedCall& withOutputParameterReturning(const SimpleString& name, const void* value, size_t size) _override; - virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString& typeName, const SimpleString& name, const void* value) _override; - virtual MockExpectedCall& ignoreOtherParameters() _override; - - virtual MockExpectedCall& andReturnValue(bool value) _override; - virtual MockExpectedCall& andReturnValue(int value) _override; - virtual MockExpectedCall& andReturnValue(unsigned int value) _override; - virtual MockExpectedCall& andReturnValue(long int value) _override; - virtual MockExpectedCall& andReturnValue(unsigned long int value) _override; - virtual MockExpectedCall& andReturnValue(double value) _override; - virtual MockExpectedCall& andReturnValue(const char* value) _override; - virtual MockExpectedCall& andReturnValue(void* value) _override; - virtual MockExpectedCall& andReturnValue(const void* value) _override; - virtual MockExpectedCall& andReturnValue(void (*value)()) _override; + MockCheckedExpectedCall(unsigned int numCalls); + virtual ~MockCheckedExpectedCall() CPPUTEST_DESTRUCTOR_OVERRIDE; + + virtual MockExpectedCall& withName(const SimpleString& name) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withCallOrder(unsigned int callOrder) CPPUTEST_OVERRIDE { return withCallOrder(callOrder, callOrder); } + virtual MockExpectedCall& withCallOrder(unsigned int initialCallOrder, unsigned int finalCallOrder) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withBoolParameter(const SimpleString& name, bool value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withIntParameter(const SimpleString& name, int value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withLongIntParameter(const SimpleString& name, long int value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withLongLongIntParameter(const SimpleString& name, cpputest_longlong value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value, double tolerance) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withStringParameter(const SimpleString& name, const char* value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withPointerParameter(const SimpleString& name, void* value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withConstPointerParameter(const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withOutputParameterReturning(const SimpleString& name, const void* value, size_t size) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString& typeName, const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& withUnmodifiedOutputParameter(const SimpleString& name) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& ignoreOtherParameters() CPPUTEST_OVERRIDE; + + virtual MockExpectedCall& andReturnValue(bool value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& andReturnValue(int value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& andReturnValue(unsigned int value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& andReturnValue(long int value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& andReturnValue(unsigned long int value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& andReturnValue(cpputest_longlong value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& andReturnValue(cpputest_ulonglong value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& andReturnValue(double value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& andReturnValue(const char* value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& andReturnValue(void* value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& andReturnValue(const void* value) CPPUTEST_OVERRIDE; + virtual MockExpectedCall& andReturnValue(void (*value)()) CPPUTEST_OVERRIDE; virtual MockNamedValue returnValue(); - virtual MockExpectedCall& onObject(void* objectPtr) _override; + virtual MockExpectedCall& onObject(void* objectPtr) CPPUTEST_OVERRIDE; virtual MockNamedValue getInputParameter(const SimpleString& name); virtual MockNamedValue getOutputParameter(const SimpleString& name); @@ -84,23 +92,25 @@ class MockCheckedExpectedCall : public MockExpectedCall virtual bool relatesToObject(const void* objectPtr) const; virtual bool isFulfilled(); - virtual bool isFulfilledWithoutIgnoredParameters(); - virtual bool areParametersFulfilled(); - virtual bool areIgnoredParametersFulfilled(); + virtual bool canMatchActualCalls(); + virtual bool isMatchingActualCallAndFinalized(); + virtual bool isMatchingActualCall(); + virtual bool areParametersMatchingActualCall(); virtual bool isOutOfOrder() const; - virtual void callWasMade(int callOrder); + virtual void callWasMade(unsigned int callOrder); virtual void inputParameterWasPassed(const SimpleString& name); virtual void outputParameterWasPassed(const SimpleString& name); - virtual void parametersWereIgnored(); + virtual void finalizeActualCallMatch(); virtual void wasPassedToObject(); - virtual void resetExpectation(); + virtual void resetActualCallMatchingState(); virtual SimpleString callToString(); virtual SimpleString missingParametersToString(); - enum { NOT_CALLED_YET = -1, NO_EXPECTED_CALL_ORDER = -1}; - virtual int getCallOrder() const; + enum { NO_EXPECTED_CALL_ORDER = 0 }; + + virtual unsigned int getActualCallsFulfilled() const; protected: void setName(const SimpleString& name); @@ -113,105 +123,71 @@ class MockCheckedExpectedCall : public MockExpectedCall { public: MockExpectedFunctionParameter(const SimpleString& name); - void setFulfilled(bool b); - bool isFulfilled() const; + void setMatchesActualCall(bool b); + bool isMatchingActualCall() const; private: - bool fulfilled_; + bool matchesActualCall_; }; MockExpectedFunctionParameter* item(MockNamedValueListNode* node); bool ignoreOtherParameters_; - bool parametersWereIgnored_; - int callOrder_; - int expectedCallOrder_; + bool isActualCallMatchFinalized_; + unsigned int initialExpectedCallOrder_; + unsigned int finalExpectedCallOrder_; bool outOfOrder_; MockNamedValueList* inputParameters_; MockNamedValueList* outputParameters_; MockNamedValue returnValue_; void* objectPtr_; + bool isSpecificObjectExpected_; bool wasPassedToObject_; -}; - -struct MockExpectedCallCompositeNode; -class MockExpectedCallComposite : public MockExpectedCall -{ -public: - MockExpectedCallComposite(); - virtual ~MockExpectedCallComposite(); - - virtual MockExpectedCall& withName(const SimpleString& name) _override; - virtual MockExpectedCall& withCallOrder(int callOrder) _override; - virtual MockExpectedCall& withBoolParameter(const SimpleString& name, bool value) _override; - virtual MockExpectedCall& withIntParameter(const SimpleString& name, int value) _override; - virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) _override; - virtual MockExpectedCall& withLongIntParameter(const SimpleString& name, long int value) _override; - virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) _override; - virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value) _override; - virtual MockExpectedCall& withStringParameter(const SimpleString& name, const char* value) _override; - virtual MockExpectedCall& withConstPointerParameter(const SimpleString& name, const void* value) _override; - virtual MockExpectedCall& withPointerParameter(const SimpleString& name, void* value) _override; - virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) _override; - virtual MockExpectedCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) _override; - virtual MockExpectedCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value) _override; - virtual MockExpectedCall& withOutputParameterReturning(const SimpleString& name, const void* value, size_t size) _override; - virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString& typeName, const SimpleString& name, const void* value) _override; - virtual MockExpectedCall& ignoreOtherParameters() _override; - - virtual MockExpectedCall& andReturnValue(bool value) _override; - virtual MockExpectedCall& andReturnValue(int value) _override; - virtual MockExpectedCall& andReturnValue(unsigned int value) _override; - virtual MockExpectedCall& andReturnValue(long int value) _override; - virtual MockExpectedCall& andReturnValue(unsigned long int value) _override; - virtual MockExpectedCall& andReturnValue(double value) _override; - virtual MockExpectedCall& andReturnValue(const char* value) _override; - virtual MockExpectedCall& andReturnValue(void* value) _override; - virtual MockExpectedCall& andReturnValue(const void* value) _override; - virtual MockExpectedCall& andReturnValue(void (*value)()) _override; - - virtual MockExpectedCall& onObject(void* objectPtr) _override; - - virtual void add(MockExpectedCall& call); - virtual void clear(); -private: - MockExpectedCallCompositeNode* head_; + unsigned int actualCalls_; + unsigned int expectedCalls_; }; class MockIgnoredExpectedCall: public MockExpectedCall { public: - virtual MockExpectedCall& withName(const SimpleString&) _override { return *this;} - virtual MockExpectedCall& withCallOrder(int) _override { return *this; } - virtual MockExpectedCall& withBoolParameter(const SimpleString&, bool) _override { return *this; } - virtual MockExpectedCall& withIntParameter(const SimpleString&, int) _override { return *this; } - virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString&, unsigned int) _override{ return *this; } - virtual MockExpectedCall& withLongIntParameter(const SimpleString&, long int) _override { return *this; } - virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString&, unsigned long int) _override { return *this; } - virtual MockExpectedCall& withDoubleParameter(const SimpleString&, double) _override { return *this; } - virtual MockExpectedCall& withStringParameter(const SimpleString&, const char*) _override { return *this; } - virtual MockExpectedCall& withPointerParameter(const SimpleString& , void*) _override { return *this; } - virtual MockExpectedCall& withConstPointerParameter(const SimpleString& , const void*) _override { return *this; } - virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& , void(*)()) _override { return *this; } - virtual MockExpectedCall& withMemoryBufferParameter(const SimpleString&, const unsigned char*, size_t) _override { return *this; } - virtual MockExpectedCall& withParameterOfType(const SimpleString&, const SimpleString&, const void*) _override { return *this; } - virtual MockExpectedCall& withOutputParameterReturning(const SimpleString&, const void*, size_t) _override { return *this; } - virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString&, const SimpleString&, const void*) _override { return *this; } - virtual MockExpectedCall& ignoreOtherParameters() _override { return *this;} - - virtual MockExpectedCall& andReturnValue(bool) _override { return *this; } - virtual MockExpectedCall& andReturnValue(int) _override { return *this; } - virtual MockExpectedCall& andReturnValue(unsigned int) _override { return *this; } - virtual MockExpectedCall& andReturnValue(long int) _override { return *this; } - virtual MockExpectedCall& andReturnValue(unsigned long int) _override { return *this; } - virtual MockExpectedCall& andReturnValue(double) _override { return *this;} - virtual MockExpectedCall& andReturnValue(const char*) _override { return *this; } - virtual MockExpectedCall& andReturnValue(void*) _override { return *this; } - virtual MockExpectedCall& andReturnValue(const void*) _override { return *this; } - virtual MockExpectedCall& andReturnValue(void (*)()) _override { return *this; } - - virtual MockExpectedCall& onObject(void*) _override { return *this; } + virtual MockExpectedCall& withName(const SimpleString&) CPPUTEST_OVERRIDE { return *this;} + virtual MockExpectedCall& withCallOrder(unsigned int) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withCallOrder(unsigned int, unsigned int) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withBoolParameter(const SimpleString&, bool) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withIntParameter(const SimpleString&, int) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString&, unsigned int) CPPUTEST_OVERRIDE{ return *this; } + virtual MockExpectedCall& withLongIntParameter(const SimpleString&, long int) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString&, unsigned long int) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withLongLongIntParameter(const SimpleString&, cpputest_longlong) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withUnsignedLongLongIntParameter(const SimpleString&, cpputest_ulonglong) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withDoubleParameter(const SimpleString&, double) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withDoubleParameter(const SimpleString&, double, double) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withStringParameter(const SimpleString&, const char*) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withPointerParameter(const SimpleString& , void*) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withConstPointerParameter(const SimpleString& , const void*) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& , void(*)()) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withMemoryBufferParameter(const SimpleString&, const unsigned char*, size_t) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withParameterOfType(const SimpleString&, const SimpleString&, const void*) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withOutputParameterReturning(const SimpleString&, const void*, size_t) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString&, const SimpleString&, const void*) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& withUnmodifiedOutputParameter(const SimpleString&) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& ignoreOtherParameters() CPPUTEST_OVERRIDE { return *this;} + + virtual MockExpectedCall& andReturnValue(bool) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& andReturnValue(int) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& andReturnValue(unsigned int) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& andReturnValue(long int) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& andReturnValue(unsigned long int) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& andReturnValue(cpputest_longlong) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& andReturnValue(cpputest_ulonglong) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& andReturnValue(double) CPPUTEST_OVERRIDE { return *this;} + virtual MockExpectedCall& andReturnValue(const char*) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& andReturnValue(void*) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& andReturnValue(const void*) CPPUTEST_OVERRIDE { return *this; } + virtual MockExpectedCall& andReturnValue(void (*)()) CPPUTEST_OVERRIDE { return *this; } + + virtual MockExpectedCall& onObject(void*) CPPUTEST_OVERRIDE { return *this; } static MockExpectedCall& instance(); }; diff --git a/include/CppUTestExt/MockExpectedCall.h b/include/CppUTestExt/MockExpectedCall.h index 73120e7f1..e043de886 100644 --- a/include/CppUTestExt/MockExpectedCall.h +++ b/include/CppUTestExt/MockExpectedCall.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -28,6 +28,8 @@ #ifndef D_MockExpectedCall_h #define D_MockExpectedCall_h +#include "CppUTest/CppUTestConfig.h" + class MockNamedValue; extern SimpleString StringFrom(const MockNamedValue& parameter); @@ -39,13 +41,17 @@ class MockExpectedCall virtual ~MockExpectedCall(); virtual MockExpectedCall& withName(const SimpleString& name)=0; - virtual MockExpectedCall& withCallOrder(int)=0; + virtual MockExpectedCall& withCallOrder(unsigned int)=0; + virtual MockExpectedCall& withCallOrder(unsigned int, unsigned int)=0; MockExpectedCall& withParameter(const SimpleString& name, bool value) { return withBoolParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, int value) { return withIntParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, unsigned int value) { return withUnsignedIntParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, long int value) { return withLongIntParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, unsigned long int value) { return withUnsignedLongIntParameter(name, value); } + MockExpectedCall& withParameter(const SimpleString& name, cpputest_longlong value) { return withLongLongIntParameter(name, value); } + MockExpectedCall& withParameter(const SimpleString& name, cpputest_ulonglong value) { return withUnsignedLongLongIntParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, double value) { return withDoubleParameter(name, value); } + MockExpectedCall& withParameter(const SimpleString& name, double value, double tolerance) { return withDoubleParameter(name, value, tolerance); } MockExpectedCall& withParameter(const SimpleString& name, const char* value) { return withStringParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, void* value) { return withPointerParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, const void* value) { return withConstPointerParameter(name, value); } @@ -54,6 +60,7 @@ class MockExpectedCall virtual MockExpectedCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value)=0; virtual MockExpectedCall& withOutputParameterReturning(const SimpleString& name, const void* value, size_t size)=0; virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString& typeName, const SimpleString& name, const void* value)=0; + virtual MockExpectedCall& withUnmodifiedOutputParameter(const SimpleString& name)=0; virtual MockExpectedCall& ignoreOtherParameters()=0; virtual MockExpectedCall& withBoolParameter(const SimpleString& name, bool value)=0; @@ -61,7 +68,10 @@ class MockExpectedCall virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value)=0; virtual MockExpectedCall& withLongIntParameter(const SimpleString& name, long int value)=0; virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value)=0; + virtual MockExpectedCall& withLongLongIntParameter(const SimpleString& name, cpputest_longlong value)=0; + virtual MockExpectedCall& withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value)=0; virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value)=0; + virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value, double tolerance)=0; virtual MockExpectedCall& withStringParameter(const SimpleString& name, const char* value)=0; virtual MockExpectedCall& withPointerParameter(const SimpleString& name, void* value)=0; virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& name, void (*value)())=0; @@ -72,6 +82,8 @@ class MockExpectedCall virtual MockExpectedCall& andReturnValue(unsigned int value)=0; virtual MockExpectedCall& andReturnValue(long int value)=0; virtual MockExpectedCall& andReturnValue(unsigned long int value)=0; + virtual MockExpectedCall& andReturnValue(cpputest_longlong value)=0; + virtual MockExpectedCall& andReturnValue(cpputest_ulonglong value)=0; virtual MockExpectedCall& andReturnValue(double value)=0; virtual MockExpectedCall& andReturnValue(const char* value)=0; virtual MockExpectedCall& andReturnValue(void* value)=0; diff --git a/include/CppUTestExt/MockExpectedCallsList.h b/include/CppUTestExt/MockExpectedCallsList.h index ea29b0f1c..3cb2e651d 100644 --- a/include/CppUTestExt/MockExpectedCallsList.h +++ b/include/CppUTestExt/MockExpectedCallsList.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -39,13 +39,12 @@ class MockExpectedCallsList virtual ~MockExpectedCallsList(); virtual void deleteAllExpectationsAndClearList(); - virtual int size() const; - virtual int amountOfExpectationsFor(const SimpleString& name) const; - virtual int amountOfUnfulfilledExpectations() const; + virtual unsigned int size() const; + virtual unsigned int amountOfActualCallsFulfilledFor(const SimpleString& name) const; + virtual unsigned int amountOfUnfulfilledExpectations() const; virtual bool hasUnfulfilledExpectations() const; - virtual bool hasFulfilledExpectations() const; - virtual bool hasFulfilledExpectationsWithoutIgnoredParameters() const; - virtual bool hasUnfulfilledExpectationsBecauseOfMissingParameters() const; + virtual bool hasFinalizedMatchingExpectations() const; + virtual bool hasUnmatchingExpectationsBecauseOfMissingParameters() const; virtual bool hasExpectationWithName(const SimpleString& name) const; virtual bool hasCallsOutOfOrder() const; virtual bool isEmpty() const; @@ -55,7 +54,7 @@ class MockExpectedCallsList virtual void addExpectationsRelatedTo(const SimpleString& name, const MockExpectedCallsList& list); virtual void onlyKeepOutOfOrderExpectations(); - virtual void addUnfulfilledExpectations(const MockExpectedCallsList& list); + virtual void addPotentiallyMatchingExpectations(const MockExpectedCallsList& list); virtual void onlyKeepExpectationsRelatedTo(const SimpleString& name); virtual void onlyKeepExpectationsWithInputParameter(const MockNamedValue& parameter); @@ -63,21 +62,21 @@ class MockExpectedCallsList virtual void onlyKeepExpectationsWithOutputParameter(const MockNamedValue& parameter); virtual void onlyKeepExpectationsWithOutputParameterName(const SimpleString& name); virtual void onlyKeepExpectationsOnObject(const void* objectPtr); - virtual void onlyKeepUnfulfilledExpectations(); + virtual void onlyKeepUnmatchingExpectations(); - virtual MockCheckedExpectedCall* removeOneFulfilledExpectation(); - virtual MockCheckedExpectedCall* removeOneFulfilledExpectationWithIgnoredParameters(); - virtual MockCheckedExpectedCall* getOneFulfilledExpectationWithIgnoredParameters(); + virtual MockCheckedExpectedCall* removeFirstFinalizedMatchingExpectation(); + virtual MockCheckedExpectedCall* removeFirstMatchingExpectation(); + virtual MockCheckedExpectedCall* getFirstMatchingExpectation(); - virtual void resetExpectations(); - virtual void callWasMade(int callOrder); + virtual void resetActualCallMatchingState(); virtual void wasPassedToObject(); virtual void parameterWasPassed(const SimpleString& parameterName); virtual void outputParameterWasPassed(const SimpleString& parameterName); virtual SimpleString unfulfilledCallsToString(const SimpleString& linePrefix = "") const; virtual SimpleString fulfilledCallsToString(const SimpleString& linePrefix = "") const; - virtual SimpleString missingParametersToString() const; + virtual SimpleString callsWithMissingParametersToString(const SimpleString& linePrefix, + const SimpleString& missingParametersPrefix) const; protected: virtual void pruneEmptyNodeFromList(); @@ -89,10 +88,9 @@ class MockExpectedCallsList MockExpectedCallsListNode* next_; MockExpectedCallsListNode(MockCheckedExpectedCall* expectedCall) - : expectedCall_(expectedCall), next_(NULL) {} + : expectedCall_(expectedCall), next_(NULLPTR) {} }; - virtual MockExpectedCallsListNode* findNodeWithCallOrderOf(int callOrder) const; private: MockExpectedCallsListNode* head_; diff --git a/include/CppUTestExt/MockFailure.h b/include/CppUTestExt/MockFailure.h index 8cfdced74..3ee4f73d3 100644 --- a/include/CppUTestExt/MockFailure.h +++ b/include/CppUTestExt/MockFailure.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -54,7 +54,7 @@ class MockFailure : public TestFailure { public: MockFailure(UtestShell* test); - virtual ~MockFailure(){} + virtual ~MockFailure() CPPUTEST_DESTRUCTOR_OVERRIDE {} protected: void addExpectationsAndCallHistory(const MockExpectedCallsList& expectations); void addExpectationsAndCallHistoryRelatedTo(const SimpleString& function, const MockExpectedCallsList& expectations); @@ -93,7 +93,8 @@ class MockUnexpectedOutputParameterFailure : public MockFailure class MockExpectedParameterDidntHappenFailure : public MockFailure { public: - MockExpectedParameterDidntHappenFailure(UtestShell* test, const SimpleString& functionName, const MockExpectedCallsList& expectations); + MockExpectedParameterDidntHappenFailure(UtestShell* test, const SimpleString& functionName, const MockExpectedCallsList& allExpectations, + const MockExpectedCallsList& matchingExpectations); }; class MockNoWayToCompareCustomTypeFailure : public MockFailure diff --git a/include/CppUTestExt/MockNamedValue.h b/include/CppUTestExt/MockNamedValue.h index 2e08be75a..b6e5be2cc 100644 --- a/include/CppUTestExt/MockNamedValue.h +++ b/include/CppUTestExt/MockNamedValue.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -27,6 +27,9 @@ #ifndef D_MockNamedValue_h #define D_MockNamedValue_h + +#include "CppUTest/CppUTestConfig.h" + /* * MockNamedValueComparator is an interface that needs to be used when creating Comparators. * This is needed when comparing values of non-native type. @@ -66,8 +69,8 @@ class MockFunctionComparator : public MockNamedValueComparator MockFunctionComparator(isEqualFunction equal, valueToStringFunction valToString) : equal_(equal), valueToString_(valToString) {} - virtual bool isEqual(const void* object1, const void* object2) _override { return equal_(object1, object2); } - virtual SimpleString valueToString(const void* object) _override { return valueToString_(object); } + virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { return equal_(object1, object2); } + virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { return valueToString_(object); } private: isEqualFunction equal_; valueToStringFunction valueToString_; @@ -80,7 +83,7 @@ class MockFunctionCopier : public MockNamedValueCopier MockFunctionCopier(copyFunction copier) : copier_(copier) {} - virtual void copy(void* dst, const void* src) _override { copier_(dst, src); } + virtual void copy(void* dst, const void* src) CPPUTEST_OVERRIDE { copier_(dst, src); } private: copyFunction copier_; @@ -106,13 +109,17 @@ class MockNamedValue virtual void setValue(unsigned int value); virtual void setValue(long int value); virtual void setValue(unsigned long int value); + virtual void setValue(cpputest_longlong value); + virtual void setValue(cpputest_ulonglong value); virtual void setValue(double value); + virtual void setValue(double value, double tolerance); virtual void setValue(void* value); virtual void setValue(const void* value); virtual void setValue(void (*value)()); virtual void setValue(const char* value); virtual void setMemoryBuffer(const unsigned char* value, size_t size); - virtual void setObjectPointer(const SimpleString& type, const void* objectPtr); + virtual void setConstObjectPointer(const SimpleString& type, const void* objectPtr); + virtual void setObjectPointer(const SimpleString& type, void* objectPtr); virtual void setSize(size_t size); virtual void setName(const char* name); @@ -130,19 +137,27 @@ class MockNamedValue virtual unsigned int getUnsignedIntValue() const; virtual long int getLongIntValue() const; virtual unsigned long int getUnsignedLongIntValue() const; + virtual cpputest_longlong getLongLongIntValue() const; + virtual cpputest_ulonglong getUnsignedLongLongIntValue() const; virtual double getDoubleValue() const; + virtual double getDoubleTolerance() const; virtual const char* getStringValue() const; virtual void* getPointerValue() const; virtual const void* getConstPointerValue() const; virtual void (*getFunctionPointerValue() const)(); virtual const unsigned char* getMemoryBuffer() const; - virtual const void* getObjectPointer() const; + virtual const void* getConstObjectPointer() const; + virtual void* getObjectPointer() const; virtual size_t getSize() const; + virtual MockNamedValueComparator* getComparator() const; virtual MockNamedValueCopier* getCopier() const; static void setDefaultComparatorsAndCopiersRepository(MockNamedValueComparatorsAndCopiersRepository* repository); + static MockNamedValueComparatorsAndCopiersRepository* getDefaultComparatorsAndCopiersRepository(); + + static const double defaultDoubleTolerance; private: SimpleString name_; SimpleString type_; @@ -152,13 +167,23 @@ class MockNamedValue unsigned int unsignedIntValue_; long int longIntValue_; unsigned long int unsignedLongIntValue_; - double doubleValue_; +#if CPPUTEST_USE_LONG_LONG + cpputest_longlong longLongIntValue_; + cpputest_ulonglong unsignedLongLongIntValue_; +#else + char longLongPlaceholder_[CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE]; +#endif + struct { + double value; + double tolerance; + } doubleValue_; const char* stringValue_; void* pointerValue_; const void* constPointerValue_; void (*functionPointerValue_)(); const unsigned char* memoryBufferValue_; - const void* objectPointerValue_; + const void* constObjectPointerValue_; + void* objectPointerValue_; const void* outputPointerValue_; } value_; size_t size_; diff --git a/include/CppUTestExt/MockSupport.h b/include/CppUTestExt/MockSupport.h old mode 100755 new mode 100644 index e58bf2a57..c8532187d --- a/include/CppUTestExt/MockSupport.h +++ b/include/CppUTestExt/MockSupport.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -37,7 +37,7 @@ class UtestShell; class MockSupport; /* This allows access to "the global" mocking support for easier testing */ -MockSupport& mock(const SimpleString& mockName = "", MockFailureReporter* failureReporterForThisCall = NULL); +MockSupport& mock(const SimpleString& mockName = "", MockFailureReporter* failureReporterForThisCall = NULLPTR); class MockSupport { @@ -48,7 +48,7 @@ class MockSupport virtual void strictOrder(); virtual MockExpectedCall& expectOneCall(const SimpleString& functionName); virtual void expectNoCall(const SimpleString& functionName); - virtual MockExpectedCall& expectNCalls(int amount, const SimpleString& functionName); + virtual MockExpectedCall& expectNCalls(unsigned int amount, const SimpleString& functionName); virtual MockActualCall& actualCall(const SimpleString& functionName); virtual bool hasReturnValue(); virtual MockNamedValue returnValue(); @@ -61,6 +61,10 @@ class MockSupport virtual long int returnLongIntValueOrDefault(long int defaultValue); virtual unsigned long int unsignedLongIntReturnValue(); virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int defaultValue); + virtual cpputest_longlong longLongIntReturnValue(); + virtual cpputest_longlong returnLongLongIntValueOrDefault(cpputest_longlong defaultValue); + virtual cpputest_ulonglong unsignedLongLongIntReturnValue(); + virtual cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong defaultValue); virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int defaultValue); virtual const char* stringReturnValue(); virtual const char* returnStringValueOrDefault(const char * defaultValue); @@ -77,12 +81,15 @@ class MockSupport void setData(const SimpleString& name, bool value); void setData(const SimpleString& name, int value); void setData(const SimpleString& name, unsigned int value); + void setData(const SimpleString& name, long int value); + void setData(const SimpleString& name, unsigned long int value); void setData(const SimpleString& name, const char* value); void setData(const SimpleString& name, double value); void setData(const SimpleString& name, void* value); void setData(const SimpleString& name, const void* value); void setData(const SimpleString& name, void (*value)()); void setDataObject(const SimpleString& name, const SimpleString& type, void* value); + void setDataConstObject(const SimpleString& name, const SimpleString& type, const void* value); MockNamedValue getData(const SimpleString& name); MockSupport* getMockSupportScope(const SimpleString& name); @@ -119,40 +126,37 @@ class MockSupport protected: MockSupport* clone(const SimpleString& mockName); - virtual MockCheckedActualCall *createActualFunctionCall(); + virtual MockCheckedActualCall *createActualCall(); virtual void failTest(MockFailure& failure); void countCheck(); private: - int callOrder_; - int expectedCallOrder_; + unsigned int actualCallOrder_; + unsigned int expectedCallOrder_; bool strictOrdering_; MockFailureReporter *activeReporter_; MockFailureReporter *standardReporter_; MockFailureReporter defaultReporter_; MockExpectedCallsList expectations_; - MockExpectedCallsList unExpectations_; bool ignoreOtherCalls_; bool enabled_; MockCheckedActualCall *lastActualFunctionCall_; - MockExpectedCallComposite compositeCalls_; MockNamedValueComparatorsAndCopiersRepository comparatorsAndCopiersRepository_; MockNamedValueList data_; const SimpleString mockName_; bool tracing_; - void checkExpectationsOfLastCall(); - bool wasLastCallFulfilled(); - void failTestWithUnexpectedCalls(); + void checkExpectationsOfLastActualCall(); + bool wasLastActualCallFulfilled(); + void failTestWithExpectedCallsNotFulfilled(); void failTestWithOutOfOrderCalls(); MockNamedValue* retrieveDataFromStore(const SimpleString& name); MockSupport* getMockSupport(MockNamedValueListNode* node); - bool hasntExpectationWithName(const SimpleString& functionName); - bool hasntUnexpectationWithName(const SimpleString& functionName); + bool callIsIgnored(const SimpleString& functionName); bool hasCallsOutOfOrder(); SimpleString appendScopeToName(const SimpleString& functionName); diff --git a/include/CppUTestExt/MockSupportPlugin.h b/include/CppUTestExt/MockSupportPlugin.h index 3ccd18ab4..b77041c38 100644 --- a/include/CppUTestExt/MockSupportPlugin.h +++ b/include/CppUTestExt/MockSupportPlugin.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -35,13 +35,15 @@ class MockSupportPlugin : public TestPlugin { public: MockSupportPlugin(const SimpleString& name = "MockSupportPLugin"); - virtual ~MockSupportPlugin(); + virtual ~MockSupportPlugin() CPPUTEST_DESTRUCTOR_OVERRIDE; - virtual void preTestAction(UtestShell&, TestResult&) _override; - virtual void postTestAction(UtestShell&, TestResult&) _override; + virtual void preTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE; + virtual void postTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE; virtual void installComparator(const SimpleString& name, MockNamedValueComparator& comparator); virtual void installCopier(const SimpleString& name, MockNamedValueCopier& copier); + + void clear(); private: MockNamedValueComparatorsAndCopiersRepository repository_; }; diff --git a/include/CppUTestExt/MockSupport_c.h b/include/CppUTestExt/MockSupport_c.h index 0706d5472..fc2745f1e 100644 --- a/include/CppUTestExt/MockSupport_c.h +++ b/include/CppUTestExt/MockSupport_c.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -32,6 +32,7 @@ extern "C" { #endif +#include "CppUTest/CppUTestConfig.h" #include "CppUTest/StandardCLibrary.h" typedef enum { @@ -40,6 +41,8 @@ typedef enum { MOCKVALUETYPE_INTEGER, MOCKVALUETYPE_LONG_INTEGER, MOCKVALUETYPE_UNSIGNED_LONG_INTEGER, + MOCKVALUETYPE_LONG_LONG_INTEGER, + MOCKVALUETYPE_UNSIGNED_LONG_LONG_INTEGER, MOCKVALUETYPE_DOUBLE, MOCKVALUETYPE_STRING, MOCKVALUETYPE_POINTER, @@ -58,13 +61,20 @@ typedef struct SMockValue_c unsigned int unsignedIntValue; long int longIntValue; unsigned long int unsignedLongIntValue; +#if CPPUTEST_USE_LONG_LONG + cpputest_longlong longLongIntValue; + cpputest_ulonglong unsignedLongLongIntValue; +#else + char longLongPlaceholder[CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE]; +#endif double doubleValue; const char* stringValue; void* pointerValue; const void* constPointerValue; void (*functionPointerValue)(void); const unsigned char* memoryBufferValue; - const void* objectValue; + void* objectValue; + const void* constObjectValue; } value; } MockValue_c; @@ -76,6 +86,8 @@ struct SMockActualCall_c MockActualCall_c* (*withUnsignedIntParameters)(const char* name, unsigned int value); MockActualCall_c* (*withLongIntParameters)(const char* name, long int value); MockActualCall_c* (*withUnsignedLongIntParameters)(const char* name, unsigned long int value); + MockActualCall_c* (*withLongLongIntParameters)(const char* name, cpputest_longlong value); + MockActualCall_c* (*withUnsignedLongLongIntParameters)(const char* name, cpputest_ulonglong value); MockActualCall_c* (*withDoubleParameters)(const char* name, double value); MockActualCall_c* (*withStringParameters)(const char* name, const char* value); MockActualCall_c* (*withPointerParameters)(const char* name, void* value); @@ -97,6 +109,10 @@ struct SMockActualCall_c long int (*returnLongIntValueOrDefault)(long int defaultValue); unsigned long int (*unsignedLongIntReturnValue)(void); unsigned long int (*returnUnsignedLongIntValueOrDefault)(unsigned long int defaultValue); + cpputest_longlong (*longLongIntReturnValue)(void); + cpputest_longlong (*returnLongLongIntValueOrDefault)(cpputest_longlong defaultValue); + cpputest_ulonglong (*unsignedLongLongIntReturnValue)(void); + cpputest_ulonglong (*returnUnsignedLongLongIntValueOrDefault)(cpputest_ulonglong defaultValue); const char* (*stringReturnValue)(void); const char* (*returnStringValueOrDefault)(const char * defaultValue); double (*doubleReturnValue)(void); @@ -117,7 +133,10 @@ struct SMockExpectedCall_c MockExpectedCall_c* (*withUnsignedIntParameters)(const char* name, unsigned int value); MockExpectedCall_c* (*withLongIntParameters)(const char* name, long int value); MockExpectedCall_c* (*withUnsignedLongIntParameters)(const char* name, unsigned long int value); + MockExpectedCall_c* (*withLongLongIntParameters)(const char* name, cpputest_longlong value); + MockExpectedCall_c* (*withUnsignedLongLongIntParameters)(const char* name, cpputest_ulonglong value); MockExpectedCall_c* (*withDoubleParameters)(const char* name, double value); + MockExpectedCall_c* (*withDoubleParametersAndTolerance)(const char* name, double value, double tolerance); MockExpectedCall_c* (*withStringParameters)(const char* name, const char* value); MockExpectedCall_c* (*withPointerParameters)(const char* name, void* value); MockExpectedCall_c* (*withConstPointerParameters)(const char* name, const void* value); @@ -126,6 +145,7 @@ struct SMockExpectedCall_c MockExpectedCall_c* (*withParameterOfType)(const char* type, const char* name, const void* value); MockExpectedCall_c* (*withOutputParameterReturning)(const char* name, const void* value, size_t size); MockExpectedCall_c* (*withOutputParameterOfTypeReturning)(const char* type, const char* name, const void* value); + MockExpectedCall_c* (*withUnmodifiedOutputParameter)(const char* name); MockExpectedCall_c* (*ignoreOtherParameters)(void); MockExpectedCall_c* (*andReturnBoolValue)(int value); @@ -133,6 +153,8 @@ struct SMockExpectedCall_c MockExpectedCall_c* (*andReturnIntValue)(int value); MockExpectedCall_c* (*andReturnLongIntValue)(long int value); MockExpectedCall_c* (*andReturnUnsignedLongIntValue)(unsigned long int value); + MockExpectedCall_c* (*andReturnLongLongIntValue)(cpputest_longlong value); + MockExpectedCall_c* (*andReturnUnsignedLongLongIntValue)(cpputest_ulonglong value); MockExpectedCall_c* (*andReturnDoubleValue)(double value); MockExpectedCall_c* (*andReturnStringValue)(const char* value); MockExpectedCall_c* (*andReturnPointerValue)(void* value); @@ -150,7 +172,7 @@ struct SMockSupport_c void (*strictOrder)(void); MockExpectedCall_c* (*expectOneCall)(const char* name); void (*expectNoCall)(const char* name); - MockExpectedCall_c* (*expectNCalls)(int number, const char* name); + MockExpectedCall_c* (*expectNCalls)(unsigned int number, const char* name); MockActualCall_c* (*actualCall)(const char* name); int (*hasReturnValue)(void); MockValue_c (*returnValue)(void); @@ -164,6 +186,10 @@ struct SMockSupport_c long int (*returnLongIntValueOrDefault)(long int defaultValue); unsigned long int (*unsignedLongIntReturnValue)(void); unsigned long int (*returnUnsignedLongIntValueOrDefault)(unsigned long int defaultValue); + cpputest_longlong (*longLongIntReturnValue)(void); + cpputest_longlong (*returnLongLongIntValueOrDefault)(cpputest_longlong defaultValue); + cpputest_ulonglong (*unsignedLongLongIntReturnValue)(void); + cpputest_ulonglong (*returnUnsignedLongLongIntValueOrDefault)(cpputest_ulonglong defaultValue); const char* (*stringReturnValue)(void); const char* (*returnStringValueOrDefault)(const char * defaultValue); double (*doubleReturnValue)(void); @@ -178,12 +204,15 @@ struct SMockSupport_c void (*setBoolData) (const char* name, int value); void (*setIntData) (const char* name, int value); void (*setUnsignedIntData) (const char* name, unsigned int value); + void (*setLongIntData) (const char* name, long int value); + void (*setUnsignedLongIntData) (const char* name, unsigned long int value); void (*setStringData) (const char* name, const char* value); void (*setDoubleData) (const char* name, double value); void (*setPointerData) (const char* name, void* value); void (*setConstPointerData) (const char* name, const void* value); void (*setFunctionPointerData) (const char* name, void (*value)(void)); void (*setDataObject) (const char* name, const char* type, void* value); + void (*setDataConstObject) (const char* name, const char* type, const void* value); MockValue_c (*getData)(const char* name); void (*disable)(void); diff --git a/include/CppUTestExt/OrderedTest.h b/include/CppUTestExt/OrderedTest.h index cf1933966..3db756b2a 100644 --- a/include/CppUTestExt/OrderedTest.h +++ b/include/CppUTestExt/OrderedTest.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -32,7 +32,7 @@ class OrderedTestShell : public UtestShell { public: OrderedTestShell(); - virtual ~OrderedTestShell(); + virtual ~OrderedTestShell() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual OrderedTestShell* addOrderedTest(OrderedTestShell* test); virtual OrderedTestShell* getNextOrderedTest(); @@ -56,7 +56,7 @@ class OrderedTestShell : public UtestShell class OrderedTestInstaller { public: - explicit OrderedTestInstaller(OrderedTestShell& test, const char* groupName, const char* testName, const char* fileName, int lineNumber, int level); + explicit OrderedTestInstaller(OrderedTestShell& test, const char* groupName, const char* testName, const char* fileName, size_t lineNumber, int level); virtual ~OrderedTestInstaller(); private: @@ -71,12 +71,17 @@ class OrderedTestInstaller extern TEST_##testGroup##_##testName##_TestShell TEST_##testGroup##_##testName##_Instance; \ class TEST_##testGroup##_##testName##_Test : public TEST_GROUP_##CppUTestGroup##testGroup \ { public: TEST_##testGroup##_##testName##_Test () : TEST_GROUP_##CppUTestGroup##testGroup () {} \ - void testBody(); }; \ + void testBody() CPPUTEST_OVERRIDE; }; \ class TEST_##testGroup##_##testName##_TestShell : public OrderedTestShell { \ - virtual Utest* createTest() _override { return new TEST_##testGroup##_##testName##_Test; } \ + virtual Utest* createTest() CPPUTEST_OVERRIDE { return new TEST_##testGroup##_##testName##_Test; } \ } TEST_##testGroup##_##testName##_Instance; \ static OrderedTestInstaller TEST_##testGroup##_##testName##_Installer(TEST_##testGroup##_##testName##_Instance, #testGroup, #testName, __FILE__,__LINE__, testLevel); \ void TEST_##testGroup##_##testName##_Test::testBody() -#endif +#define TEST_ORDERED_C_WRAPPER(group_name, test_name, testLevel) \ + extern "C" void test_##group_name##_##test_name##_wrapper_c(void); \ + TEST_ORDERED(group_name, test_name, testLevel) { \ + test_##group_name##_##test_name##_wrapper_c(); \ + } +#endif diff --git a/include/Platforms/c2000/stdint.h b/include/Platforms/c2000/stdint.h index e2831fdc0..3e076a500 100644 --- a/include/Platforms/c2000/stdint.h +++ b/include/Platforms/c2000/stdint.h @@ -14,7 +14,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/m4/m4_ax_compiler_vendor.m4 b/m4/m4_ax_compiler_vendor.m4 new file mode 100644 index 000000000..f06e86540 --- /dev/null +++ b/m4/m4_ax_compiler_vendor.m4 @@ -0,0 +1,117 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_compiler_vendor.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_COMPILER_VENDOR +# +# DESCRIPTION +# +# Determine the vendor of the C, C++ or Fortran compiler. The vendor is +# returned in the cache variable $ax_cv_c_compiler_vendor for C, +# $ax_cv_cxx_compiler_vendor for C++ or $ax_cv_fc_compiler_vendor for +# (modern) Fortran. The value is one of "intel", "ibm", "pathscale", +# "clang" (LLVM), "cray", "fujitsu", "sdcc", "sx", "portland" (PGI), "gnu" +# (GCC), "sun" (Oracle Developer Studio), "hp", "dec", "borland", +# "comeau", "kai", "lcc", "sgi", "microsoft", "metrowerks", "watcom", +# "tcc" (Tiny CC) or "unknown" (if the compiler cannot be determined). +# +# To check for a Fortran compiler, you must first call AC_FC_PP_SRCEXT +# with an appropriate preprocessor-enabled extension. For example: +# +# AC_LANG_PUSH([Fortran]) +# AC_PROG_FC +# AC_FC_PP_SRCEXT([F]) +# AX_COMPILER_VENDOR +# AC_LANG_POP([Fortran]) +# +# LICENSE +# +# Copyright (c) 2008 Steven G. Johnson +# Copyright (c) 2008 Matteo Frigo +# Copyright (c) 2018-19 John Zaitseff +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. + +#serial 30 + +AC_DEFUN([AX_COMPILER_VENDOR], [dnl + AC_CACHE_CHECK([for _AC_LANG compiler vendor], ax_cv_[]_AC_LANG_ABBREV[]_compiler_vendor, [dnl + dnl If you modify this list of vendors, please add similar support + dnl to ax_compiler_version.m4 if at all possible. + dnl + dnl Note: Do NOT check for GCC first since some other compilers + dnl define __GNUC__ to remain compatible with it. Compilers that + dnl are very slow to start (such as Intel) are listed first. + + vendors=" + intel: __ICC,__ECC,__INTEL_COMPILER + ibm: __xlc__,__xlC__,__IBMC__,__IBMCPP__,__ibmxl__ + pathscale: __PATHCC__,__PATHSCALE__ + clang: __clang__ + cray: _CRAYC + fujitsu: __FUJITSU + sdcc: SDCC,__SDCC + sx: _SX + portland: __PGI + gnu: __GNUC__ + sun: __SUNPRO_C,__SUNPRO_CC,__SUNPRO_F90,__SUNPRO_F95 + hp: __HP_cc,__HP_aCC + dec: __DECC,__DECCXX,__DECC_VER,__DECCXX_VER + borland: __BORLANDC__,__CODEGEARC__,__TURBOC__ + comeau: __COMO__ + kai: __KCC + lcc: __LCC__ + sgi: __sgi,sgi + microsoft: _MSC_VER + metrowerks: __MWERKS__ + watcom: __WATCOMC__ + tcc: __TINYC__ + unknown: UNKNOWN + " + for ventest in $vendors; do + case $ventest in + *:) + vendor=$ventest + continue + ;; + *) + vencpp="defined("`echo $ventest | sed 's/,/) || defined(/g'`")" + ;; + esac + + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [[ +#if !($vencpp) + thisisanerror; +#endif + ]])], [break]) + done + + ax_cv_[]_AC_LANG_ABBREV[]_compiler_vendor=`echo $vendor | cut -d: -f1` + ]) +])dnl diff --git a/m4/m4_ax_compiler_version.m4 b/m4/m4_ax_compiler_version.m4 new file mode 100644 index 000000000..0581d1bc0 --- /dev/null +++ b/m4/m4_ax_compiler_version.m4 @@ -0,0 +1,529 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_compiler_version.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_COMPILER_VERSION +# +# DESCRIPTION +# +# This macro retrieves the compiler version and returns it in the cache +# variable $ax_cv_c_compiler_version for C and $ax_cv_cxx_compiler_version +# for C++. +# +# Version is returned as epoch:major.minor.patchversion +# +# Epoch is used in order to have an increasing version number in case of +# marketing change. +# +# Epoch use: * borland compiler use chronologically 0turboc for turboc +# era, +# +# 1borlanc BORLANDC++ before 5, 2cppbuilder for cppbuilder era, +# 3borlancpp for return of BORLANDC++ (after version 5.5), +# 4cppbuilder for cppbuilder with year version, +# and 5xe for XE era. +# +# An empty string is returned otherwise. +# +# LICENSE +# +# Copyright (c) 2014 Bastien ROUCARIES +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 12 + +# for intel +AC_DEFUN([_AX_COMPILER_VERSION_INTEL], + [ dnl + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + [__INTEL_COMPILER/100],, + AC_MSG_FAILURE([[[$0]] unknown intel compiler version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + [(__INTEL_COMPILER%100)/10],, + AC_MSG_FAILURE([[[$0]] unknown intel compiler version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + [(__INTEL_COMPILER%10)],, + AC_MSG_FAILURE([[[$0]] unknown intel compiler version])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) + +# for IBM +AC_DEFUN([_AX_COMPILER_VERSION_IBM], + [ dnl + dnl check between z/OS C/C++ and XL C/C++ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([], + [ + #if defined(__COMPILER_VER__) + choke me; + #endif + ])], + [ + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + [__xlC__/100],, + AC_MSG_FAILURE([[[$0]] unknown IBM compiler major version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + [__xlC__%100],, + AC_MSG_FAILURE([[[$0]] unknown IBM compiler minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + [__xlC_ver__/0x100],, + AC_MSG_FAILURE([[[$0]] unknown IBM compiler patch version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_build, + [__xlC_ver__%0x100],, + AC_MSG_FAILURE([[[$0]] unknown IBM compiler build version])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_build" + ], + [ + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + [__xlC__%1000],, + AC_MSG_FAILURE([[[$0]] unknown IBM compiler patch version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + [(__xlC__/10000)%10],, + AC_MSG_FAILURE([[[$0]] unknown IBM compiler minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + [(__xlC__/100000)%10],, + AC_MSG_FAILURE([[[$0]] unknown IBM compiler major version])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) +]) + +# for pathscale +AC_DEFUN([_AX_COMPILER_VERSION_PATHSCALE],[ + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + __PATHCC__,, + AC_MSG_FAILURE([[[$0]] unknown pathscale major])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + __PATHCC_MINOR__,, + AC_MSG_FAILURE([[[$0]] unknown pathscale minor])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + [__PATHCC_PATCHLEVEL__],, + AC_MSG_FAILURE([[[$0]] unknown pathscale patch level])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) + +# for clang +AC_DEFUN([_AX_COMPILER_VERSION_CLANG],[ + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + __clang_major__,, + AC_MSG_FAILURE([[[$0]] unknown clang major])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + __clang_minor__,, + AC_MSG_FAILURE([[[$0]] unknown clang minor])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + [__clang_patchlevel__],,0) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) + +# for crayc +AC_DEFUN([_AX_COMPILER_VERSION_CRAY],[ + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + _RELEASE,, + AC_MSG_FAILURE([[[$0]] unknown crayc release])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + _RELEASE_MINOR,, + AC_MSG_FAILURE([[[$0]] unknown crayc minor])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor" + ]) + +# for fujitsu +AC_DEFUN([_AX_COMPILER_VERSION_FUJITSU],[ + AC_COMPUTE_INT(ax_cv_[]_AC_LANG_ABBREV[]_compiler_version, + __FCC_VERSION,, + AC_MSG_FAILURE([[[$0]]unknown fujitsu release])) + ]) + +# for GNU +AC_DEFUN([_AX_COMPILER_VERSION_GNU],[ + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + __GNUC__,, + AC_MSG_FAILURE([[[$0]] unknown gcc major])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + __GNUC_MINOR__,, + AC_MSG_FAILURE([[[$0]] unknown gcc minor])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + [__GNUC_PATCHLEVEL__],, + AC_MSG_FAILURE([[[$0]] unknown gcc patch level])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) + +# For sun +AC_DEFUN([_AX_COMPILER_VERSION_SUN],[ + m4_define([_AX_COMPILER_VERSION_SUN_NUMBER], + [ + #if defined(__SUNPRO_CC) + __SUNPRO_CC + #else + __SUNPRO_C + #endif + ]) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_until59, + !!(_AX_COMPILER_VERSION_SUN_NUMBER < 0x1000),, + AC_MSG_FAILURE([[[$0]] unknown sun release version])) + AS_IF([test "X$_ax_[]_AC_LANG_ABBREV[]_compiler_version_until59" = X1], + [dnl + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + _AX_COMPILER_VERSION_SUN_NUMBER % 0x10,, + AC_MSG_FAILURE([[[$0]] unknown sun patch version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + (_AX_COMPILER_VERSION_SUN_NUMBER / 0x10) % 0x10,, + AC_MSG_FAILURE([[[$0]] unknown sun minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + (_AX_COMPILER_VERSION_SUN_NUMBER / 0x100),, + AC_MSG_FAILURE([[[$0]] unknown sun major version])) + ], + [dnl + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + _AX_COMPILER_VERSION_SUN_NUMBER % 0x10,, + AC_MSG_FAILURE([[[$0]] unknown sun patch version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + (_AX_COMPILER_VERSION_SUN_NUMBER / 0x100) % 0x100,, + AC_MSG_FAILURE([[[$0]] unknown sun minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + (_AX_COMPILER_VERSION_SUN_NUMBER / 0x1000),, + AC_MSG_FAILURE([[[$0]] unknown sun major version])) + ]) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" +]) + +AC_DEFUN([_AX_COMPILER_VERSION_HP],[ + m4_define([_AX_COMPILER_VERSION_HP_NUMBER], + [ + #if defined(__HP_cc) + __HP_cc + #else + __HP_aCC + #endif + ]) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_untilA0121, + !!(_AX_COMPILER_VERSION_HP_NUMBER <= 1),, + AC_MSG_FAILURE([[[$0]] unknown hp release version])) + AS_IF([test "X$_ax_[]_AC_LANG_ABBREV[]_compiler_version_untilA0121" = X1], + [dnl By default output last version with this behavior. + dnl it is so old + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="01.21.00" + ], + [dnl + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + (_AX_COMPILER_VERSION_HP_NUMBER % 100),, + AC_MSG_FAILURE([[[$0]] unknown hp release version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + ((_AX_COMPILER_VERSION_HP_NUMBER / 100)%100),, + AC_MSG_FAILURE([[[$0]] unknown hp minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + ((_AX_COMPILER_VERSION_HP_NUMBER / 10000)%100),, + AC_MSG_FAILURE([[[$0]] unknown hp major version])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) +]) + +AC_DEFUN([_AX_COMPILER_VERSION_DEC],[dnl + m4_define([_AX_COMPILER_VERSION_DEC_NUMBER], + [ + #if defined(__DECC_VER) + __DECC_VER + #else + __DECCXX_VER + #endif + ]) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + (_AX_COMPILER_VERSION_DEC_NUMBER % 10000),, + AC_MSG_FAILURE([[[$0]] unknown dec release version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + ((_AX_COMPILER_VERSION_DEC_NUMBER / 100000UL)%100),, + AC_MSG_FAILURE([[[$0]] unknown dec minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + ((_AX_COMPILER_VERSION_DEC_NUMBER / 10000000UL)%100),, + AC_MSG_FAILURE([[[$0]] unknown dec major version])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) + +# borland +AC_DEFUN([_AX_COMPILER_VERSION_BORLAND],[dnl + m4_define([_AX_COMPILER_VERSION_TURBOC_NUMBER], + [ + #if defined(__TURBOC__) + __TURBOC__ + #else + choke me + #endif + ]) + m4_define([_AX_COMPILER_VERSION_BORLANDC_NUMBER], + [ + #if defined(__BORLANDC__) + __BORLANDC__ + #else + __CODEGEARC__ + #endif + ]) + AC_COMPILE_IFELSE( + [AC_LANG_PROGRAM(, + _AX_COMPILER_VERSION_TURBOC_NUMBER)], + [dnl TURBOC + AC_COMPUTE_INT( + _ax_[]_AC_LANG_ABBREV[]_compiler_version_turboc_raw, + _AX_COMPILER_VERSION_TURBOC_NUMBER,, + AC_MSG_FAILURE([[[$0]] unknown turboc version])) + AS_IF( + [test $_ax_[]_AC_LANG_ABBREV[]_compiler_version_turboc_raw -lt 661 || test $_ax_[]_AC_LANG_ABBREV[]_compiler_version_turboc_raw -gt 1023], + [dnl compute normal version + AC_COMPUTE_INT( + _ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + _AX_COMPILER_VERSION_TURBOC_NUMBER % 0x100,, + AC_MSG_FAILURE([[[$0]] unknown turboc minor version])) + AC_COMPUTE_INT( + _ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + (_AX_COMPILER_VERSION_TURBOC_NUMBER/0x100)%0x100,, + AC_MSG_FAILURE([[[$0]] unknown turboc major version])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="0turboc:$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor"], + [dnl special version + AS_CASE([$_ax_[]_AC_LANG_ABBREV[]_compiler_version_turboc_raw], + [661],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="0turboc:1.00"], + [662],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="0turboc:1.01"], + [663],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="0turboc:2.00"], + [ + AC_MSG_WARN([[[$0]] unknown turboc version between 0x295 and 0x400 please report bug]) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="" + ]) + ]) + ], + # borlandc + [ + AC_COMPUTE_INT( + _ax_[]_AC_LANG_ABBREV[]_compiler_version_borlandc_raw, + _AX_COMPILER_VERSION_BORLANDC_NUMBER,, + AC_MSG_FAILURE([[[$0]] unknown borlandc version])) + AS_CASE([$_ax_[]_AC_LANG_ABBREV[]_compiler_version_borlandc_raw], + dnl BORLANDC++ before 5.5 + [512] ,[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="1borlanc:2.00"], + [1024],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="1borlanc:3.00"], + [1024],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="1borlanc:3.00"], + [1040],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="1borlanc:3.1"], + [1106],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="1borlanc:4.0"], + [1280],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="1borlanc:5.0"], + [1312],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="1borlanc:5.02"], + dnl C++ Builder era + [1328],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="2cppbuilder:3.0"], + [1344],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="2cppbuilder:4.0"], + dnl BORLANDC++ after 5.5 + [1360],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="3borlancpp:5.5"], + [1361],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="3borlancpp:5.51"], + [1378],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="3borlancpp:5.6.4"], + dnl C++ Builder with year number + [1392],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="4cppbuilder:2006"], + [1424],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="4cppbuilder:2007"], + [1555],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="4cppbuilder:2009"], + [1569],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="4cppbuilder:2010"], + dnl XE version + [1584],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="5xe"], + [1600],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="5xe:2"], + [1616],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="5xe:3"], + [1632],[ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="5xe:4"], + [ + AC_MSG_WARN([[[$0]] Unknown borlandc compiler version $_ax_[]_AC_LANG_ABBREV[]_compiler_version_borlandc_raw please report bug]) + ]) + ]) + ]) + +# COMO +AC_DEFUN([_AX_COMPILER_VERSION_COMEAU], + [ dnl + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + [__COMO_VERSION__%100],, + AC_MSG_FAILURE([[[$0]] unknown comeau compiler minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + [(__COMO_VERSION__/100)%10],, + AC_MSG_FAILURE([[[$0]] unknown comeau compiler major version])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor" + ]) + +# KAI +AC_DEFUN([_AX_COMPILER_VERSION_KAI],[ + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + [__KCC_VERSION%100],, + AC_MSG_FAILURE([[[$0]] unknown kay compiler patch version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + [(__KCC_VERSION/100)%10],, + AC_MSG_FAILURE([[[$0]] unknown kay compiler minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + [(__KCC_VERSION/1000)%10],, + AC_MSG_FAILURE([[[$0]] unknown kay compiler major version])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) + +dnl LCC +dnl LCC does not output version... + +# SGI +AC_DEFUN([_AX_COMPILER_VERSION_SGI],[ + m4_define([_AX_COMPILER_VERSION_SGI_NUMBER], + [ + #if defined(_COMPILER_VERSION) + _COMPILER_VERSION + #else + _SGI_COMPILER_VERSION + #endif + ]) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + [_AX_COMPILER_VERSION_SGI_NUMBER%10],, + AC_MSG_FAILURE([[[$0]] unknown SGI compiler patch version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + [(_AX_COMPILER_VERSION_SGI_NUMBER/10)%10],, + AC_MSG_FAILURE([[[$0]] unknown SGI compiler minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + [(_AX_COMPILER_VERSION_SGI_NUMBER/100)%10],, + AC_MSG_FAILURE([[[$0]] unknown SGI compiler major version])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) + +# microsoft +AC_DEFUN([_AX_COMPILER_VERSION_MICROSOFT],[ + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + _MSC_VER%100,, + AC_MSG_FAILURE([[[$0]] unknown microsoft compiler minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + (_MSC_VER/100)%100,, + AC_MSG_FAILURE([[[$0]] unknown microsoft compiler major version])) + dnl could be overridden + _ax_[]_AC_LANG_ABBREV[]_compiler_version_patch=0 + _ax_[]_AC_LANG_ABBREV[]_compiler_version_build=0 + # special case for version 6 + AS_IF([test "X$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major" = "X12"], + [AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + _MSC_FULL_VER%1000,, + _ax_[]_AC_LANG_ABBREV[]_compiler_version_patch=0)]) + # for version 7 + AS_IF([test "X$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major" = "X13"], + [AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + _MSC_FULL_VER%1000,, + AC_MSG_FAILURE([[[$0]] unknown microsoft compiler patch version])) + ]) + # for version > 8 + AS_IF([test $_ax_[]_AC_LANG_ABBREV[]_compiler_version_major -ge 14], + [AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + _MSC_FULL_VER%10000,, + AC_MSG_FAILURE([[[$0]] unknown microsoft compiler patch version])) + ]) + AS_IF([test $_ax_[]_AC_LANG_ABBREV[]_compiler_version_major -ge 15], + [AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_build, + _MSC_BUILD,, + AC_MSG_FAILURE([[[$0]] unknown microsoft compiler build version])) + ]) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_build" + ]) + +# for metrowerks +AC_DEFUN([_AX_COMPILER_VERSION_METROWERKS],[dnl + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + __MWERKS__%0x100,, + AC_MSG_FAILURE([[[$0]] unknown metrowerks compiler patch version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + (__MWERKS__/0x100)%0x10,, + AC_MSG_FAILURE([[[$0]] unknown metrowerks compiler minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + (__MWERKS__/0x1000)%0x10,, + AC_MSG_FAILURE([[[$0]] unknown metrowerks compiler major version])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) + +# for watcom +AC_DEFUN([_AX_COMPILER_VERSION_WATCOM],[dnl + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + __WATCOMC__%100,, + AC_MSG_FAILURE([[[$0]] unknown watcom compiler minor version])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + (__WATCOMC__/100)%100,, + AC_MSG_FAILURE([[[$0]] unknown watcom compiler major version])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor" + ]) + +# for PGI +AC_DEFUN([_AX_COMPILER_VERSION_PORTLAND],[ + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + __PGIC__,, + AC_MSG_FAILURE([[[$0]] unknown pgi major])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + __PGIC_MINOR__,, + AC_MSG_FAILURE([[[$0]] unknown pgi minor])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + [__PGIC_PATCHLEVEL__],, + AC_MSG_FAILURE([[[$0]] unknown pgi patch level])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) + +# tcc +AC_DEFUN([_AX_COMPILER_VERSION_TCC],[ + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version=[`tcc -v | $SED 's/^[ ]*tcc[ ]\+version[ ]\+\([0-9.]\+\).*/\1/g'`] + ]) + +# for GNU +AC_DEFUN([_AX_COMPILER_VERSION_SDCC],[ + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_major, + /* avoid parse error with comments */ + #if(defined(__SDCC_VERSION_MAJOR)) + __SDCC_VERSION_MAJOR + #else + SDCC/100 + #endif + ,, + AC_MSG_FAILURE([[[$0]] unknown sdcc major])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor, + /* avoid parse error with comments */ + #if(defined(__SDCC_VERSION_MINOR)) + __SDCC_VERSION_MINOR + #else + (SDCC%100)/10 + #endif + ,, + AC_MSG_FAILURE([[[$0]] unknown sdcc minor])) + AC_COMPUTE_INT(_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch, + [ + /* avoid parse error with comments */ + #if(defined(__SDCC_VERSION_PATCH)) + __SDCC_VERSION_PATCH + #elsif(defined(_SDCC_VERSION_PATCHLEVEL)) + __SDCC_VERSION_PATCHLEVEL + #else + SDCC%10 + #endif + ],, + AC_MSG_FAILURE([[[$0]] unknown sdcc patch level])) + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version="$_ax_[]_AC_LANG_ABBREV[]_compiler_version_major.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_minor.$_ax_[]_AC_LANG_ABBREV[]_compiler_version_patch" + ]) + +# main entry point +AC_DEFUN([AX_COMPILER_VERSION],[dnl + AC_REQUIRE([AX_COMPILER_VENDOR]) + AC_REQUIRE([AC_PROG_SED]) + AC_CACHE_CHECK([for _AC_LANG compiler version], + ax_cv_[]_AC_LANG_ABBREV[]_compiler_version, + [ dnl + AS_CASE([$ax_cv_[]_AC_LANG_ABBREV[]_compiler_vendor], + [intel],[_AX_COMPILER_VERSION_INTEL], + [ibm],[_AX_COMPILER_VERSION_IBM], + [pathscale],[_AX_COMPILER_VERSION_PATHSCALE], + [clang],[_AX_COMPILER_VERSION_CLANG], + [cray],[_AX_COMPILER_VERSION_CRAY], + [fujitsu],[_AX_COMPILER_VERSION_FUJITSU], + [gnu],[_AX_COMPILER_VERSION_GNU], + [sun],[_AX_COMPILER_VERSION_SUN], + [hp],[_AX_COMPILER_VERSION_HP], + [dec],[_AX_COMPILER_VERSION_DEC], + [borland],[_AX_COMPILER_VERSION_BORLAND], + [comeau],[_AX_COMPILER_VERSION_COMEAU], + [kai],[_AX_COMPILER_VERSION_KAI], + [sgi],[_AX_COMPILER_VERSION_SGI], + [microsoft],[_AX_COMPILER_VERSION_MICROSOFT], + [metrowerks],[_AX_COMPILER_VERSION_METROWERKS], + [watcom],[_AX_COMPILER_VERSION_WATCOM], + [portland],[_AX_COMPILER_VERSION_PORTLAND], + [tcc],[_AX_COMPILER_VERSION_TCC], + [sdcc],[_AX_COMPILER_VERSION_SDCC], + [ax_cv_[]_AC_LANG_ABBREV[]_compiler_version=""]) + ]) +]) diff --git a/makeAndRun.bat b/makeAndRun.bat deleted file mode 100644 index 534ede1ea..000000000 --- a/makeAndRun.bat +++ /dev/null @@ -1,16 +0,0 @@ -rem **** -rem * for this command line build to work independent of where it was created -rem * -rem * Generate Project/Export Makefiles -rem * -rem * then do these edits to the generated files -rem * CppUTest.dep - change the relitive path to ....\program files to \program files -rem * AllTests.mak - At the end of the makefile where the depended upon CppUTest is made -rem* Change cd "\absolute\path\CppUTest" to cd .. -PATH=C:\Program Files\Microsoft Visual Studio\VC98\Bin;%PATH% -rem nmake /f CppUTest.mak CFG="CppUTest - Win32 Debug" all -cd tests -nmake /f AllTests.mak all -cd Debug -AllTests -v -cd ..\.. diff --git a/makeVc6.bat b/makeVc6.bat deleted file mode 100644 index d60d91830..000000000 --- a/makeVc6.bat +++ /dev/null @@ -1,16 +0,0 @@ -rem **** -rem * Command line build - For CppUTest - Run from dsw directory -rem * -rem * A single parameter is supported and it is the last parameter of msdev -rem * for example: -rem * /clean -rem * make sure to use the slash -rem * this needs to be in your path -rem ****PATH=C:\Program Files\Microsoft Visual Studio\VC98\Bin;%PATH% - -msdev CppUTest.dsp /MAKE "CppUTest - Debug" %1 -msdev tests\AllTests.dsp /MAKE "AllTests - Debug" %1 -if "%1" EQU "/clean" goto end -if "%1" EQU "/CLEAN" goto end -tests\Debug\AllTests -:end diff --git a/platforms/CCStudio/CppUTest.pjt b/platforms/CCStudio/CppUTest.pjt index 60a338dd8..3186c6109 100644 --- a/platforms/CCStudio/CppUTest.pjt +++ b/platforms/CCStudio/CppUTest.pjt @@ -30,6 +30,7 @@ Source="..\..\src\CppUTest\TestResult.cpp" Source="..\..\src\CppUTest\TestTestingFixture.cpp" Source="..\..\src\CppUTest\Utest.cpp" Source="..\..\src\CppUTestExt\CodeMemoryReportFormatter.cpp" +Source="..\..\src\CppUTestExt\GTest.cpp" Source="..\..\src\CppUTestExt\MemoryReportAllocator.cpp" Source="..\..\src\CppUTestExt\MemoryReporterPlugin.cpp" Source="..\..\src\CppUTestExt\MemoryReportFormatter.cpp" diff --git a/platforms/CCStudio/CppUTestExtRunAllTests1.pjt b/platforms/CCStudio/CppUTestExtRunAllTests1.pjt index d48d4aaec..2afdd31e3 100644 --- a/platforms/CCStudio/CppUTestExtRunAllTests1.pjt +++ b/platforms/CCStudio/CppUTestExtRunAllTests1.pjt @@ -18,6 +18,7 @@ Source="..\..\src\CppUTest\MemoryLeakDetector.cpp" Source="..\..\src\CppUTest\MemoryLeakWarningPlugin.cpp" Source="..\..\src\CppUTest\SimpleMutex.cpp" Source="..\..\src\CppUTest\SimpleString.cpp" +Source="..\..\src\CppUTest\SimpleStringInternalCache.cpp" Source="..\..\src\CppUTest\TeamCityTestOutput.cpp" Source="..\..\src\CppUTest\TestFailure.cpp" Source="..\..\src\CppUTest\TestFilter.cpp" @@ -30,6 +31,7 @@ Source="..\..\src\CppUTest\TestResult.cpp" Source="..\..\src\CppUTest\TestTestingFixture.cpp" Source="..\..\src\CppUTest\Utest.cpp" Source="..\..\src\CppUTestExt\CodeMemoryReportFormatter.cpp" +Source="..\..\src\CppUTestExt\GTest.cpp" Source="..\..\src\CppUTestExt\MemoryReportAllocator.cpp" Source="..\..\src\CppUTestExt\MemoryReporterPlugin.cpp" Source="..\..\src\CppUTestExt\MemoryReportFormatter.cpp" diff --git a/platforms/CCStudio/CppUTestExtRunAllTests2.pjt b/platforms/CCStudio/CppUTestExtRunAllTests2.pjt index 3a16a39b3..b9a40b195 100644 --- a/platforms/CCStudio/CppUTestExtRunAllTests2.pjt +++ b/platforms/CCStudio/CppUTestExtRunAllTests2.pjt @@ -18,6 +18,7 @@ Source="..\..\src\CppUTest\MemoryLeakDetector.cpp" Source="..\..\src\CppUTest\MemoryLeakWarningPlugin.cpp" Source="..\..\src\CppUTest\SimpleMutex.cpp" Source="..\..\src\CppUTest\SimpleString.cpp" +Source="..\..\src\CppUTest\SimpleStringInternalCache.cpp" Source="..\..\src\CppUTest\TeamCityTestOutput.cpp" Source="..\..\src\CppUTest\TestFailure.cpp" Source="..\..\src\CppUTest\TestFilter.cpp" @@ -30,6 +31,7 @@ Source="..\..\src\CppUTest\TestResult.cpp" Source="..\..\src\CppUTest\TestTestingFixture.cpp" Source="..\..\src\CppUTest\Utest.cpp" Source="..\..\src\CppUTestExt\CodeMemoryReportFormatter.cpp" +Source="..\..\src\CppUTestExt\GTest.cpp" Source="..\..\src\CppUTestExt\MemoryReportAllocator.cpp" Source="..\..\src\CppUTestExt\MemoryReporterPlugin.cpp" Source="..\..\src\CppUTestExt\MemoryReportFormatter.cpp" @@ -52,6 +54,7 @@ Source="..\..\tests\CppUTestExt\MockParameterTest.cpp" Source="..\..\tests\CppUTestExt\MockSupport_cTest.cpp" Source="..\..\tests\CppUTestExt\MockSupport_cTestCFile.c" Source="..\..\tests\CppUTestExt\OrderedTestTest.cpp" +Source="..\..\tests\CppUTestExt\OrderedTestTest_c.c" Source="C:\CCStudio_v3.3\C2000\cgtools\lib\src\farmem_cpp.cpp" Source="tests\CppUTestExt\AllTestsForTarget.cpp" Source="sim28335.cmd" diff --git a/platforms/CCStudio/CppUTestRunAllTests1.pjt b/platforms/CCStudio/CppUTestRunAllTests1.pjt index bd08bc024..9625021ee 100644 --- a/platforms/CCStudio/CppUTestRunAllTests1.pjt +++ b/platforms/CCStudio/CppUTestRunAllTests1.pjt @@ -18,6 +18,7 @@ Source="..\..\src\CppUTest\MemoryLeakDetector.cpp" Source="..\..\src\CppUTest\MemoryLeakWarningPlugin.cpp" Source="..\..\src\CppUTest\SimpleMutex.cpp" Source="..\..\src\CppUTest\SimpleString.cpp" +Source="..\..\src\CppUTest\SimpleStringInternalCache.cpp" Source="..\..\src\CppUTest\TeamCityTestOutput.cpp" Source="..\..\src\CppUTest\TestFailure.cpp" Source="..\..\src\CppUTest\TestFilter.cpp" @@ -35,6 +36,7 @@ Source="..\..\tests\AllocationInCppFile.cpp" Source="..\..\tests\AllocLetTestFree.c" Source="..\..\tests\AllocLetTestFreeTest.cpp" Source="..\..\tests\CheatSheetTest.cpp" +Source="..\..\tests\CompatabilityTests.cpp" Source="..\..\tests\CommandLineArgumentsTest.cpp" Source="..\..\tests\CommandLineTestRunnerTest.cpp" Source="..\..\tests\JUnitOutputTest.cpp" diff --git a/platforms/CCStudio/CppUTestRunAllTests2.pjt b/platforms/CCStudio/CppUTestRunAllTests2.pjt index 279afff4c..256969796 100644 --- a/platforms/CCStudio/CppUTestRunAllTests2.pjt +++ b/platforms/CCStudio/CppUTestRunAllTests2.pjt @@ -18,6 +18,7 @@ Source="..\..\src\CppUTest\MemoryLeakDetector.cpp" Source="..\..\src\CppUTest\MemoryLeakWarningPlugin.cpp" Source="..\..\src\CppUTest\SimpleMutex.cpp" Source="..\..\src\CppUTest\SimpleString.cpp" +Source="..\..\src\CppUTest\SimpleStringInternalCache.cpp" Source="..\..\src\CppUTest\TeamCityTestOutput.cpp" Source="..\..\src\CppUTest\TestFailure.cpp" Source="..\..\src\CppUTest\TestFilter.cpp" @@ -31,7 +32,7 @@ Source="..\..\src\CppUTest\TestTestingFixture.cpp" Source="..\..\src\CppUTest\Utest.cpp" Source="..\..\src\CppUTestExt\MockSupportPlugin.cpp" Source="..\..\src\Platforms\C2000\UtestPlatform.cpp" -Source="..\..\tests\SimpleStringTest.cpp" +Source="..\..\tests\SimpleStringCacheTest.cpp" Source="..\..\tests\TestFilterTest.cpp" Source="..\..\tests\TestHarness_cTest.cpp" Source="..\..\tests\TestHarness_cTestCFile.c" diff --git a/platforms/CCStudio/tests/CppUTest/AllTestsForTarget.cpp b/platforms/CCStudio/tests/CppUTest/AllTestsForTarget.cpp index 47cda0edc..1c977dbde 100644 --- a/platforms/CCStudio/tests/CppUTest/AllTestsForTarget.cpp +++ b/platforms/CCStudio/tests/CppUTest/AllTestsForTarget.cpp @@ -14,7 +14,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/platforms/CCStudio/tests/CppUTestExt/AllTestsForTarget.cpp b/platforms/CCStudio/tests/CppUTestExt/AllTestsForTarget.cpp index 4d7ec09df..d55800a2d 100644 --- a/platforms/CCStudio/tests/CppUTestExt/AllTestsForTarget.cpp +++ b/platforms/CCStudio/tests/CppUTestExt/AllTestsForTarget.cpp @@ -14,7 +14,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/platforms/Dos/Makefile b/platforms/Dos/Makefile index 4b1150b09..7b19cafa4 100644 --- a/platforms/Dos/Makefile +++ b/platforms/Dos/Makefile @@ -9,33 +9,44 @@ comma := , path_separator := / drive = $(subst $(CYGDRIVE),$(lastword $(subst /, ,$(CYGDRIVE))):/,$(1)) convert_paths = $(if $(CYGDRIVE),$(subst /,$(path_separator),$(call drive,$(1))),$(1)) +export CPPUTEST_HOME ?= . --include ../platforms/Dos/platform.mk -include ../platforms/Dos/sources.mk +-include $(CPPUTEST_HOME)/platforms/Dos/platform.mk +include $(CPPUTEST_HOME)/platforms/Dos/sources.mk -# Disable W013 unreachable code - it overreacts to CHECK_EQUAL macros -# Disable W367 conditional expression in if statement is always true - same -# Disable W368 conditional expression in if statement is always false - same -# Disable W391 assignment found in boolean expression - we don't care - -CFLAGS := \ - -q -c -os -oc -d0 -we -w=3 -wcd=13 -wcd=367 -wcd=368 -wcd391 -wcd=472 -ml -zm \ +COMMONFLAGS := \ + -q -c -os -oc -d0 -we -w=3 -ml -zm \ -dCPPUTEST_MEM_LEAK_DETECTION_DISABLED=1 -dCPPUTEST_STD_CPP_LIB_DISABLED=1 \ -i$(call convert_paths,$(CPPUTEST_HOME)/include) \ - -i$(call convert_paths,$(CPPUTEST_HOME)/include/Platforms/Dos) \ -i$(call convert_paths,$(WATCOM)/h) -i$(call convert_paths,$(WATCOM)/h/nt) \ -CXXFLAGS := $(CFLAGS) -xds +# Disable W303 unreferenced parameter - PUNUSED is GNU-specific +CFLAGS := \ + $(COMMONFLAGS) \ + -wcd=303 + +# Disable W013 unreachable code - it overreacts to CHECK_EQUAL macros +# Disable W367 conditional expression in if statement is always true - same +# Disable W368 conditional expression in if statement is always false - same +# Disable W391 assignment found in boolean expression - we don't care +CXXFLAGS := \ + $(COMMONFLAGS) \ + -wcd=13 \ + -wcd=367 \ + -wcd=368 \ + -wcd=391 \ + -xds .PHONY: all clean -all: CPPU.LIB CPPUX.LIB CPPU1.EXE CPPU2.EXE CPPU3.EXE CPPU4.EXE \ - CPPU5.EXE CPPU6.EXE CPPU7.EXE +all: CPPU.LIB CPPUX.LIB \ + CPPU1.EXE CPPU2.EXE CPPU3.EXE CPPU4.EXE CPPU5.EXE CPPU6.EXE CPPU7.EXE CPPU8.EXE \ + CPPUX1.EXE CPPUX2.EXE CPPUX3.EXE CPPUX4.EXE CPPUX5.EXE CPPUX6.EXE CPPUX7.EXE CPPUX8.EXE CPPUX9.EXE clean: rm -rf ../src/CppUTest/*.o ../src/CppUTestExt/*.o \ ../src/Platforms/dos/*.o ../tests/*.o ../tests/CppUTestExt/*.o \ - *.o *.map *.txt *.LOG *.EXE *.err *.LIB *.LST + *.o *.map *.LOG *.EXE *.err *.LIB *.LST %.o: %.cpp $(CXX) $(CXXFLAGS) -fo=$(call convert_paths,$@) $(call convert_paths,$<) @@ -51,3 +62,7 @@ clean: %.EXE: $$($$*_OBJECTS) | CPPU.LIB CPPUX.LIB $(LINK) opt q,map,st=50k sys dos lib CPPU.LIB,CPPUX.LIB \ file $(subst $(space),$(comma),$(call convert_paths,$?)) name $@ + +.PHONY: +test: + $(CPPUTEST_HOME)/platforms/Dos/alltests.sh diff --git a/platforms/Dos/alltests.sh b/platforms/Dos/alltests.sh index 6bfa8fd30..9c54b3e0b 100755 --- a/platforms/Dos/alltests.sh +++ b/platforms/Dos/alltests.sh @@ -1,13 +1,29 @@ #!/bin/bash + +: "${CPPUTEST_HOME:=.}" + +checkForCppUTestToolsEnvVariable() { + if [ -z "$CPPUTEST_HOME" ] ; then + echo "CPPUTEST_HOME not set. You must set CPPUTEST_HOME to the top level CppUTest directory" + exit 1 + fi + if [ ! -d "$CPPUTEST_HOME" ] ; then + echo "CPPUTEST_HOME not set to a directory. You must set CPPUTEST_HOME to the top level CppUTest directory" + exit 2 + fi +} + +checkForCppUTestToolsEnvVariable + printf "" > exit # so dosbox will run 'external' command 'exit' correctly printf "" >ALLTESTS.LOG for test in `ls *.EXE`; do kb=`ls -lsk ${test} | awk '{print $1}'` printf "Running ${test} (${kb}k) inside DOSBox...\n" - dosbox -conf ../platforms/Dos/dosbox-0.74.conf exit \ + dosbox -conf $CPPUTEST_HOME/platforms/Dos/dosbox-0.74.conf exit \ -c "echo *** ${test} (${kb}k) *****************************>>ALLTESTS.LOG" \ -c "${test}>>ALLTESTS.LOG" \ - -noconsole -exit || exit 1 + -noconsole -exit 1>console_output 2>dosbox_error.log || { printf "error running command!\n"; cat dosbox_error.log; exit 1; } done printf "\n" [ "`cat ALLTESTS.LOG`" ] || { printf "No tests to run!\n"; exit 1; } diff --git a/platforms/Dos/sources.mk b/platforms/Dos/sources.mk index 0c44762e0..7515febe6 100644 --- a/platforms/Dos/sources.mk +++ b/platforms/Dos/sources.mk @@ -7,7 +7,7 @@ CPPU_OBJECTS := \ $(CPPUTEST_HOME)/src/CppUTest/MemoryLeakWarningPlugin.o \ $(CPPUTEST_HOME)/src/CppUTest/SimpleMutex.o \ $(CPPUTEST_HOME)/src/CppUTest/SimpleString.o \ - $(CPPUTEST_HOME)/src/CppUTest/TeamCityTestOutput.o \ + $(CPPUTEST_HOME)/src/CppUTest/SimpleStringInternalCache.o \ $(CPPUTEST_HOME)/src/CppUTest/TestFailure.o \ $(CPPUTEST_HOME)/src/CppUTest/TestFilter.o \ $(CPPUTEST_HOME)/src/CppUTest/TestHarness_c.o \ @@ -18,7 +18,7 @@ CPPU_OBJECTS := \ $(CPPUTEST_HOME)/src/CppUTest/TestTestingFixture.o \ $(CPPUTEST_HOME)/src/CppUTest/TestResult.o \ $(CPPUTEST_HOME)/src/CppUTest/Utest.o \ - $(CPPUTEST_HOME)/src/Platforms/Dos/UtestPlatform.o \ + $(CPPUTEST_HOME)/src/Platforms/Dos/UtestPlatform.o CPPUX_OBJECTS := \ $(CPPUTEST_HOME)/src/CppUTestExt/CodeMemoryReportFormatter.o \ @@ -34,55 +34,78 @@ CPPUX_OBJECTS := \ $(CPPUTEST_HOME)/src/CppUTestExt/OrderedTest.o \ $(CPPUTEST_HOME)/src/CppUTestExt/MemoryReportFormatter.o \ $(CPPUTEST_HOME)/src/CppUTestExt/MockExpectedCallsList.o \ - $(CPPUTEST_HOME)/src/CppUTestExt/MockSupport.o \ + $(CPPUTEST_HOME)/src/CppUTestExt/MockSupport.o CPPU1_OBJECTS := \ - $(CPPUTEST_HOME)/tests/AllTests.o \ - $(CPPUTEST_HOME)/tests/AllocLetTestFree.o \ - $(CPPUTEST_HOME)/tests/AllocLetTestFreeTest.o \ - $(CPPUTEST_HOME)/tests/CheatSheetTest.o \ - $(CPPUTEST_HOME)/tests/CommandLineArgumentsTest.o \ - $(CPPUTEST_HOME)/tests/CommandLineTestRunnerTest.o \ - $(CPPUTEST_HOME)/tests/JUnitOutputTest.o \ - $(CPPUTEST_HOME)/tests/MemoryLeakWarningTest.o \ - $(CPPUTEST_HOME)/tests/PluginTest.o \ - $(CPPUTEST_HOME)/tests/PreprocessorTest.o \ - $(CPPUTEST_HOME)/tests/SetPluginTest.o \ - $(CPPUTEST_HOME)/tests/SimpleMutexTest.o \ - $(CPPUTEST_HOME)/tests/TeamCityOutputTest.o \ - $(CPPUTEST_HOME)/tests/TestFailureNaNTest.o \ - $(CPPUTEST_HOME)/tests/TestFailureTest.o \ - $(CPPUTEST_HOME)/tests/TestResultTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTest/AllocLetTestFree.o \ + $(CPPUTEST_HOME)/tests/CppUTest/AllocLetTestFreeTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/CheatSheetTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/CompatabilityTests.o \ + $(CPPUTEST_HOME)/tests/CppUTest/CommandLineArgumentsTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/CommandLineTestRunnerTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/JUnitOutputTest.o CPPU2_OBJECTS := \ - $(CPPUTEST_HOME)/tests/AllTests.o \ - $(CPPUTEST_HOME)/tests/MemoryLeakDetectorTest.o \ - $(CPPUTEST_HOME)/tests/SimpleStringTest.o \ - $(CPPUTEST_HOME)/tests/TestOutputTest.o \ - $(CPPUTEST_HOME)/tests/TestRegistryTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTest/DummyMemoryLeakDetector.o \ + $(CPPUTEST_HOME)/tests/CppUTest/MemoryLeakWarningTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/PluginTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/PreprocessorTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/SetPluginTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/SimpleMutexTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TeamCityOutputTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestFailureNaNTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestFailureTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestResultTest.o \ CPPU3_OBJECTS := \ - $(CPPUTEST_HOME)/tests/AllTests.o \ - $(CPPUTEST_HOME)/tests/AllocationInCFile.o \ - $(CPPUTEST_HOME)/tests/AllocationInCppFile.o \ - $(CPPUTEST_HOME)/tests/MemoryOperatorOverloadTest.o \ - $(CPPUTEST_HOME)/tests/TeamCityOutputTest.o \ - $(CPPUTEST_HOME)/tests/TestFilterTest.o \ - $(CPPUTEST_HOME)/tests/TestHarness_cTest.o \ - $(CPPUTEST_HOME)/tests/TestHarness_cTestCFile.o \ - $(CPPUTEST_HOME)/tests/TestInstallerTest.o \ - $(CPPUTEST_HOME)/tests/TestMemoryAllocatorTest.o \ - $(CPPUTEST_HOME)/tests/TestUTestMacro.o \ - $(CPPUTEST_HOME)/tests/UtestPlatformTest.o \ - $(CPPUTEST_HOME)/tests/UtestTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTest/MemoryLeakDetectorTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/SimpleStringTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/SimpleStringCacheTest.o CPPU4_OBJECTS := \ + $(CPPUTEST_HOME)/tests/CppUTest/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestOutputTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestRegistryTest.o \ + +CPPU5_OBJECTS := \ + $(CPPUTEST_HOME)/tests/CppUTest/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTest/AllocationInCFile.o \ + $(CPPUTEST_HOME)/tests/CppUTest/AllocationInCppFile.o \ + $(CPPUTEST_HOME)/tests/CppUTest/MemoryOperatorOverloadTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TeamCityOutputTest.o + +CPPU6_OBJECTS := \ + $(CPPUTEST_HOME)/tests/CppUTest/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestFilterTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestHarness_cTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestHarness_cTestCFile.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestInstallerTest.o + +CPPU7_OBJECTS := \ + $(CPPUTEST_HOME)/tests/CppUTest/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestMemoryAllocatorTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestUTestMacro.o + +CPPU8_OBJECTS := \ + $(CPPUTEST_HOME)/tests/CppUTest/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTest/UtestPlatformTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/UtestTest.o \ + $(CPPUTEST_HOME)/tests/CppUTest/TestUTestStringMacro.o \ + +CPPUX1_OBJECTS := \ $(CPPUTEST_HOME)/tests/CppUTestExt/AllTests.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockFailureReporterForTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/ExpectedFunctionsListTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/GMockTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/GTest1Test.o \ - $(CPPUTEST_HOME)/tests/CppUTestExt/GTest2ConvertorTest.o \ + $(CPPUTEST_HOME)/tests/CppUTestExt/GTest2ConvertorTest.o + +CPPUX2_OBJECTS := \ + $(CPPUTEST_HOME)/tests/CppUTestExt/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTestExt/MockFailureReporterForTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MemoryReportAllocatorTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MemoryReportFormatterTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MemoryReporterPluginTest.o \ @@ -90,35 +113,51 @@ CPPU4_OBJECTS := \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockCheatSheetTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockComparatorCopierTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockExpectedCallTest.o \ - $(CPPUTEST_HOME)/tests/CppUTestExt/MockHierarchyTest.o \ + $(CPPUTEST_HOME)/tests/CppUTestExt/MockHierarchyTest.o -CPPU5_OBJECTS := \ +CPPUX3_OBJECTS := \ $(CPPUTEST_HOME)/tests/CppUTestExt/AllTests.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockFailureReporterForTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/CodeMemoryReporterTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/OrderedTestTest.o \ + $(CPPUTEST_HOME)/tests/CppUTestExt/OrderedTestTest_c.o \ + +CPPUX4_OBJECTS := \ + $(CPPUTEST_HOME)/tests/CppUTestExt/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTestExt/MockFailureReporterForTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockReturnValueTest.o \ - $(CPPUTEST_HOME)/tests/CppUTestExt/MockNamedValueTest.o \ + $(CPPUTEST_HOME)/tests/CppUTestExt/MockNamedValueTest.o + +CPPUX5_OBJECTS := \ + $(CPPUTEST_HOME)/tests/CppUTestExt/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTestExt/MockFailureReporterForTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockPluginTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockSupport_cTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockSupport_cTestCFile.o \ -CPPU6_OBJECTS := \ +CPPUX6_OBJECTS := \ $(CPPUTEST_HOME)/tests/CppUTestExt/AllTests.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockFailureReporterForTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/ExpectedFunctionsListTest.o \ - $(CPPUTEST_HOME)/tests/CppUTestExt/MockCallTest.o \ + $(CPPUTEST_HOME)/tests/CppUTestExt/MockCallTest.o + +CPPUX7_OBJECTS := \ + $(CPPUTEST_HOME)/tests/CppUTestExt/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTestExt/MockFailureReporterForTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockComparatorCopierTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockHierarchyTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockParameterTest.o \ - $(CPPUTEST_HOME)/tests/TestUTestStringMacro.o \ - CPPU7_OBJECTS := \ +CPPUX8_OBJECTS := \ $(CPPUTEST_HOME)/tests/CppUTestExt/AllTests.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockFailureReporterForTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/IEEE754PluginTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/IEEE754PluginTest_c.o \ - $(CPPUTEST_HOME)/tests/CppUTestExt/MockComparatorCopierTest.o \ + $(CPPUTEST_HOME)/tests/CppUTestExt/MockComparatorCopierTest.o + +CPPUX9_OBJECTS := \ + $(CPPUTEST_HOME)/tests/CppUTestExt/AllTests.o \ + $(CPPUTEST_HOME)/tests/CppUTestExt/MockFailureReporterForTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockFailureTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockHierarchyTest.o \ $(CPPUTEST_HOME)/tests/CppUTestExt/MockPluginTest.o \ diff --git a/platforms/Eclipse-Cygwin/.project b/platforms/Eclipse-Cygwin/.project index 5a28c97d8..488e625d5 100644 --- a/platforms/Eclipse-Cygwin/.project +++ b/platforms/Eclipse-Cygwin/.project @@ -39,11 +39,6 @@ 1 PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/.travis.yml - - .travis_github_deployer.yml - 1 - PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/.travis_github_deployer.yml - AUTHORS 1 @@ -389,11 +384,6 @@ 1 PARENT-2-PROJECT_LOC/cpputest_build/Makefile - - docs/WalkThrough_VS21010.docx - 1 - PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/docs/WalkThrough_VS21010.docx - examples/.cdtproject 1 @@ -729,6 +719,11 @@ 1 PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/CheatSheetTest.cpp + + tests/CompatabilityTests.cpp + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/CompatabilityTests.cpp + tests/CommandLineArgumentsTest.cpp 1 @@ -789,6 +784,11 @@ 1 PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/SetPluginTest.cpp + + tests/SimpleStringCacheTest.cpp + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/SimpleStringCacheTest.cpp + tests/SimpleStringTest.cpp 1 @@ -1019,6 +1019,11 @@ 1 PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/include/CppUTest/SimpleString.h + + include/CppUTest/SimpleStringInternalCache.h + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/include/CppUTest/SimpleStringInternalCache.h + include/CppUTest/StandardCLibrary.h 1 @@ -1094,6 +1099,11 @@ 1 PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/include/CppUTestExt/GMock.h + + include/CppUTestExt/GTestSupport.h + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/include/CppUTestExt/GTestSupport.h + include/CppUTestExt/GTest.h 1 @@ -1504,10 +1514,15 @@ 1 PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/src/CppUTest/MemoryLeakWarningPlugin.cpp - + src/CppUTest/SimpleString.cpp 1 PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/src/CppUTest/SimpleString.cpp + + src/CppUTest/SimpleStringInternalCache.cpp + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/src/CppUTest/SimpleStringInternalCache.cpp src/CppUTest/TestFailure.cpp @@ -1564,6 +1579,11 @@ 1 PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/src/CppUTestExt/CodeMemoryReportFormatter.cpp + + src/CppUTestExt/GTest.cpp + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/src/CppUTestExt/GTest.cpp + src/CppUTestExt/MemoryReportAllocator.cpp 1 @@ -1764,6 +1784,16 @@ 1 PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/CppUTestExt/OrderedTestTest.cpp + + tests/CppUTestExt/OrderedTestTest_c.c + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/CppUTestExt/OrderedTestTest_c.c + + + tests/CppUTestExt/OrderedTestTest.h + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/CppUTestExt/OrderedTestTest.h + tests/Debug/AllTests.bsc 1 @@ -1854,6 +1884,16 @@ 1 PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/Debug/CodeMemoryReportFormatterTest.sbr + + tests/Debug/CompatabilityTests.obj + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/Debug/CompatabilityTests.obj + + + tests/Debug/CompatabilityTests.sbr + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/Debug/CompatabilityTests.sbr + tests/Debug/CommandLineArgumentsTest.obj 1 @@ -2064,6 +2104,16 @@ 1 PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/Debug/OrderedTestTest.sbr + + tests/Debug/OrderedTestTest_c.obj + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/Debug/OrderedTestTest_c.obj + + + tests/Debug/OrderedTestTest_c.sbr + 1 + PARENT-2-ECLIPSE_HOME/00_Dev/05_CppUTest/cpputest/tests/Debug/OrderedTestTest_c.sbr + tests/Debug/PluginTest.obj 1 diff --git a/platforms/Eclipse-Cygwin/README.md b/platforms/Eclipse-Cygwin/README.md index fc007194c..503b21eb5 100644 --- a/platforms/Eclipse-Cygwin/README.md +++ b/platforms/Eclipse-Cygwin/README.md @@ -1,21 +1,21 @@ -##Using the Eclipse-Cygwin Project +## Using the Eclipse-Cygwin Project This project is for use on the Windows platform. These are the steps required for using it. (If you only wish to compile the CppUTest libraries, it is recommended that you use the method described at http://cpputest.github.io, rather than setting up Eclipse). -###Preparation -####1. Install Cygwin +### Preparation +#### 1. Install Cygwin You need to have Cygwin installed, with at least the Gnu C\C++ compiler, make, autotools and libtool. Please follow the instructions at http://cpputest.github.io to build CppUTest from the Cygwin bash prompt. -####2. Set your PATH +#### 2. Set your PATH Next, you need to add the path to your Cygwin binaries to your Windows system path, e.g. ```dos C:\\Cygwin\bin ``` -####3. Install Eclipse CDT +#### 3. Install Eclipse CDT Use your existing Eclipse CDT (Juno, Kepler, ...) or unpack the release to your system drive. You may use the 32 bit version as it will work on all systems. Unless you have a specific reason, you do not require the 64 bit version. You may need to install or update your Java JRE and add it to your system path. The JRE needs to match, e.g. 32 bit Eclipse requires the 32 bit JRE. -####4. Install the C/C++Unit plugin +#### 4. Install the C/C++Unit plugin Open Eclipse. Accept the default workspace for now (you may want to set a more appropriate workspace location later on). Then install the "C/C++ Unit Test" plugin: "Help"->"Install New Software"-> work with "Kepler - http://download.eclipse.org/releases/kepler". @@ -30,20 +30,20 @@ While you are at it, you might also want to install: [x] Gcov Integration ``` -####5. Add the CppUTest plugin +#### 5. Add the CppUTest plugin Clone the [CppUTest Eclipse Test Runner](https://github.com/tcmak/CppUTestEclipseJunoTestRunner) and add it to Eclipse following the instructions there. -###Import this project into Eclipse +### Import this project into Eclipse In Eclipse you can't simply "open" a project - you have to first import it into the workspace: * File->Import...->General->Existing Projects into workspace * [Next >]->Select root directory: `/Platforms/Eclipse-Cygwin` * Make sure that `[ ] Copy projects into workspace` is **NOT** ticked. * Click Finish. -###Compile and run tests +### Compile and run tests Before you can compile CppUTest in Eclipse, you must configure it using Automake. Instructions can be found at http://cpputest.github.io/. Once you have done this, select a configuration (Libraries, Check, CppUTestTests or CppUTestExtTests) via Project->BuildConfiguration->Set Active>. The 'Check' configuration will build the libraries along with all tests and run the tests. -###Working with the C/C++ Unit plugin +### Working with the C/C++ Unit plugin Make sure your unit test executable has been built and exists, e.g. cpputest_build/CppUTestTests.exe. The first time you run tests using the plugin, you need to select them via @@ -56,10 +56,10 @@ Note that launch configurations have been included with this project; in your ow This is an example of what a successful test run would look like: ![Successful Test Run](https://raw.githubusercontent.com/cpputest/cpputest.github.io/master/images/eclipse-testrunner-01.png) You can select and rerun individual tests in the upper pane, and error messages for failed tests will appear in the lower pane. -###Troubleshooting -####Problem: I am getting no test results... +### Troubleshooting +#### Problem: I am getting no test results... ...but you know your tests should have run, and you did not receive any error message. -#####Possible Reason: +##### Possible Reason: This can happen if the Cygwin-generated binary can't find the Cygwin DLLs. (If you were to run your test executable at the Windows cmd prompt, you would see a Windows error message box to that effect). Since no error message is displayed in the console via stderr, this leaves the test runner ignorant of what happenend -#####Solution: +##### Solution: You need to add /Cygwin/bin to your system PATH variable. Then you must restart Eclipse. diff --git a/platforms/IAR-STR912.zip b/platforms/IAR-STR912.zip deleted file mode 100644 index f5e69943e..000000000 Binary files a/platforms/IAR-STR912.zip and /dev/null differ diff --git a/platforms/armcc/Makefile b/platforms/armcc/Makefile index 83e64c57a..0bb7c5db9 100644 --- a/platforms/armcc/Makefile +++ b/platforms/armcc/Makefile @@ -29,7 +29,6 @@ COMPONENT_NAME := CppUTest INCLUDE_DIRS :=\ $(CPPUTEST_HOME)/include \ - $(CPPUTEST_HOME)/include/Platforms/armcc \ # armcc system include path SYS_INCLUDE_DIRS:=$(KEIL_DIR)/include diff --git a/platforms/iar/CppUTest.dep b/platforms/iar/CppUTest.dep deleted file mode 100644 index a4e6664ce..000000000 --- a/platforms/iar/CppUTest.dep +++ /dev/null @@ -1,557 +0,0 @@ - - - - 2 - 1004061121 - - Debug - - $PROJ_DIR$\Debug\Obj\TestFailure.o - $PROJ_DIR$\Debug\Obj\SimpleString.o - $PROJ_DIR$\Debug\Obj\TestFilter.o - $PROJ_DIR$\Debug\Obj\MemoryLeakWarningPlugin.o - $PROJ_DIR$\Debug\Obj\TestMemoryAllocator.o - $PROJ_DIR$\Debug\Obj\TestHarness_c.o - $PROJ_DIR$\Debug\Obj\SimpleMutex.o - $PROJ_DIR$\Debug\Obj\CommandLineArguments.pbi - $PROJ_DIR$\Debug\Obj\UtestPlatform.o - $PROJ_DIR$\Debug\Obj\TestPlugin.o - $PROJ_DIR$\Debug\Obj\TestOutput.o - $PROJ_DIR$\Debug\Obj\TestRegistry.o - $PROJ_DIR$\Debug\Obj\TestResult.o - $PROJ_DIR$\Debug\Obj\Utest.o - $PROJ_DIR$\Debug\Obj\JUnitTestOutput.pbi - $PROJ_DIR$\Debug\Obj\CommandLineTestRunner.pbi - $PROJ_DIR$\Debug\Obj\MemoryLeakDetector.pbi - $PROJ_DIR$\Debug\Obj\MemoryLeakWarningPlugin.pbi - $PROJ_DIR$\Debug\Obj\SimpleMutex.pbi - $PROJ_DIR$\Debug\Obj\SimpleString.pbi - $PROJ_DIR$\Debug\Obj\TestFailure.pbi - $PROJ_DIR$\Debug\Obj\TestFilter.pbi - $PROJ_DIR$\Debug\Obj\TestHarness_c.pbi - $PROJ_DIR$\Debug\Obj\TestMemoryAllocator.pbi - $PROJ_DIR$\Debug\Obj\TestOutput.pbi - $PROJ_DIR$\Debug\Obj\TestPlugin.pbi - $PROJ_DIR$\Debug\Obj\TestRegistry.pbi - $PROJ_DIR$\Debug\Obj\TestResult.pbi - $PROJ_DIR$\Debug\Obj\UtestPlatform.pbi - $PROJ_DIR$\..\..\include\CppUTest\JUnitTestOutput.h - $PROJ_DIR$\..\..\include\CppUTest\CommandLineTestRunner.h - $PROJ_DIR$\..\..\include\CppUTest\TestRegistry.h - $PROJ_DIR$\..\..\include\CppUTest\TestMemoryAllocator.h - $PROJ_DIR$\..\..\include\CppUTest\SimpleMutex.h - $PROJ_DIR$\..\..\include\CppUTest\MemoryLeakDetector.h - $PROJ_DIR$\..\..\include\CppUTest\TestHarness_c.h - $TOOLKIT_DIR$\inc\c\setjmp.h - $PROJ_DIR$\..\..\src\CppUTest\JUnitTestOutput.cpp - $PROJ_DIR$\..\..\src\CppUTest\CommandLineTestRunner.cpp - $PROJ_DIR$\..\..\src\CppUTest\CommandLineArguments.cpp - $PROJ_DIR$\..\..\src\CppUTest\MemoryLeakDetector.cpp - $PROJ_DIR$\..\..\src\CppUTest\MemoryLeakWarningPlugin.cpp - $PROJ_DIR$\..\..\src\CppUTest\SimpleMutex.cpp - $PROJ_DIR$\..\..\src\CppUTest\SimpleString.cpp - $PROJ_DIR$\..\..\src\CppUTest\TestFailure.cpp - $PROJ_DIR$\..\..\src\CppUTest\TestFilter.cpp - $PROJ_DIR$\..\..\src\CppUTest\TestHarness_c.cpp - $PROJ_DIR$\..\..\src\CppUTest\TestMemoryAllocator.cpp - $PROJ_DIR$\..\..\src\CppUTest\TestOutput.cpp - $PROJ_DIR$\..\..\src\CppUTest\TestPlugin.cpp - $PROJ_DIR$\..\..\src\CppUTest\TestRegistry.cpp - $PROJ_DIR$\..\..\src\CppUTest\TestResult.cpp - $PROJ_DIR$\..\..\src\Platforms\Iar\UtestPlatform.cpp - $PROJ_DIR$\..\..\src\CppUTest\Utest.cpp - $PROJ_DIR$\Debug\Obj\CommandLineTestRunner.o - $PROJ_DIR$\Debug\Obj\CommandLineArguments.o - $PROJ_DIR$\Debug\Obj\MemoryLeakDetector.o - $PROJ_DIR$\Debug\Obj\JUnitTestOutput.o - $PROJ_DIR$\Debug\Obj\Utest.pbi - $PROJ_DIR$\Debug\Exe\CppUTest.a - $PROJ_DIR$\Debug\Obj\CppUTest.pbd - $TOOLKIT_DIR$\inc\cpp\xlocinfo - $TOOLKIT_DIR$\inc\c\xencoding_limits.h - $TOOLKIT_DIR$\inc\c\cmath - $TOOLKIT_DIR$\inc\c\yvals.h - $TOOLKIT_DIR$\inc\c\ycheck.h - $TOOLKIT_DIR$\inc\c\ysizet.h - $TOOLKIT_DIR$\inc\c\cstdlib - $PROJ_DIR$\..\..\include\CppUTest\StandardCLibrary.h - $TOOLKIT_DIR$\inc\c\ymath.h - $PROJ_DIR$\..\..\include\CppUTest\CppUTestConfig.h - $PROJ_DIR$\..\..\include\CppUTest\TestResult.h - $TOOLKIT_DIR$\inc\c\math.h - $TOOLKIT_DIR$\inc\cpp\xiosbase - $TOOLKIT_DIR$\inc\cpp\xlocale - $TOOLKIT_DIR$\inc\cpp\utility - $PROJ_DIR$\..\..\include\CppUTest\SimpleString.h - $TOOLKIT_DIR$\inc\c\DLib_Defaults.h - $TOOLKIT_DIR$\inc\c\DLib_Product.h - $PROJ_DIR$\..\..\include\CppUTest\PlatformSpecificFunctions.h - $TOOLKIT_DIR$\inc\c\cstring - $PROJ_DIR$\..\..\include\CppUTest\PlatformSpecificFunctions_c.h - $TOOLKIT_DIR$\inc\c\ystdio.h - $PROJ_DIR$\..\..\include\CppUTest\UtestMacros.h - $TOOLKIT_DIR$\inc\c\stddef.h - $TOOLKIT_DIR$\inc\cpp\iosfwd - $TOOLKIT_DIR$\inc\cpp\xstddef - $TOOLKIT_DIR$\inc\c\DLib_Config_Normal.h - $PROJ_DIR$\..\..\include\CppUTest\TestPlugin.h - $TOOLKIT_DIR$\inc\c\DLib_Product_string.h - $TOOLKIT_DIR$\inc\c\stdlib.h - $TOOLKIT_DIR$\inc\c\stdio.h - $PROJ_DIR$\..\..\include\CppUTest\CommandLineArguments.h - $TOOLKIT_DIR$\inc\cpp\string - $TOOLKIT_DIR$\inc\c\ctype.h - $TOOLKIT_DIR$\inc\cpp\typeinfo - $TOOLKIT_DIR$\inc\c\wchar.h - $TOOLKIT_DIR$\inc\cpp\xstring - $TOOLKIT_DIR$\inc\cpp\xutility - $TOOLKIT_DIR$\inc\cpp\exception - $PROJ_DIR$\..\..\include\CppUTest\TestFailure.h - $TOOLKIT_DIR$\inc\c\xlocaleuse.h - $TOOLKIT_DIR$\inc\cpp\ios - $TOOLKIT_DIR$\inc\cpp\memory - $PROJ_DIR$\..\..\include\CppUTest\MemoryLeakWarningPlugin.h - $PROJ_DIR$\..\..\include\CppUTest\Utest.h - $TOOLKIT_DIR$\inc\c\climits - $TOOLKIT_DIR$\inc\c\DLib_Threads.h - $TOOLKIT_DIR$\inc\cpp\istream - $TOOLKIT_DIR$\inc\cpp\ostream - $TOOLKIT_DIR$\inc\c\cstdio - $TOOLKIT_DIR$\inc\cpp\xlocnum - $TOOLKIT_DIR$\inc\c\cstddef - $TOOLKIT_DIR$\inc\c\clocale - $TOOLKIT_DIR$\inc\cpp\streambuf - $TOOLKIT_DIR$\inc\c\limits.h - $TOOLKIT_DIR$\inc\c\xtgmath.h - $TOOLKIT_DIR$\inc\cpp\stdexcept - $TOOLKIT_DIR$\inc\cpp\xdebug - $TOOLKIT_DIR$\inc\cpp\new - $TOOLKIT_DIR$\inc\c\string.h - $TOOLKIT_DIR$\inc\c\cwchar - $TOOLKIT_DIR$\inc\cpp\xmemory - $TOOLKIT_DIR$\inc\c\ctime - $TOOLKIT_DIR$\inc\c\xtls.h - $TOOLKIT_DIR$\inc\c\xmtx.h - $TOOLKIT_DIR$\inc\c\xlocale.h - $PROJ_DIR$\..\..\include\CppUTest\TestHarness.h - $TOOLKIT_DIR$\inc\c\cctype - $PROJ_DIR$\..\..\include\CppUTest\TestOutput.h - $TOOLKIT_DIR$\inc\c\time.h - $PROJ_DIR$\..\..\include\CppUTest\MemoryLeakDetectorNewMacros.h - $TOOLKIT_DIR$\inc\c\xlocale_c.h - $TOOLKIT_DIR$\inc\c\locale.h - $TOOLKIT_DIR$\inc\c\xlocale_lconv.h - $PROJ_DIR$\..\..\include\CppUTest\TestFilter.h - - - [ROOT_NODE] - - - IARCHIVE - 59 - - - - - $PROJ_DIR$\..\..\src\CppUTest\JUnitTestOutput.cpp - - - BICOMP - 14 - - - ICCARM - 57 - - - - - BICOMP - 78 121 132 70 106 64 65 66 90 77 109 114 112 79 71 62 111 118 120 122 97 134 81 83 88 68 84 87 108 102 110 115 116 117 113 99 86 119 67 133 131 29 100 105 76 104 107 93 63 72 69 91 82 73 74 80 95 61 89 98 75 85 96 128 123 130 129 127 94 126 124 101 125 103 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 29 129 79 81 - - - - - $PROJ_DIR$\..\..\src\CppUTest\CommandLineTestRunner.cpp - - - BICOMP - 15 - - - ICCARM - 54 - - - - - BICOMP - 65 102 64 76 108 117 99 135 31 70 104 107 110 115 116 113 86 119 129 105 100 67 90 62 109 111 106 114 66 118 120 112 122 121 80 94 101 96 103 30 29 83 71 88 68 84 77 87 78 93 63 72 69 91 82 73 74 95 61 89 97 98 75 85 126 124 125 127 128 123 132 133 134 130 131 92 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 30 129 92 135 29 31 - - - - - $PROJ_DIR$\..\..\src\CppUTest\CommandLineArguments.cpp - - - BICOMP - 7 - - - ICCARM - 55 - - - - - BICOMP - 61 65 66 62 63 64 67 71 69 73 74 75 70 77 78 76 68 72 82 80 84 85 86 81 79 83 88 90 87 93 91 95 89 97 98 99 94 101 96 103 92 105 100 104 107 108 109 102 111 106 110 114 115 116 117 118 113 120 112 122 119 121 126 124 125 129 127 128 123 132 133 134 130 131 135 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 92 129 135 79 81 - - - - - $PROJ_DIR$\..\..\src\CppUTest\MemoryLeakDetector.cpp - - - BICOMP - 16 - - - ICCARM - 56 - - - - - BICOMP - 64 65 120 105 90 111 122 81 62 106 118 124 33 100 67 107 109 114 66 112 113 126 125 88 32 70 76 104 108 102 110 115 116 117 99 86 98 80 121 34 79 83 71 68 84 77 87 78 93 63 72 69 91 82 73 74 95 61 89 97 75 85 94 101 96 103 127 119 128 123 132 133 134 130 131 129 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 34 32 79 129 81 33 - - - - - $PROJ_DIR$\..\..\src\CppUTest\MemoryLeakWarningPlugin.cpp - - - BICOMP - 17 - - - ICCARM - 3 - - - - - BICOMP - 105 64 111 122 65 120 81 106 118 124 79 100 67 87 109 114 66 112 113 126 125 88 34 70 76 104 77 62 78 108 102 110 115 116 117 99 86 119 80 121 32 33 83 71 68 84 90 107 93 63 72 69 91 82 73 74 95 61 89 97 98 75 85 94 101 96 103 127 128 123 132 133 134 130 131 129 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 34 32 79 129 81 33 - - - - - $PROJ_DIR$\..\..\src\CppUTest\SimpleMutex.cpp - - - BICOMP - 18 - - - ICCARM - 6 - - - - - BICOMP - 112 65 66 109 114 64 71 87 106 121 70 90 62 111 118 120 122 81 83 88 68 84 77 78 108 102 110 115 116 117 113 99 86 119 96 80 94 101 76 103 33 105 100 104 67 107 93 63 72 69 91 82 73 74 95 61 89 97 98 75 85 126 124 125 127 128 123 132 133 134 130 131 79 129 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 33 79 129 81 - - - - - $PROJ_DIR$\..\..\src\CppUTest\SimpleString.cpp - - - BICOMP - 19 - - - ICCARM - 1 - - - - - BICOMP - 68 64 65 67 98 130 88 90 87 83 84 62 93 91 95 89 97 128 79 71 70 66 77 78 76 63 72 69 82 73 74 80 61 75 110 96 123 122 129 32 105 100 104 107 108 109 102 111 106 114 115 116 117 118 113 120 99 86 112 119 121 132 133 134 131 127 85 94 126 124 101 125 103 81 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 79 129 81 32 - - - - - $PROJ_DIR$\..\..\src\CppUTest\TestFailure.cpp - - - BICOMP - 20 - - - ICCARM - 0 - - - - - BICOMP - 66 65 95 89 97 70 93 91 79 71 87 64 67 98 85 86 81 129 83 88 68 84 90 77 62 78 76 63 72 69 82 73 74 80 61 75 99 94 101 96 100 105 104 107 108 109 102 111 106 110 114 115 116 117 118 113 120 112 122 119 121 126 124 125 103 127 128 123 132 133 134 130 131 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 129 79 81 - - - - - $PROJ_DIR$\..\..\src\CppUTest\TestFilter.cpp - - - BICOMP - 21 - - - ICCARM - 2 - - - - - BICOMP - 121 107 64 67 76 63 98 65 69 91 80 66 68 72 95 89 97 113 126 124 125 135 70 84 90 77 62 93 82 73 74 61 75 85 86 99 94 101 96 87 78 108 109 102 111 106 110 114 115 116 117 118 120 112 122 119 128 123 132 133 134 130 - - - ICCARM - 70 68 84 65 64 77 87 78 62 107 66 67 90 135 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 - - - - - $PROJ_DIR$\..\..\src\CppUTest\TestHarness_c.cpp - - - BICOMP - 22 - - - ICCARM - 5 - - - - - BICOMP - 68 76 64 84 65 77 72 88 90 78 82 80 66 85 35 83 62 63 69 73 74 61 67 75 86 32 71 70 87 93 91 95 89 97 98 99 94 101 96 103 34 79 105 100 104 107 108 109 102 111 106 110 114 115 116 117 118 113 120 112 122 119 121 126 124 125 81 127 128 123 132 133 134 130 131 129 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 34 32 79 129 81 35 - - - - - $PROJ_DIR$\..\..\src\CppUTest\TestMemoryAllocator.cpp - - - BICOMP - 23 - - - ICCARM - 4 - - - - - BICOMP - 64 68 67 98 124 88 90 87 65 83 84 66 93 91 95 89 97 113 126 125 79 71 70 77 62 78 76 63 72 69 82 73 74 80 61 75 121 32 34 105 100 104 107 108 109 102 111 106 110 114 115 116 117 118 120 99 86 112 122 119 85 94 101 96 103 129 127 128 123 132 133 134 130 131 81 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 32 79 129 81 34 - - - - - $PROJ_DIR$\..\..\src\CppUTest\TestOutput.cpp - - - BICOMP - 24 - - - ICCARM - 10 - - - - - BICOMP - 83 84 69 73 74 75 121 65 62 63 64 61 67 88 68 90 77 78 76 72 82 80 66 81 79 71 70 87 93 91 95 89 97 98 113 126 124 125 129 105 100 104 107 108 109 102 111 106 110 114 115 116 117 118 120 99 86 112 122 119 85 94 101 96 103 127 128 123 132 133 134 130 131 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 129 79 81 - - - - - $PROJ_DIR$\..\..\src\CppUTest\TestPlugin.cpp - - - BICOMP - 25 - - - ICCARM - 9 - - - - - BICOMP - 80 63 64 67 71 107 61 66 65 69 73 74 75 103 70 76 68 72 82 84 85 86 99 94 101 96 83 88 90 93 91 95 89 97 98 105 100 104 77 62 87 78 108 109 102 111 106 110 114 115 116 117 118 113 120 112 122 119 121 126 124 125 127 128 123 132 133 134 130 131 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 - - - - - $PROJ_DIR$\..\..\src\CppUTest\TestRegistry.cpp - - - BICOMP - 26 - - - ICCARM - 11 - - - - - BICOMP - 64 102 65 105 96 66 108 117 99 94 101 76 100 67 107 110 115 116 113 86 119 80 103 70 104 109 111 106 114 118 120 112 122 121 31 83 71 88 68 84 90 77 62 87 78 93 63 72 69 91 82 73 74 95 61 89 97 98 75 85 126 124 125 135 127 128 123 132 133 134 130 131 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 31 135 - - - - - $PROJ_DIR$\..\..\src\CppUTest\TestResult.cpp - - - BICOMP - 27 - - - ICCARM - 12 - - - - - BICOMP - 65 106 62 118 121 70 90 111 120 122 79 71 66 87 64 109 114 112 81 100 83 88 68 84 77 78 108 102 110 115 116 117 113 99 86 119 126 124 125 129 105 76 104 67 107 93 63 72 69 91 82 73 74 80 95 61 89 97 98 75 85 94 101 96 103 127 128 123 132 133 134 130 131 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 129 79 81 - - - - - $PROJ_DIR$\..\..\src\Platforms\Iar\UtestPlatform.cpp - - - BICOMP - 28 - - - ICCARM - 8 - - - - - BICOMP - 100 74 108 67 73 80 133 62 116 127 66 64 65 102 120 113 81 36 89 101 96 105 90 110 115 118 98 94 107 82 124 125 70 76 104 109 111 106 114 97 121 134 88 91 72 79 77 87 78 126 132 69 83 71 68 84 93 63 117 75 85 86 99 130 103 95 61 112 122 119 128 123 131 129 - - - ICCARM - 130 65 64 77 87 78 62 107 66 91 82 90 36 120 89 94 126 124 125 101 132 96 72 69 116 127 70 68 84 67 105 76 93 108 109 102 111 106 115 63 110 114 73 74 80 117 99 86 112 97 122 119 98 75 85 121 95 118 61 128 113 133 134 123 83 71 100 88 104 131 103 79 129 81 - - - - - $PROJ_DIR$\..\..\src\CppUTest\Utest.cpp - - - BICOMP - 58 - - - ICCARM - 13 - - - - - BICOMP - 98 65 64 67 88 90 66 68 76 80 81 83 84 93 91 95 89 97 121 135 79 71 70 107 62 63 72 69 82 73 74 61 75 113 126 124 125 31 129 105 100 104 77 87 78 108 109 102 111 106 110 114 115 116 117 118 120 99 86 112 122 119 85 94 101 96 103 127 128 123 132 133 134 130 131 - - - ICCARM - 127 70 68 84 65 64 77 87 78 62 107 66 67 90 105 76 93 108 109 102 111 106 115 63 72 69 116 110 91 82 114 73 74 80 120 89 117 99 86 112 97 122 119 98 75 85 121 96 95 118 61 128 94 126 124 125 101 132 113 133 134 123 130 83 71 100 88 104 131 103 31 135 79 129 81 - - - - - - Release - - - [MULTI_TOOL] - ILINK - - - - - diff --git a/platforms/iar/CppUTest.ewd b/platforms/iar/CppUTest.ewd index 68ed95334..1c6f889c9 100644 --- a/platforms/iar/CppUTest.ewd +++ b/platforms/iar/CppUTest.ewd @@ -12,7 +12,7 @@ C-SPY 2 - 26 + 28 1 1 - + + @@ -278,18 +282,47 @@ - CMSISDAP_ID + CADI_ID 2 - 2 + 0 1 1 + + + + + + + + CMSISDAP_ID + 2 + + 4 + 1 + 1 + + + @@ -520,15 +561,15 @@ IJET_ID 2 - 6 + 8 1 1 + + JLINK_ID 2 - 15 + 16 1 1 + - @@ -1193,7 +1195,7 @@ STLINK_ID 2 - 2 + 3 1 1 + + + + + + + + + + + + + + + + + + @@ -1253,10 +1328,10 @@ - XDS100_ID + TIFET_ID 2 - 2 + 1 1 1 + + + + + + + + + + + + + + XDS100_ID + 2 + + 5 + 1 + 1 + + + - - - - - $TOOLKIT_DIR$\plugins\middleware\HCCWare\HCCWare.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\AVIX\AVIX.ENU.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\CMX\CmxArmPlugin.ENU.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\CMX\CmxTinyArmPlugin.ENU.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\embOS\embOSPlugin.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\MQX\MQXRtosPlugin.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\OpenRTOS\OpenRTOSPlugin.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\Quadros\Quadros_EWB7_Plugin.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\SafeRTOS\SafeRTOSPlugin.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\ThreadX\ThreadXArmPlugin.ENU.ewplugin - 0 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $TOOLKIT_DIR$\plugins\middleware\HCCWare\HCCWare.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\middleware\PercepioTraceExporter\PercepioTraceExportPlugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\AVIX\AVIX.ENU.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\CMX\CmxArmPlugin.ENU.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\CMX\CmxTinyArmPlugin.ENU.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\embOS\embOSPlugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\MQX\MQXRtosPlugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\OpenRTOS\OpenRTOSPlugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\Quadros\Quadros_EWB7_Plugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\SafeRTOS\SafeRTOSPlugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\ThreadX\ThreadXArmPlugin.ENU.ewplugin + 0 + + $TOOLKIT_DIR$\plugins\rtos\TI-RTOS\tirtosplugin.ewplugin 0 @@ -1359,10 +1627,6 @@ $EW_DIR$\common\plugins\Orti\Orti.ENU.ewplugin 0 - - $EW_DIR$\common\plugins\SymList\SymList.ENU.ewplugin - 1 - $EW_DIR$\common\plugins\uCProbe\uCProbePlugin.ENU.ewplugin 0 @@ -1379,7 +1643,7 @@ C-SPY 2 - 26 + 28 1 0 - + + @@ -1645,18 +1913,47 @@ - CMSISDAP_ID + CADI_ID 2 - 2 + 0 1 0 + + + + + + + + CMSISDAP_ID + 2 + + 4 + 1 + 0 + + + @@ -1887,15 +2192,15 @@ IJET_ID 2 - 6 + 8 1 0 + + JLINK_ID 2 - 15 + 16 1 0 + - @@ -2560,7 +2826,7 @@ STLINK_ID 2 - 2 + 3 1 0 + + + + + + + + + + + + + + + + + + @@ -2620,10 +2959,10 @@ - XDS100_ID + TIFET_ID 2 - 2 + 1 1 0 + + + + + + + + + + + + + + XDS100_ID + 2 + + 5 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2666,6 +3194,10 @@ $TOOLKIT_DIR$\plugins\middleware\HCCWare\HCCWare.ewplugin 0 + + $TOOLKIT_DIR$\plugins\middleware\PercepioTraceExporter\PercepioTraceExportPlugin.ewplugin + 0 + $TOOLKIT_DIR$\plugins\rtos\AVIX\AVIX.ENU.ewplugin 0 @@ -2726,10 +3258,6 @@ $EW_DIR$\common\plugins\Orti\Orti.ENU.ewplugin 0 - - $EW_DIR$\common\plugins\SymList\SymList.ENU.ewplugin - 1 - $EW_DIR$\common\plugins\uCProbe\uCProbePlugin.ENU.ewplugin 0 diff --git a/platforms/iar/CppUTest.ewp b/platforms/iar/CppUTest.ewp index 35697ada4..f2f1fbe16 100644 --- a/platforms/iar/CppUTest.ewp +++ b/platforms/iar/CppUTest.ewp @@ -12,7 +12,7 @@ General 3 - 22 + 24 1 1 - - - + + + + + + @@ -229,7 +242,7 @@ @@ -934,7 +955,7 @@ @@ -954,7 +975,7 @@ General 3 - 22 + 24 1 0 - - - + + + + + + @@ -1573,7 +1607,7 @@ ILINK 0 - 16 + 18 1 0 + + @@ -1911,6 +1953,12 @@ $PROJ_DIR$\..\..\src\CppUTest\SimpleString.cpp + + $PROJ_DIR$\..\..\src\CppUTest\SimpleStringInternalCache.cpp + + + $PROJ_DIR$\..\..\src\CppUTest\TeamCityTestOutput.cpp + $PROJ_DIR$\..\..\src\CppUTest\TestFailure.cpp @@ -1935,6 +1983,9 @@ $PROJ_DIR$\..\..\src\CppUTest\TestResult.cpp + + $PROJ_DIR$\..\..\src\CppUTest\TestTestingFixture.cpp + $PROJ_DIR$\..\..\src\CppUTest\Utest.cpp diff --git a/platforms/iar/CppUTest.ewt b/platforms/iar/CppUTest.ewt deleted file mode 100644 index c1de1bc55..000000000 --- a/platforms/iar/CppUTest.ewt +++ /dev/null @@ -1,2176 +0,0 @@ - - - - 2 - - Debug - - ARM - - 1 - - C-STAT - 1 - - 1 - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - RuntimeChecking - 0 - - 2 - 1 - 1 - - - - - - - - - - - - - - - - - - - - - - Release - - ARM - - 0 - - C-STAT - 1 - - 1 - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - RuntimeChecking - 0 - - 2 - 1 - 0 - - - - - - - - - - - - - - - - - - - - - - src - - CppUTest - - $PROJ_DIR$\src\CppUTest\CommandLineArguments.cpp - - - $PROJ_DIR$\src\CppUTest\CommandLineTestRunner.cpp - - - $PROJ_DIR$\src\CppUTest\JUnitTestOutput.cpp - - - $PROJ_DIR$\src\CppUTest\MemoryLeakDetector.cpp - - - $PROJ_DIR$\src\CppUTest\MemoryLeakWarningPlugin.cpp - - - $PROJ_DIR$\src\CppUTest\SimpleMutex.cpp - - - $PROJ_DIR$\src\CppUTest\SimpleString.cpp - - - $PROJ_DIR$\src\CppUTest\TestFailure.cpp - - - $PROJ_DIR$\src\CppUTest\TestFilter.cpp - - - $PROJ_DIR$\src\CppUTest\TestHarness_c.cpp - - - $PROJ_DIR$\src\CppUTest\TestMemoryAllocator.cpp - - - $PROJ_DIR$\src\CppUTest\TestOutput.cpp - - - $PROJ_DIR$\src\CppUTest\TestPlugin.cpp - - - $PROJ_DIR$\src\CppUTest\TestRegistry.cpp - - - $PROJ_DIR$\src\CppUTest\TestResult.cpp - - - $PROJ_DIR$\src\CppUTest\Utest.cpp - - - - Platforms - - Iar - - $PROJ_DIR$\src\Platforms\Iar\UtestPlatform.cpp - - - - - - - diff --git a/platforms/iar/CppUTest.eww b/platforms/iar/CppUTest.eww index 2a0cec9a0..004925c23 100644 --- a/platforms/iar/CppUTest.eww +++ b/platforms/iar/CppUTest.eww @@ -4,6 +4,12 @@ $WS_DIR$\CppUTest.ewp + + $WS_DIR$\CppUTestExt.ewp + + + $WS_DIR$\CppUTestExtTest.ewp + $WS_DIR$\CppUTestTest.ewp diff --git a/platforms/iar/CppUTestExt.ewp b/platforms/iar/CppUTestExt.ewp new file mode 100644 index 000000000..429c3f5cf --- /dev/null +++ b/platforms/iar/CppUTestExt.ewp @@ -0,0 +1,1993 @@ + + + + 2 + + Debug + + ARM + + 1 + + General + 3 + + 24 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ICCARM + 2 + + 31 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AARM + 2 + + 9 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + OBJCOPY + 0 + + 1 + 1 + 1 + + + + + + + + + CUSTOM + 3 + + + + 0 + + + + BICOMP + 0 + + + + BUILDACTION + 1 + + + + + + + ILINK + 0 + + 18 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + IARCHIVE + 0 + + 0 + 1 + 1 + + + + + + + BILINK + 0 + + + + + Release + + ARM + + 0 + + General + 3 + + 24 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ICCARM + 2 + + 31 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AARM + 2 + + 9 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + OBJCOPY + 0 + + 1 + 1 + 0 + + + + + + + + + CUSTOM + 3 + + + + 0 + + + + BICOMP + 0 + + + + BUILDACTION + 1 + + + + + + + ILINK + 0 + + 18 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + IARCHIVE + 0 + + 0 + 1 + 0 + + + + + + + BILINK + 0 + + + + + src + + CppUTestExt + + $PROJ_DIR$\..\..\src\CppUTestExt\CodeMemoryReportFormatter.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\GTest.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\IEEE754ExceptionsPlugin.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\MemoryReportAllocator.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\MemoryReporterPlugin.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\MemoryReportFormatter.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\MockActualCall.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\MockExpectedCall.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\MockExpectedCallsList.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\MockFailure.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\MockNamedValue.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\MockSupport.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\MockSupport_c.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\MockSupportPlugin.cpp + + + $PROJ_DIR$\..\..\src\CppUTestExt\OrderedTest.cpp + + + + Platforms + + Iar + + $PROJ_DIR$\..\..\src\Platforms\Iar\UtestPlatform.cpp + + + + + + + diff --git a/platforms/iar/CppUTestExtTest.ewp b/platforms/iar/CppUTestExtTest.ewp new file mode 100644 index 000000000..6ad4084c7 --- /dev/null +++ b/platforms/iar/CppUTestExtTest.ewp @@ -0,0 +1,2048 @@ + + + + 2 + + Debug + + ARM + + 1 + + General + 3 + + 24 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ICCARM + 2 + + 31 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AARM + 2 + + 9 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + OBJCOPY + 0 + + 1 + 1 + 1 + + + + + + + + + CUSTOM + 3 + + + + 0 + + + + BICOMP + 0 + + + + BUILDACTION + 1 + + + + + + + ILINK + 0 + + 18 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + IARCHIVE + 0 + + 0 + 1 + 1 + + + + + + + BILINK + 0 + + + + + Release + + ARM + + 0 + + General + 3 + + 24 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ICCARM + 2 + + 31 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AARM + 2 + + 9 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + OBJCOPY + 0 + + 1 + 1 + 0 + + + + + + + + + CUSTOM + 3 + + + + 0 + + + + BICOMP + 0 + + + + BUILDACTION + 1 + + + + + + + ILINK + 0 + + 18 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + IARCHIVE + 0 + + 0 + 1 + 0 + + + + + + + BILINK + 0 + + + + + tests + + failing + + + passing + + $PROJ_DIR$\..\..\tests\CppUTestExt\CodeMemoryReporterTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\ExpectedFunctionsListTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\GMockTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\GTest1Test.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\GTest2ConvertorTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\IEEE754PluginTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\IEEE754PluginTest_c.c + + + $PROJ_DIR$\..\..\tests\CppUTestExt\IEEE754PluginTest_c.h + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MemoryReportAllocatorTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MemoryReporterPluginTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MemoryReportFormatterTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockActualCallTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockCallTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockCheatSheetTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockComparatorCopierTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockExpectedCallTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockFailureReporterForTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockFailureReporterForTest.h + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockFailureTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockHierarchyTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockNamedValueTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockParameterTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockPluginTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockReturnValueTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockStrictOrderTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockSupport_cTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockSupport_cTestCFile.c + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockSupport_cTestCFile.h + + + $PROJ_DIR$\..\..\tests\CppUTestExt\MockSupportTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\OrderedTestTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTestExt\OrderedTestTest.h + + + $PROJ_DIR$\..\..\tests\CppUTestExt\OrderedTestTest_c.c + + + + warnings + + + $PROJ_DIR$\..\..\tests\CppUTestExt\AllTests.cpp + + + $PROJ_DIR$\tests\iar_argc_argv.c + + + + + diff --git a/platforms/iar/CppUTestExtTest.icf b/platforms/iar/CppUTestExtTest.icf new file mode 100644 index 000000000..23bfb64c3 --- /dev/null +++ b/platforms/iar/CppUTestExtTest.icf @@ -0,0 +1,72 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\a_v1_1.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x00000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_IROM1_start__ = 0x00000080; +define symbol __ICFEDIT_region_IROM1_end__ = 0x000FFFFF; +define symbol __ICFEDIT_region_IROM2_start__ = 0x0; +define symbol __ICFEDIT_region_IROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM1_start__ = 0x0; +define symbol __ICFEDIT_region_EROM1_end__ = 0x0; +define symbol __ICFEDIT_region_EROM2_start__ = 0x0; +define symbol __ICFEDIT_region_EROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM3_start__ = 0x0; +define symbol __ICFEDIT_region_EROM3_end__ = 0x0; +define symbol __ICFEDIT_region_IRAM1_start__ = 0x00100000; +define symbol __ICFEDIT_region_IRAM1_end__ = 0x001FFFFF; +define symbol __ICFEDIT_region_IRAM2_start__ = 0x0; +define symbol __ICFEDIT_region_IRAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_end__ = 0x0; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x2000; +define symbol __ICFEDIT_size_svcstack__ = 0x100; +define symbol __ICFEDIT_size_irqstack__ = 0x100; +define symbol __ICFEDIT_size_fiqstack__ = 0x100; +define symbol __ICFEDIT_size_undstack__ = 0x100; +define symbol __ICFEDIT_size_abtstack__ = 0x100; +define symbol __ICFEDIT_size_heap__ = 0x10000; +/**** End of ICF editor section. ###ICF###*/ + +define memory mem with size = 4G; +define region IROM_region = mem:[from __ICFEDIT_region_IROM1_start__ to __ICFEDIT_region_IROM1_end__] + | mem:[from __ICFEDIT_region_IROM2_start__ to __ICFEDIT_region_IROM2_end__]; +define region EROM_region = mem:[from __ICFEDIT_region_EROM1_start__ to __ICFEDIT_region_EROM1_end__] + | mem:[from __ICFEDIT_region_EROM2_start__ to __ICFEDIT_region_EROM2_end__] + | mem:[from __ICFEDIT_region_EROM3_start__ to __ICFEDIT_region_EROM3_end__]; +define region IRAM_region = mem:[from __ICFEDIT_region_IRAM1_start__ to __ICFEDIT_region_IRAM1_end__] + | mem:[from __ICFEDIT_region_IRAM2_start__ to __ICFEDIT_region_IRAM2_end__]; +define region ERAM_region = mem:[from __ICFEDIT_region_ERAM1_start__ to __ICFEDIT_region_ERAM1_end__] + | mem:[from __ICFEDIT_region_ERAM2_start__ to __ICFEDIT_region_ERAM2_end__] + | mem:[from __ICFEDIT_region_ERAM3_start__ to __ICFEDIT_region_ERAM3_end__]; + +define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; +define block SVC_STACK with alignment = 8, size = __ICFEDIT_size_svcstack__ { }; +define block IRQ_STACK with alignment = 8, size = __ICFEDIT_size_irqstack__ { }; +define block FIQ_STACK with alignment = 8, size = __ICFEDIT_size_fiqstack__ { }; +define block UND_STACK with alignment = 8, size = __ICFEDIT_size_undstack__ { }; +define block ABT_STACK with alignment = 8, size = __ICFEDIT_size_abtstack__ { }; +define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + +do not initialize { section .noinit }; +initialize by copy { readwrite }; +if (isdefinedsymbol(__USE_DLIB_PERTHREAD)) +{ + // Required in a multi-threaded application + initialize by copy with packing = none { section __DLIB_PERTHREAD }; +} + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +place in IROM_region { readonly }; +place in EROM_region { readonly section application_specific_ro }; +place in IRAM_region { readwrite, + block CSTACK, block SVC_STACK, block IRQ_STACK, block FIQ_STACK, + block UND_STACK, block ABT_STACK, block HEAP }; +place in ERAM_region { readwrite section application_specific_rw }; \ No newline at end of file diff --git a/platforms/iar/CppUTestTest.dep b/platforms/iar/CppUTestTest.dep deleted file mode 100644 index 6c31bc41c..000000000 --- a/platforms/iar/CppUTestTest.dep +++ /dev/null @@ -1,1228 +0,0 @@ - - - - 2 - 1731071481 - - Debug - - $TOOLKIT_DIR$\inc\c\time.h - $TOOLKIT_DIR$\inc\c\limits.h - $TOOLKIT_DIR$\inc\c\xtgmath.h - $TOOLKIT_DIR$\inc\cpp\stdexcept - $TOOLKIT_DIR$\inc\cpp\xdebug - $TOOLKIT_DIR$\inc\cpp\xmemory - $TOOLKIT_DIR$\inc\c\string.h - $TOOLKIT_DIR$\inc\cpp\xutility - $TOOLKIT_DIR$\inc\cpp\utility - $TOOLKIT_DIR$\inc\c\xmtx.h - $TOOLKIT_DIR$\inc\c\xlocale.h - $PROJ_DIR$\..\..\include\CppUTest\TestHarness.h - $PROJ_DIR$\Debug\Obj\AllTests.pbi - $PROJ_DIR$\Debug\Obj\AllTests.o - $TOOLKIT_DIR$\inc\c\DLib_Defaults.h - $TOOLKIT_DIR$\inc\c\clocale - $TOOLKIT_DIR$\inc\c\stdlib.h - $PROJ_DIR$\..\..\include\CppUTest\PlatformSpecificFunctions_c.h - $TOOLKIT_DIR$\inc\c\DLib_Product.h - $TOOLKIT_DIR$\inc\cpp\istream - $TOOLKIT_DIR$\inc\cpp\ostream - $TOOLKIT_DIR$\inc\c\cstddef - $TOOLKIT_DIR$\inc\cpp\xlocnum - $TOOLKIT_DIR$\inc\c\cwchar - $TOOLKIT_DIR$\inc\cpp\streambuf - $TOOLKIT_DIR$\inc\c\xtls.h - $PROJ_DIR$\..\..\include\CppUTest\TestFailure.h - $TOOLKIT_DIR$\inc\cpp\new - $TOOLKIT_DIR$\inc\c\DLib_Threads.h - $TOOLKIT_DIR$\inc\c\ctype.h - $TOOLKIT_DIR$\inc\cpp\memory - $PROJ_DIR$\..\..\include\CppUTest\MemoryLeakDetector.h - $PROJ_DIR$\..\..\include\CppUTest\SimpleString.h - $PROJ_DIR$\..\..\include\CppUTest\Utest.h - $PROJ_DIR$\..\..\include\CppUTest\CppUTestConfig.h - $PROJ_DIR$\..\..\include\CppUTest\PlatformSpecificFunctions.h - $PROJ_DIR$\..\..\include\CppUTest\StandardCLibrary.h - $PROJ_DIR$\..\..\include\CppUTest\MemoryLeakWarningPlugin.h - $TOOLKIT_DIR$\inc\c\cmath - $TOOLKIT_DIR$\inc\c\math.h - $TOOLKIT_DIR$\inc\c\ymath.h - $TOOLKIT_DIR$\inc\cpp\ios - $TOOLKIT_DIR$\inc\c\ystdio.h - $PROJ_DIR$\..\..\include\CppUTest\UtestMacros.h - $TOOLKIT_DIR$\inc\cpp\xiosbase - $TOOLKIT_DIR$\inc\cpp\xlocale - $TOOLKIT_DIR$\inc\cpp\xlocinfo - $TOOLKIT_DIR$\inc\c\stddef.h - $TOOLKIT_DIR$\inc\c\xencoding_limits.h - $TOOLKIT_DIR$\inc\cpp\iosfwd - $TOOLKIT_DIR$\inc\cpp\xstddef - $TOOLKIT_DIR$\inc\c\DLib_Config_Normal.h - $TOOLKIT_DIR$\inc\c\cstdio - $PROJ_DIR$\..\..\include\CppUTest\TestResult.h - $PROJ_DIR$\..\..\include\CppUTest\TestPlugin.h - $PROJ_DIR$\Debug\Obj\tests.o - $TOOLKIT_DIR$\inc\c\cstdlib - $PROJ_DIR$\..\..\tests\UtestPlatformTest.cpp - $PROJ_DIR$\..\..\tests\UtestTest.cpp - $PROJ_DIR$\..\..\tests\tests.cpp - $TOOLKIT_DIR$\inc\c\wchar.h - $TOOLKIT_DIR$\inc\cpp\xstring - $TOOLKIT_DIR$\inc\cpp\typeinfo - $TOOLKIT_DIR$\inc\cpp\exception - $TOOLKIT_DIR$\inc\cpp\string - $PROJ_DIR$\..\..\include\CppUTest\TestMemoryAllocator.h - $TOOLKIT_DIR$\inc\c\ysizet.h - $PROJ_DIR$\Debug\Obj\AllocationInCppFile.o - $PROJ_DIR$\Debug\Obj\AllocLetTestFreeTest.o - $PROJ_DIR$\Debug\Obj\AllocationInCFile.o - $TOOLKIT_DIR$\lib\m7M_tls.a - $TOOLKIT_DIR$\lib\rt7M_tl.a - $PROJ_DIR$\CppUTestTest.icf - $TOOLKIT_DIR$\lib\shb_l.a - $TOOLKIT_DIR$\lib\dlpp7M_tl_nc.a - $PROJ_DIR$\Debug\Exe\CppUTest.a - $TOOLKIT_DIR$\lib\dl7M_tln.a - $PROJ_DIR$\..\..\include\CppUTest\JUnitTestOutput.h - $PROJ_DIR$\..\..\tests\AllocationInCppFile.cpp - $PROJ_DIR$\..\..\tests\AllocationInCFile.c - $PROJ_DIR$\..\..\tests\AllocLetTestFree.c - $PROJ_DIR$\..\..\tests\MemoryOperatorOverloadTest.cpp - $PROJ_DIR$\..\..\include\CppUTest\SimpleMutex.h - $PROJ_DIR$\..\..\tests\TestResultTest.cpp - $PROJ_DIR$\..\..\tests\TestRegistryTest.cpp - $PROJ_DIR$\..\..\tests\TestUTestMacro.cpp - $TOOLKIT_DIR$\inc\c\climits - $PROJ_DIR$\..\..\tests\AllTests.cpp - $PROJ_DIR$\..\..\tests\SimpleStringTest.cpp - $TOOLKIT_DIR$\inc\c\cctype - $TOOLKIT_DIR$\inc\c\ctime - $TOOLKIT_DIR$\inc\c\xlocale_c.h - $PROJ_DIR$\..\..\include\CppUTest\MemoryLeakDetectorNewMacros.h - $TOOLKIT_DIR$\inc\c\locale.h - $TOOLKIT_DIR$\inc\c\xlocale_lconv.h - $PROJ_DIR$\..\..\include\CppUTest\TestOutput.h - $TOOLKIT_DIR$\inc\c\DLib_Product_string.h - $PROJ_DIR$\Debug\Exe\CppUTestTest.out - $PROJ_DIR$\Debug\Obj\UtestPlatformTest.pbi - $TOOLKIT_DIR$\inc\c\yvals.h - $PROJ_DIR$\Debug\Obj\CppUTestTest.pbd - $PROJ_DIR$\Debug\Obj\tests.pbi - $TOOLKIT_DIR$\inc\c\stdio.h - $TOOLKIT_DIR$\inc\c\cstring - $PROJ_DIR$\Debug\Obj\UtestPlatformTest.o - $PROJ_DIR$\Debug\Obj\UtestTest.pbi - $PROJ_DIR$\Debug\Obj\SimpleStringTest.pbi - $PROJ_DIR$\Debug\Obj\SimpleStringTest.o - $PROJ_DIR$\Debug\Obj\UtestTest.o - $TOOLKIT_DIR$\inc\c\xlocaleuse.h - $TOOLKIT_DIR$\inc\c\ycheck.h - $PROJ_DIR$\..\..\include\CppUTest\TestRegistry.h - $PROJ_DIR$\..\..\include\CppUTest\TestTestingFixture.h - $PROJ_DIR$\..\..\include\CppUTest\TestFilter.h - $PROJ_DIR$\..\..\include\CppUTest\CommandLineTestRunner.h - $PROJ_DIR$\..\..\include\CppUTest\CommandLineArguments.h - $PROJ_DIR$\..\..\tests\SetPluginTest.cpp - $PROJ_DIR$\..\..\tests\PreprocessorTest.cpp - $PROJ_DIR$\..\..\tests\SimpleMutexTest.cpp - $PROJ_DIR$\..\..\tests\TestFailureNaNTest.cpp - $PROJ_DIR$\..\..\tests\TestFailureTest.cpp - $PROJ_DIR$\..\..\tests\TestHarness_cTest.cpp - $PROJ_DIR$\..\..\tests\TestFilterTest.cpp - $PROJ_DIR$\..\..\tests\TestOutputTest.cpp - $PROJ_DIR$\..\..\tests\TestHarness_cTestCFile.c - $PROJ_DIR$\..\..\tests\TestInstallerTest.cpp - $PROJ_DIR$\..\..\tests\TestMemoryAllocatorTest.cpp - $PROJ_DIR$\Debug\Obj\TestFailureNaNTest.o - $PROJ_DIR$\Debug\Obj\TestHarness_cTestCFile.o - $PROJ_DIR$\Debug\Obj\TestFailureTest.o - $PROJ_DIR$\..\..\tests\AllocLetTestFreeTest.cpp - $PROJ_DIR$\..\..\tests\CheatSheetTest.cpp - $PROJ_DIR$\..\..\tests\CommandLineTestRunnerTest.cpp - $PROJ_DIR$\..\..\tests\CommandLineArgumentsTest.cpp - $PROJ_DIR$\..\..\tests\MemoryLeakWarningTest.cpp - $PROJ_DIR$\..\..\tests\JUnitOutputTest.cpp - $PROJ_DIR$\..\..\tests\MemoryLeakDetectorTest.cpp - $PROJ_DIR$\..\..\tests\PluginTest.cpp - $PROJ_DIR$\..\..\include\CppUTest\TestHarness_c.h - $PROJ_DIR$\Debug\Obj\CheatSheetTest.pbi - $PROJ_DIR$\Debug\Obj\MemoryOperatorOverloadTest.o - $PROJ_DIR$\..\..\tests\AllocLetTestFree.h - $PROJ_DIR$\..\..\tests\AllocationInCppFile.h - $PROJ_DIR$\Debug\Obj\CommandLineArgumentsTest.pbi - $PROJ_DIR$\Debug\Obj\CommandLineTestRunnerTest.pbi - $PROJ_DIR$\Debug\Obj\MemoryLeakWarningTest.o - $PROJ_DIR$\Debug\Obj\JUnitOutputTest.o - $PROJ_DIR$\Debug\Obj\JUnitOutputTest.pbi - $PROJ_DIR$\Debug\Obj\MemoryOperatorOverloadTest.pbi - $PROJ_DIR$\Debug\Obj\MemoryLeakDetectorTest.pbi - $PROJ_DIR$\Debug\Obj\MemoryLeakWarningTest.pbi - $PROJ_DIR$\Debug\Obj\MemoryLeakDetectorTest.o - $PROJ_DIR$\Debug\Obj\AllocLetTestFree.pbi - $PROJ_DIR$\Debug\Obj\AllocationInCFile.pbi - $PROJ_DIR$\Debug\Obj\AllocLetTestFree.o - $PROJ_DIR$\Debug\Obj\AllocationInCppFile.pbi - $PROJ_DIR$\Debug\Obj\AllocLetTestFreeTest.pbi - $PROJ_DIR$\Debug\Obj\CommandLineTestRunnerTest.o - $PROJ_DIR$\Debug\Obj\CheatSheetTest.o - $PROJ_DIR$\Debug\Obj\CommandLineArgumentsTest.o - $PROJ_DIR$\..\..\include\CppUTest\MemoryLeakDetectorMallocMacros.h - $PROJ_DIR$\..\..\tests\AllocationInCFile.h - $PROJ_DIR$\Debug\Obj\SetPluginTest.o - $PROJ_DIR$\Debug\Obj\SimpleMutexTest.o - $PROJ_DIR$\Debug\Obj\CheatSheetTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestInstallerTest.pbi - $PROJ_DIR$\Debug\Obj\TestRegistryTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestOutputTest.o - $PROJ_DIR$\Debug\Obj\PreprocessorTest.pbi - $PROJ_DIR$\Debug\Obj\PreprocessorTest.o - $PROJ_DIR$\Debug\Obj\SetPluginTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestUTestMacro.pbi - $PROJ_DIR$\Debug\Obj\JUnitOutputTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestUTestMacro.o - $PROJ_DIR$\Debug\Obj\TestRegistryTest.o - $PROJ_DIR$\Debug\Obj\TestResultTest.pbi - $PROJ_DIR$\Debug\Obj\SetPluginTest.pbi - $PROJ_DIR$\Debug\Obj\CommandLineArgumentsTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestInstallerTest.o - $PROJ_DIR$\Debug\Obj\PluginTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestMemoryAllocatorTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestRegistryTest.pbi - $PROJ_DIR$\Debug\Obj\SimpleMutexTest.pbi - $PROJ_DIR$\Debug\Obj\MemoryLeakWarningTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestFailureNaNTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestHarness_cTestCFile.__cstat.et - $PROJ_DIR$\Debug\Obj\TestResultTest.o - $PROJ_DIR$\Debug\Obj\CommandLineTestRunnerTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestHarness_cTest.__cstat.et - $PROJ_DIR$\Debug\Obj\AllocationInCppFile.__cstat.et - $PROJ_DIR$\Debug\Obj\TestInstallerTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestMemoryAllocatorTest.o - $PROJ_DIR$\Debug\Obj\AllocLetTestFreeTest.__cstat.et - $PROJ_DIR$\Debug\Obj\MemoryLeakDetectorTest.__cstat.et - $PROJ_DIR$\Debug\Obj\AllocationInCFile.__cstat.et - $PROJ_DIR$\Debug\Obj\TestFailureTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestResultTest.__cstat.et - $PROJ_DIR$\Debug\Obj\PluginTest.pbi - $PROJ_DIR$\Debug\Obj\PreprocessorTest.__cstat.et - $PROJ_DIR$\Debug\Obj\MemoryOperatorOverloadTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestOutputTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestOutputTest.pbi - $PROJ_DIR$\Debug\Obj\SimpleMutexTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestFilterTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestUTestMacro.__cstat.et - $PROJ_DIR$\Debug\Obj\AllocLetTestFree.__cstat.et - $PROJ_DIR$\Debug\Obj\TestMemoryAllocatorTest.pbi - $PROJ_DIR$\Debug\Obj\PluginTest.o - $PROJ_DIR$\Debug\Obj\SimpleStringTest.__cstat.et - $PROJ_DIR$\Debug\Obj\AllTests.__cstat.et - $PROJ_DIR$\Debug\Obj\UtestPlatformTest.__cstat.et - $PROJ_DIR$\Debug\Obj\UtestTest.__cstat.et - $PROJ_DIR$\Debug\Obj\TestHarness_cTest.pbi - $PROJ_DIR$\Debug\Obj\TestHarness_cTest.o - $PROJ_DIR$\Debug\Obj\TestFilterTest.o - $PROJ_DIR$\Debug\Obj\TestFilterTest.pbi - $PROJ_DIR$\Debug\Obj\TestFailureTest.pbi - $PROJ_DIR$\Debug\Obj\TestHarness_cTestCFile.pbi - $PROJ_DIR$\Debug\Obj\TestFailureNaNTest.pbi - $PROJ_DIR$\tests\AllTests.cpp - - - $PROJ_DIR$\..\..\tests\UtestPlatformTest.cpp - - - BICOMP - 98 - - - ICCARM - 104 - - - __cstat - 210 - - - - - BICOMP - 110 52 1 99 27 60 28 15 95 32 2 50 63 29 109 17 34 37 66 19 41 3 103 30 112 113 33 26 56 20 22 86 24 4 6 21 5 23 11 35 115 43 53 54 36 47 16 14 48 51 18 64 38 39 40 102 42 44 45 62 46 96 61 7 8 49 10 25 9 114 89 90 91 93 94 0 92 111 - - - ICCARM - 114 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 95 115 113 112 111 35 17 - - - - - $PROJ_DIR$\..\..\tests\UtestTest.cpp - - - BICOMP - 105 - - - ICCARM - 108 - - - __cstat - 211 - - - - - BICOMP - 66 14 36 102 64 110 54 16 18 62 96 61 99 95 17 43 47 48 56 7 103 23 113 112 53 34 51 32 38 39 40 42 44 45 46 8 49 50 15 10 25 9 35 33 26 37 28 19 20 41 22 86 52 24 1 2 3 4 6 63 21 5 27 29 109 60 30 11 89 90 91 93 94 0 92 111 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 95 112 111 113 35 17 - - - - - $PROJ_DIR$\..\..\tests\tests.cpp - - - BICOMP - 101 - - - ICCARM - 55 - - - - - $PROJ_DIR$\..\..\tests\AllocationInCppFile.cpp - - - BICOMP - 155 - - - ICCARM - 67 - - - __cstat - 189 - - - - - BICOMP - 24 20 66 102 47 110 99 18 0 36 16 27 52 62 89 30 34 14 48 86 96 22 2 90 142 64 56 28 51 23 42 60 41 44 45 103 46 63 5 61 91 93 94 92 50 21 7 8 1 49 6 19 38 39 40 3 4 15 29 10 25 109 9 - - - ICCARM - 92 34 36 47 110 99 14 51 18 48 28 66 56 16 27 63 50 21 30 5 7 86 1 8 49 52 102 42 103 6 96 23 60 64 19 20 41 22 38 39 40 2 24 44 45 3 61 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 142 - - - - - $PROJ_DIR$\..\..\tests\AllocationInCFile.c - - - BICOMP - 153 - - - ICCARM - 69 - - - __cstat - 194 - - - - - BICOMP - 110 47 99 36 14 18 34 48 51 160 16 66 28 161 - - - ICCARM - 161 160 34 36 47 110 99 14 51 18 48 28 66 16 - - - - - $PROJ_DIR$\..\..\tests\AllocLetTestFree.c - - - BICOMP - 152 - - - ICCARM - 154 - - - __cstat - 205 - - - - - BICOMP - 110 99 14 18 16 36 66 48 51 34 47 28 141 - - - ICCARM - 36 34 47 110 99 14 51 18 48 28 66 16 141 - - - - - $PROJ_DIR$\..\..\tests\MemoryOperatorOverloadTest.cpp - - - BICOMP - 148 - - - ICCARM - 140 - - - __cstat - 199 - - - - - BICOMP - 99 7 92 56 110 36 138 54 16 51 0 30 113 111 43 47 66 64 102 62 96 61 89 17 31 112 53 34 14 48 18 32 38 39 40 42 44 45 103 46 8 49 52 60 90 65 95 35 142 161 33 26 37 28 19 20 41 22 86 24 1 2 3 4 15 6 63 50 21 5 27 23 91 93 94 11 29 10 25 109 9 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 65 31 95 111 113 35 17 112 142 138 161 - - - - - $PROJ_DIR$\..\..\tests\TestResultTest.cpp - - - BICOMP - 175 - - - ICCARM - 186 - - - __cstat - 196 - - - - - BICOMP - 99 86 26 56 66 23 20 24 110 21 33 16 48 22 4 6 5 17 95 34 32 37 28 19 41 52 1 2 3 15 63 50 27 60 10 25 9 54 35 43 53 36 47 14 51 18 64 38 39 40 102 42 44 45 103 62 46 96 61 7 8 49 29 109 30 11 89 90 91 93 94 0 92 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 35 95 17 - - - - - $PROJ_DIR$\..\..\tests\TestRegistryTest.cpp - - - BICOMP - 181 - - - ICCARM - 174 - - - __cstat - 166 - - - - - BICOMP - 14 21 34 110 103 20 24 18 66 86 99 23 30 53 48 22 4 6 5 63 29 109 60 32 95 43 54 36 47 16 51 19 41 52 1 2 3 15 50 27 111 33 26 37 56 28 64 38 39 40 102 42 44 45 62 46 96 61 7 8 49 10 25 9 113 11 89 90 91 93 94 0 92 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 111 113 95 - - - - - $PROJ_DIR$\..\..\tests\TestUTestMacro.cpp - - - BICOMP - 171 - - - ICCARM - 173 - - - __cstat - 204 - - - - - BICOMP - 56 110 48 99 66 7 53 0 34 14 18 64 102 62 96 61 89 112 43 54 36 47 16 51 32 38 39 40 42 44 45 103 46 8 52 60 90 5 111 95 33 26 37 28 19 20 41 22 86 24 1 2 3 4 15 6 63 50 21 27 23 91 93 94 92 113 11 49 29 10 25 109 9 30 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 95 112 111 113 - - - - - $PROJ_DIR$\..\..\tests\AllTests.cpp - - - BICOMP - 12 - - - ICCARM - 13 - - - __cstat - 209 - - - - - BICOMP - 95 20 24 110 99 53 14 21 66 18 86 23 11 34 48 22 4 6 5 115 43 54 36 47 16 51 19 41 52 1 2 3 15 63 50 27 60 10 25 9 113 33 32 26 37 56 28 64 38 39 40 102 42 44 45 103 62 46 96 61 7 8 49 29 109 30 114 89 90 91 93 94 0 92 - - - ICCARM - 114 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 95 115 113 - - - - - $PROJ_DIR$\..\..\tests\SimpleStringTest.cpp - - - BICOMP - 106 - - - ICCARM - 107 - - - __cstat - 208 - - - - - BICOMP - 66 86 99 30 33 20 24 110 21 7 103 31 26 56 16 48 22 4 6 5 63 29 109 60 32 35 34 37 28 19 41 52 1 2 3 15 50 8 49 65 43 53 54 36 47 14 51 18 64 38 39 40 102 42 44 45 62 46 96 61 27 23 10 25 9 17 11 89 90 91 93 94 0 92 95 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 35 95 17 65 31 - - - - - $PROJ_DIR$\Debug\Exe\CppUTestTest.out - - - ILINK - 72 69 67 154 68 13 158 159 157 146 151 145 140 207 169 162 163 107 127 129 214 213 128 178 191 167 174 186 173 104 108 75 73 71 74 70 76 - - - - - $PROJ_DIR$\..\..\tests\SetPluginTest.cpp - - - BICOMP - 176 - - - ICCARM - 162 - - - __cstat - 170 - - - - - BICOMP - 4 99 27 48 86 110 32 16 22 6 5 66 56 92 34 37 51 20 24 21 23 93 95 33 26 14 18 19 41 52 1 2 3 15 63 50 60 61 91 94 111 54 43 53 36 47 28 64 38 39 40 102 42 44 45 103 62 46 96 7 8 49 89 90 0 11 29 10 25 109 9 30 113 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 111 113 95 - - - - - $PROJ_DIR$\..\..\tests\PreprocessorTest.cpp - - - BICOMP - 168 - - - ICCARM - 169 - - - __cstat - 198 - - - - - BICOMP - 23 28 99 66 56 7 53 110 103 34 64 102 62 96 61 15 10 109 60 32 27 43 54 36 47 16 38 39 40 42 44 45 46 8 49 50 63 29 33 26 37 14 48 51 18 19 20 41 22 86 52 24 1 2 3 4 6 21 5 89 90 25 9 11 91 93 94 0 92 30 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 - - - - - $PROJ_DIR$\..\..\tests\SimpleMutexTest.cpp - - - BICOMP - 182 - - - ICCARM - 163 - - - __cstat - 202 - - - - - BICOMP - 66 62 96 61 110 99 53 64 102 34 51 56 7 103 17 35 43 54 36 47 16 14 48 18 32 38 39 40 42 44 45 46 8 49 50 63 29 109 60 30 82 33 26 37 28 19 20 41 22 86 52 24 1 2 3 4 15 6 21 5 27 23 10 25 9 11 89 90 91 93 94 0 92 95 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 82 35 95 17 - - - - - $PROJ_DIR$\..\..\tests\TestFailureNaNTest.cpp - - - BICOMP - 218 - - - ICCARM - 127 - - - __cstat - 184 - - - - - BICOMP - 99 103 51 110 34 56 7 66 17 53 64 102 62 96 61 23 35 43 54 36 47 16 14 48 18 32 38 39 40 42 44 45 46 8 49 50 15 10 25 9 95 33 26 37 28 19 20 41 22 86 52 24 1 2 3 4 6 63 21 5 27 60 29 109 30 11 89 90 91 93 94 0 92 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 95 35 17 - - - - - $PROJ_DIR$\..\..\tests\TestFailureTest.cpp - - - BICOMP - 216 - - - ICCARM - 129 - - - __cstat - 195 - - - - - BICOMP - 32 36 110 99 47 14 39 93 54 16 18 42 103 66 49 50 43 48 38 40 44 45 46 56 8 92 27 53 34 51 64 102 62 96 61 7 91 94 95 33 26 37 28 19 20 41 22 86 52 24 1 2 3 4 15 6 63 21 5 23 60 89 90 0 11 29 10 25 109 9 30 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 95 - - - - - $PROJ_DIR$\..\..\tests\TestHarness_cTest.cpp - - - BICOMP - 212 - - - ICCARM - 213 - - - __cstat - 188 - - - - - BICOMP - 99 36 33 10 9 16 66 32 39 3 63 110 15 54 112 47 28 26 38 40 50 27 25 111 31 34 37 64 56 86 4 6 21 5 103 23 113 95 11 35 14 48 51 18 43 53 19 20 41 22 52 24 1 2 102 42 44 45 62 46 96 61 7 8 49 29 109 60 30 138 89 90 91 93 94 0 92 17 - - - ICCARM - 138 34 36 47 110 99 14 51 18 48 28 66 56 16 11 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 111 113 95 112 35 17 31 - - - - - $PROJ_DIR$\..\..\tests\TestFilterTest.cpp - - - BICOMP - 215 - - - ICCARM - 214 - - - __cstat - 203 - - - - - BICOMP - 2 50 53 110 52 66 48 1 15 27 60 90 34 14 18 99 19 41 3 63 89 64 43 54 36 47 16 51 20 22 86 24 4 6 21 5 23 56 61 10 25 9 113 33 32 26 37 28 38 39 40 102 42 44 45 103 62 46 96 7 8 49 29 109 11 91 93 94 0 92 30 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 113 - - - - - $PROJ_DIR$\..\..\tests\TestOutputTest.cpp - - - BICOMP - 201 - - - ICCARM - 167 - - - __cstat - 200 - - - - - BICOMP - 62 43 96 61 47 110 48 23 16 64 102 54 36 14 18 56 99 7 103 66 17 53 34 51 32 38 39 40 42 44 45 46 8 15 10 25 9 95 35 33 26 37 28 19 20 41 22 86 52 24 1 2 3 4 6 63 50 21 5 27 49 29 109 60 30 11 89 90 91 93 94 0 92 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 95 35 17 - - - - - $PROJ_DIR$\..\..\tests\TestHarness_cTestCFile.c - - - BICOMP - 217 - - - ICCARM - 128 - - - __cstat - 185 - - - - - BICOMP - 47 48 28 99 66 36 110 34 14 17 16 51 18 138 - - - ICCARM - 138 34 36 47 110 99 14 51 18 48 28 66 16 17 - - - - - $PROJ_DIR$\..\..\tests\TestInstallerTest.cpp - - - BICOMP - 165 - - - ICCARM - 178 - - - __cstat - 190 - - - - - BICOMP - 99 86 51 54 16 110 66 23 90 32 36 20 24 21 64 43 47 22 4 6 5 53 34 14 48 18 19 41 52 1 2 3 15 63 50 27 60 89 0 111 33 26 37 56 28 38 39 40 102 42 44 45 103 62 46 96 61 7 8 49 91 93 94 92 11 29 10 25 109 9 30 113 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 111 113 - - - - - $PROJ_DIR$\..\..\tests\TestMemoryAllocatorTest.cpp - - - BICOMP - 206 - - - ICCARM - 191 - - - __cstat - 180 - - - - - BICOMP - 44 51 8 40 45 54 16 99 110 36 38 46 56 23 43 47 32 39 42 103 66 49 35 112 53 34 14 48 18 64 102 62 96 61 7 15 10 25 9 111 65 33 26 37 28 19 20 41 22 86 52 24 1 2 3 4 6 63 50 21 5 27 29 109 60 30 95 113 11 89 90 91 93 94 0 92 17 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 65 35 95 17 112 111 113 - - - - - $PROJ_DIR$\..\..\tests\AllocLetTestFreeTest.cpp - - - BICOMP - 156 - - - ICCARM - 68 - - - __cstat - 192 - - - - - BICOMP - 20 24 110 21 61 34 66 86 99 23 53 22 4 6 5 56 109 60 32 27 11 47 16 28 43 54 19 41 52 1 2 3 15 63 50 89 90 141 36 14 48 51 18 33 26 37 64 38 39 40 102 42 44 45 103 62 46 96 7 8 49 29 10 25 9 91 93 94 0 92 30 - - - ICCARM - 36 34 47 110 99 14 51 18 48 28 66 56 16 141 11 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 - - - - - $PROJ_DIR$\..\..\tests\CheatSheetTest.cpp - - - BICOMP - 139 - - - ICCARM - 158 - - - __cstat - 164 - - - - - BICOMP - 110 26 56 99 103 28 7 23 33 66 64 102 62 96 61 15 10 109 60 32 27 11 34 37 36 38 39 40 42 44 45 46 47 8 49 50 63 29 43 53 54 16 14 48 51 18 19 20 41 22 86 52 24 1 2 3 4 6 21 5 89 90 25 9 91 93 94 0 92 30 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 - - - - - $PROJ_DIR$\..\..\tests\CommandLineTestRunnerTest.cpp - - - BICOMP - 144 - - - ICCARM - 157 - - - __cstat - 187 - - - - - BICOMP - 25 48 99 33 28 62 96 61 110 16 64 102 32 54 26 56 7 15 10 9 17 111 35 34 37 36 38 39 40 42 44 45 103 46 66 47 8 23 95 114 112 77 43 53 14 51 18 19 20 41 22 86 52 24 1 2 3 4 6 63 50 21 5 27 49 29 109 60 30 113 11 89 90 91 93 94 0 92 115 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 114 95 115 113 111 112 77 35 17 - - - - - $PROJ_DIR$\..\..\tests\CommandLineArgumentsTest.cpp - - - BICOMP - 143 - - - ICCARM - 159 - - - __cstat - 177 - - - - - BICOMP - 66 46 110 38 99 56 32 43 47 40 44 45 8 93 54 36 16 39 42 103 49 50 92 27 111 53 34 28 64 102 62 96 61 7 91 94 113 115 33 26 37 14 48 51 18 19 20 41 22 86 52 24 1 2 3 4 15 6 63 21 5 23 60 89 90 0 11 29 10 25 109 9 30 95 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 115 95 113 111 - - - - - $PROJ_DIR$\..\..\tests\MemoryLeakWarningTest.cpp - - - BICOMP - 150 - - - ICCARM - 145 - - - __cstat - 183 - - - - - BICOMP - 32 36 92 110 99 47 14 39 52 82 54 16 18 42 103 66 49 64 17 31 43 48 38 40 44 45 46 56 8 60 90 95 112 53 34 51 102 62 96 61 7 89 0 113 111 37 65 138 33 26 28 19 20 41 22 86 24 1 2 3 4 15 6 63 50 21 5 27 23 91 93 94 11 29 10 25 109 9 30 35 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 111 113 95 31 65 112 138 82 35 17 - - - - - $PROJ_DIR$\..\..\tests\JUnitOutputTest.cpp - - - BICOMP - 147 - - - ICCARM - 146 - - - __cstat - 172 - - - - - BICOMP - 42 110 16 50 91 34 54 49 103 66 36 32 99 39 47 43 38 40 44 45 46 56 8 61 94 17 53 28 64 102 62 96 7 93 92 27 77 35 33 26 37 14 48 51 18 19 20 41 22 86 52 24 1 2 3 4 15 6 63 21 5 23 60 89 90 0 95 11 29 10 25 109 9 30 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 77 95 35 17 - - - - - $PROJ_DIR$\..\..\tests\MemoryLeakDetectorTest.cpp - - - BICOMP - 149 - - - ICCARM - 151 - - - __cstat - 193 - - - - - BICOMP - 47 16 102 99 43 64 25 110 48 62 96 61 17 54 36 51 56 7 15 10 9 65 53 34 66 14 18 32 38 39 40 42 44 45 103 46 8 49 23 31 35 33 26 37 28 19 20 41 22 86 52 24 1 2 3 4 6 63 50 21 5 27 29 109 60 30 11 89 90 91 93 94 0 92 95 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 31 65 35 95 17 - - - - - $PROJ_DIR$\..\..\tests\PluginTest.cpp - - - BICOMP - 197 - - - ICCARM - 207 - - - __cstat - 179 - - - - - BICOMP - 99 110 48 56 7 60 33 103 63 29 109 32 26 14 18 66 64 102 62 96 61 30 95 34 37 51 36 38 39 40 42 44 45 46 47 8 49 50 111 112 43 53 54 16 28 19 20 41 22 86 52 24 1 2 3 4 15 6 21 5 27 23 10 25 9 113 11 89 90 91 93 94 0 92 - - - ICCARM - 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 111 113 95 112 - - - - - [ROOT_NODE] - - - ILINK - 97 - - - - - $PROJ_DIR$\tests\AllTests.cpp - - - BICOMP - 12 - - - ICCARM - 13 - - - - - BICOMP - 40 45 95 44 8 99 53 66 38 46 56 110 11 34 32 36 39 42 103 47 49 50 23 115 43 54 16 28 48 64 102 62 96 61 7 15 10 25 9 113 33 26 37 14 51 18 19 20 41 22 86 52 24 1 2 3 4 6 63 21 5 27 60 29 109 30 114 89 90 91 93 94 0 92 - - - ICCARM - 114 11 34 36 47 110 99 14 51 18 48 28 66 56 16 33 32 64 19 20 41 22 86 1 38 39 40 2 52 102 42 24 44 45 103 6 96 3 63 50 21 61 5 27 7 8 49 23 60 62 4 46 89 29 10 25 9 109 91 15 93 94 90 0 43 53 26 54 37 92 30 95 115 113 - - - - - $PROJ_DIR$\..\..\tests\UtestPlatformTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\UtestTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\AllocationInCppFile.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\AllocationInCFile.c - C-STAT - - - $PROJ_DIR$\..\..\tests\AllocLetTestFree.c - C-STAT - - - $PROJ_DIR$\..\..\tests\MemoryOperatorOverloadTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\TestResultTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\TestRegistryTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\TestUTestMacro.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\AllTests.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\SimpleStringTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\SetPluginTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\PreprocessorTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\SimpleMutexTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\TestFailureNaNTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\TestFailureTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\TestHarness_cTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\TestFilterTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\TestOutputTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\TestHarness_cTestCFile.c - C-STAT - - - $PROJ_DIR$\..\..\tests\TestInstallerTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\TestMemoryAllocatorTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\AllocLetTestFreeTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\CheatSheetTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\CommandLineTestRunnerTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\CommandLineArgumentsTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\MemoryLeakWarningTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\JUnitOutputTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\MemoryLeakDetectorTest.cpp - C-STAT - - - $PROJ_DIR$\..\..\tests\PluginTest.cpp - C-STAT - - - - Release - - - [MULTI_TOOL] - ILINK - - - [REBUILD_ALL] - - - - - diff --git a/platforms/iar/CppUTestTest.ewd b/platforms/iar/CppUTestTest.ewd index 68ed95334..1c6f889c9 100644 --- a/platforms/iar/CppUTestTest.ewd +++ b/platforms/iar/CppUTestTest.ewd @@ -12,7 +12,7 @@ C-SPY 2 - 26 + 28 1 1 - + + @@ -278,18 +282,47 @@ - CMSISDAP_ID + CADI_ID 2 - 2 + 0 1 1 + + + + + + + + CMSISDAP_ID + 2 + + 4 + 1 + 1 + + + @@ -520,15 +561,15 @@ IJET_ID 2 - 6 + 8 1 1 + + JLINK_ID 2 - 15 + 16 1 1 + - @@ -1193,7 +1195,7 @@ STLINK_ID 2 - 2 + 3 1 1 + + + + + + + + + + + + + + + + + + @@ -1253,10 +1328,10 @@ - XDS100_ID + TIFET_ID 2 - 2 + 1 1 1 + + + + + + + + + + + + + + XDS100_ID + 2 + + 5 + 1 + 1 + + + - - - - - $TOOLKIT_DIR$\plugins\middleware\HCCWare\HCCWare.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\AVIX\AVIX.ENU.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\CMX\CmxArmPlugin.ENU.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\CMX\CmxTinyArmPlugin.ENU.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\embOS\embOSPlugin.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\MQX\MQXRtosPlugin.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\OpenRTOS\OpenRTOSPlugin.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\Quadros\Quadros_EWB7_Plugin.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\SafeRTOS\SafeRTOSPlugin.ewplugin - 0 - - - $TOOLKIT_DIR$\plugins\rtos\ThreadX\ThreadXArmPlugin.ENU.ewplugin - 0 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $TOOLKIT_DIR$\plugins\middleware\HCCWare\HCCWare.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\middleware\PercepioTraceExporter\PercepioTraceExportPlugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\AVIX\AVIX.ENU.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\CMX\CmxArmPlugin.ENU.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\CMX\CmxTinyArmPlugin.ENU.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\embOS\embOSPlugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\MQX\MQXRtosPlugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\OpenRTOS\OpenRTOSPlugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\Quadros\Quadros_EWB7_Plugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\SafeRTOS\SafeRTOSPlugin.ewplugin + 0 + + + $TOOLKIT_DIR$\plugins\rtos\ThreadX\ThreadXArmPlugin.ENU.ewplugin + 0 + + $TOOLKIT_DIR$\plugins\rtos\TI-RTOS\tirtosplugin.ewplugin 0 @@ -1359,10 +1627,6 @@ $EW_DIR$\common\plugins\Orti\Orti.ENU.ewplugin 0 - - $EW_DIR$\common\plugins\SymList\SymList.ENU.ewplugin - 1 - $EW_DIR$\common\plugins\uCProbe\uCProbePlugin.ENU.ewplugin 0 @@ -1379,7 +1643,7 @@ C-SPY 2 - 26 + 28 1 0 - + + @@ -1645,18 +1913,47 @@ - CMSISDAP_ID + CADI_ID 2 - 2 + 0 1 0 + + + + + + + + CMSISDAP_ID + 2 + + 4 + 1 + 0 + + + @@ -1887,15 +2192,15 @@ IJET_ID 2 - 6 + 8 1 0 + + JLINK_ID 2 - 15 + 16 1 0 + - @@ -2560,7 +2826,7 @@ STLINK_ID 2 - 2 + 3 1 0 + + + + + + + + + + + + + + + + + + @@ -2620,10 +2959,10 @@ - XDS100_ID + TIFET_ID 2 - 2 + 1 1 0 + + + + + + + + + + + + + + XDS100_ID + 2 + + 5 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2666,6 +3194,10 @@ $TOOLKIT_DIR$\plugins\middleware\HCCWare\HCCWare.ewplugin 0 + + $TOOLKIT_DIR$\plugins\middleware\PercepioTraceExporter\PercepioTraceExportPlugin.ewplugin + 0 + $TOOLKIT_DIR$\plugins\rtos\AVIX\AVIX.ENU.ewplugin 0 @@ -2726,10 +3258,6 @@ $EW_DIR$\common\plugins\Orti\Orti.ENU.ewplugin 0 - - $EW_DIR$\common\plugins\SymList\SymList.ENU.ewplugin - 1 - $EW_DIR$\common\plugins\uCProbe\uCProbePlugin.ENU.ewplugin 0 diff --git a/platforms/iar/CppUTestTest.ewp b/platforms/iar/CppUTestTest.ewp index f057ad905..c1283fe9e 100644 --- a/platforms/iar/CppUTestTest.ewp +++ b/platforms/iar/CppUTestTest.ewp @@ -12,7 +12,7 @@ General 3 - 22 + 24 1 1 - - - + + + + + + @@ -249,7 +262,7 @@ @@ -954,7 +975,7 @@ General 3 - 22 + 24 1 0 - - - + + + + + + @@ -1573,7 +1607,7 @@ ILINK 0 - 16 + 18 1 0 + + @@ -1894,98 +1936,116 @@ passing - $PROJ_DIR$\..\..\tests\AllocationInCFile.c + $PROJ_DIR$\..\..\tests\CppUTest\AllocationInCFile.c - $PROJ_DIR$\..\..\tests\AllocationInCppFile.cpp + $PROJ_DIR$\..\..\tests\CppUTest\AllocationInCppFile.cpp - $PROJ_DIR$\..\..\tests\AllocLetTestFree.c + $PROJ_DIR$\..\..\tests\CppUTest\AllocLetTestFree.c - $PROJ_DIR$\..\..\tests\AllocLetTestFreeTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\AllocLetTestFreeTest.cpp - $PROJ_DIR$\..\..\tests\CheatSheetTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\CheatSheetTest.cpp - $PROJ_DIR$\..\..\tests\CommandLineArgumentsTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\CommandLineArgumentsTest.cpp - $PROJ_DIR$\..\..\tests\CommandLineTestRunnerTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\CommandLineTestRunnerTest.cpp - $PROJ_DIR$\..\..\tests\JUnitOutputTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\CompatabilityTests.cpp - $PROJ_DIR$\..\..\tests\MemoryLeakDetectorTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\DummyMemoryLeakDetector.cpp - $PROJ_DIR$\..\..\tests\MemoryLeakWarningTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\JUnitOutputTest.cpp - $PROJ_DIR$\..\..\tests\MemoryOperatorOverloadTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\MemoryLeakDetectorTest.cpp - $PROJ_DIR$\..\..\tests\PluginTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\MemoryLeakWarningTest.cpp - $PROJ_DIR$\..\..\tests\PreprocessorTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\MemoryOperatorOverloadTest.cpp - $PROJ_DIR$\..\..\tests\SetPluginTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\PluginTest.cpp - $PROJ_DIR$\..\..\tests\SimpleMutexTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\PreprocessorTest.cpp - $PROJ_DIR$\..\..\tests\SimpleStringTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\SetPluginTest.cpp - $PROJ_DIR$\..\..\tests\TestFailureNaNTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\SimpleMutexTest.cpp - $PROJ_DIR$\..\..\tests\TestFailureTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\SimpleStringCacheTest.cpp - $PROJ_DIR$\..\..\tests\TestFilterTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\SimpleStringTest.cpp - $PROJ_DIR$\..\..\tests\TestHarness_cTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\TeamCityOutputTest.cpp - $PROJ_DIR$\..\..\tests\TestHarness_cTestCFile.c + $PROJ_DIR$\..\..\tests\CppUTest\TestFailureNaNTest.cpp - $PROJ_DIR$\..\..\tests\TestInstallerTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\TestFailureTest.cpp - $PROJ_DIR$\..\..\tests\TestMemoryAllocatorTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\TestFilterTest.cpp - $PROJ_DIR$\..\..\tests\TestOutputTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\TestHarness_cTest.cpp - $PROJ_DIR$\..\..\tests\TestRegistryTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\TestHarness_cTestCFile.c - $PROJ_DIR$\..\..\tests\TestResultTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\TestInstallerTest.cpp - $PROJ_DIR$\..\..\tests\TestUTestMacro.cpp + $PROJ_DIR$\..\..\tests\CppUTest\TestMemoryAllocatorTest.cpp - $PROJ_DIR$\..\..\tests\UtestPlatformTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\TestOutputTest.cpp - $PROJ_DIR$\..\..\tests\UtestTest.cpp + $PROJ_DIR$\..\..\tests\CppUTest\TestRegistryTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTest\TestResultTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTest\TestUTestMacro.cpp + + + $PROJ_DIR$\..\..\tests\CppUTest\TestUTestStringMacro.cpp + + + $PROJ_DIR$\..\..\tests\CppUTest\UtestPlatformTest.cpp + + + $PROJ_DIR$\..\..\tests\CppUTest\UtestTest.cpp warnings - $PROJ_DIR$\tests\AllTests.cpp + $PROJ_DIR$\..\..\tests\CppUTest\AllTests.cpp + + + $PROJ_DIR$\tests\iar_argc_argv.c diff --git a/platforms/iar/CppUTestTest.ewt b/platforms/iar/CppUTestTest.ewt deleted file mode 100644 index 64dba0e4f..000000000 --- a/platforms/iar/CppUTestTest.ewt +++ /dev/null @@ -1,2215 +0,0 @@ - - - - 2 - - Debug - - ARM - - 1 - - C-STAT - 1 - - 1 - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - RuntimeChecking - 0 - - 2 - 1 - 1 - - - - - - - - - - - - - - - - - - - - - - Release - - ARM - - 0 - - C-STAT - 1 - - 1 - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - RuntimeChecking - 0 - - 2 - 1 - 0 - - - - - - - - - - - - - - - - - - - - - - tests - - failing - - - passing - - $PROJ_DIR$\..\..\tests\AllocationInCFile.c - - - $PROJ_DIR$\..\..\tests\AllocationInCppFile.cpp - - - $PROJ_DIR$\..\..\tests\AllocLetTestFree.c - - - $PROJ_DIR$\..\..\tests\AllocLetTestFreeTest.cpp - - - $PROJ_DIR$\..\..\tests\CheatSheetTest.cpp - - - $PROJ_DIR$\..\..\tests\CommandLineArgumentsTest.cpp - - - $PROJ_DIR$\..\..\tests\CommandLineTestRunnerTest.cpp - - - $PROJ_DIR$\..\..\tests\JUnitOutputTest.cpp - - - $PROJ_DIR$\..\..\tests\MemoryLeakDetectorTest.cpp - - - $PROJ_DIR$\..\..\tests\MemoryLeakWarningTest.cpp - - - $PROJ_DIR$\..\..\tests\MemoryOperatorOverloadTest.cpp - - - $PROJ_DIR$\..\..\tests\PluginTest.cpp - - - $PROJ_DIR$\..\..\tests\PreprocessorTest.cpp - - - $PROJ_DIR$\..\..\tests\SetPluginTest.cpp - - - $PROJ_DIR$\..\..\tests\SimpleMutexTest.cpp - - - $PROJ_DIR$\..\..\tests\SimpleStringTest.cpp - - - $PROJ_DIR$\..\..\tests\TestFailureNaNTest.cpp - - - $PROJ_DIR$\..\..\tests\TestFailureTest.cpp - - - $PROJ_DIR$\..\..\tests\TestFilterTest.cpp - - - $PROJ_DIR$\..\..\tests\TestHarness_cTest.cpp - - - $PROJ_DIR$\..\..\tests\TestHarness_cTestCFile.c - - - $PROJ_DIR$\..\..\tests\TestInstallerTest.cpp - - - $PROJ_DIR$\..\..\tests\TestMemoryAllocatorTest.cpp - - - $PROJ_DIR$\..\..\tests\TestOutputTest.cpp - - - $PROJ_DIR$\..\..\tests\TestRegistryTest.cpp - - - $PROJ_DIR$\..\..\tests\TestResultTest.cpp - - - $PROJ_DIR$\..\..\tests\TestUTestMacro.cpp - - - $PROJ_DIR$\..\..\tests\UtestPlatformTest.cpp - - - $PROJ_DIR$\..\..\tests\UtestTest.cpp - - - - warnings - - - $PROJ_DIR$\tests\AllTests.cpp - - - - - diff --git a/platforms/iar/CppUTestTest.icf b/platforms/iar/CppUTestTest.icf index 3384b6152..23bfb64c3 100644 --- a/platforms/iar/CppUTestTest.icf +++ b/platforms/iar/CppUTestTest.icf @@ -5,7 +5,7 @@ define symbol __ICFEDIT_intvec_start__ = 0x00000000; /*-Memory Regions-*/ define symbol __ICFEDIT_region_IROM1_start__ = 0x00000080; -define symbol __ICFEDIT_region_IROM1_end__ = 0x0007FFFF; +define symbol __ICFEDIT_region_IROM1_end__ = 0x000FFFFF; define symbol __ICFEDIT_region_IROM2_start__ = 0x0; define symbol __ICFEDIT_region_IROM2_end__ = 0x0; define symbol __ICFEDIT_region_EROM1_start__ = 0x0; @@ -25,13 +25,13 @@ define symbol __ICFEDIT_region_ERAM2_end__ = 0x0; define symbol __ICFEDIT_region_ERAM3_start__ = 0x0; define symbol __ICFEDIT_region_ERAM3_end__ = 0x0; /*-Sizes-*/ -define symbol __ICFEDIT_size_cstack__ = 0x600; +define symbol __ICFEDIT_size_cstack__ = 0x2000; define symbol __ICFEDIT_size_svcstack__ = 0x100; define symbol __ICFEDIT_size_irqstack__ = 0x100; define symbol __ICFEDIT_size_fiqstack__ = 0x100; define symbol __ICFEDIT_size_undstack__ = 0x100; define symbol __ICFEDIT_size_abtstack__ = 0x100; -define symbol __ICFEDIT_size_heap__ = 0x8000; +define symbol __ICFEDIT_size_heap__ = 0x10000; /**** End of ICF editor section. ###ICF###*/ define memory mem with size = 4G; diff --git a/platforms/iar/tests/iar_argc_argv.c b/platforms/iar/tests/iar_argc_argv.c new file mode 100644 index 000000000..e12de9d41 --- /dev/null +++ b/platforms/iar/tests/iar_argc_argv.c @@ -0,0 +1,14 @@ +#define NUM_ARGS 2 + +static char __argvbuf0[] = {"exe"}; +static char __argvbuf1[] = {"-v"}; + +static int __argc = NUM_ARGS; +static char * __argv[NUM_ARGS] = { __argvbuf0, __argvbuf1 }; + +void __iar_argc_argv(void) +{ + // setup R0 (argc) and R1 (argv) arguments to main (see cmain.s) + asm volatile ("MOVS R1, %0" : : "r" (__argv)); + asm volatile ("MOVS R0, %0" : : "r" (__argc)); +} diff --git a/platforms_examples/armcc/AT91SAM7A3/tests/main.cpp b/platforms_examples/armcc/AT91SAM7A3/tests/main.cpp index e1eac674c..8199883d5 100644 --- a/platforms_examples/armcc/AT91SAM7A3/tests/main.cpp +++ b/platforms_examples/armcc/AT91SAM7A3/tests/main.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/platforms_examples/armcc/LPC1768/tests/main.cpp b/platforms_examples/armcc/LPC1768/tests/main.cpp index b8dd10eec..254b171ae 100644 --- a/platforms_examples/armcc/LPC1768/tests/main.cpp +++ b/platforms_examples/armcc/LPC1768/tests/main.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/platforms_examples/armcc/LPC1833/tests/main.cpp b/platforms_examples/armcc/LPC1833/tests/main.cpp index 90f317a05..f1299259f 100644 --- a/platforms_examples/armcc/LPC1833/tests/main.cpp +++ b/platforms_examples/armcc/LPC1833/tests/main.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/scripts/InstallScripts.sh b/scripts/InstallScripts.sh index 54b85e3a9..1c632e718 100755 --- a/scripts/InstallScripts.sh +++ b/scripts/InstallScripts.sh @@ -3,7 +3,8 @@ FirstLetter=${0:0:1} if [[ $FirstLetter == "/" ]] ; then CPPUTEST_HOME=${0%/scripts/*} else - CPPUTEST_HOME="$(pwd)/${0%/scripts/*}" + file=$(pwd)/${0} + CPPUTEST_HOME="${file%/scripts/*}" fi EXE_DIR=${EXE_DIR:-/usr/local/bin} diff --git a/scripts/README.txt b/scripts/README.txt index 8840b1b0a..c6adab6f0 100644 --- a/scripts/README.txt +++ b/scripts/README.txt @@ -1,5 +1,5 @@ The New*.sh scripts are helpful for creating the initial files for a new class... - NewClass.sh - for TTDing a new C++ class + NewClass.sh - for TDDing a new C++ class NewInterface.sh - for TDDing a new interface along with its Mock NewCModule.sh - for TDDing a C module NewCmiModule.sh - for TDDing a C module where there will be multiple @@ -14,7 +14,7 @@ Like this: You might have to add the execute privilege to the shell scripts. Like this: - chmod *.sh + chmod +x *.sh Using NewClass for example: cd to the directory where you want the files located diff --git a/scripts/VS2010Templates/CppUTest_VS2010.props b/scripts/VS2010Templates/CppUTest_VS2010.props index fad877723..7655261a1 100644 --- a/scripts/VS2010Templates/CppUTest_VS2010.props +++ b/scripts/VS2010Templates/CppUTest_VS2010.props @@ -2,9 +2,9 @@ - $(CPPUTEST_HOME)\include;$(CPPUTEST_HOME)\include\CppUTestExt\CppUTestGTest;$(CPPUTEST_HOME)\include\CppUTestExt\CppUTestGMock;$(CPPUTEST_HOME)\include\Platforms\VisualCpp + $(CPPUTEST_HOME)\include;$(CPPUTEST_HOME)\include\CppUTestExt\CppUTestGTest;$(CPPUTEST_HOME)\include\CppUTestExt\CppUTestGMock $(CPPUTEST_HOME)\lib - $(CPPUTEST_HOME)\include\Platforms\VisualCpp\Platform.h;$(CPPUTEST_HOME)\include\CppUTest\MemoryLeakDetectorMallocMacros.h; + $(CPPUTEST_HOME)\include\CppUTest\MemoryLeakDetectorMallocMacros.h; CppUTest.lib diff --git a/scripts/appveyor_ci_build.ps1 b/scripts/appveyor_ci_build.ps1 index 238688545..5f33eacd6 100644 --- a/scripts/appveyor_ci_build.ps1 +++ b/scripts/appveyor_ci_build.ps1 @@ -2,6 +2,8 @@ # Load functions from the helper file . (Join-Path (Split-Path $MyInvocation.MyCommand.Path) 'appveyor_helpers.ps1') +mkdir cpputest_build + function Invoke-BuildCommand($command, $directory = '.') { $command_wrapped = "$command;`$err = `$?" @@ -27,7 +29,7 @@ function Invoke-CygwinCommand($command, $directory = '.') $cygwin_directory = (. "${cygwin_bin}\cygpath.exe" (Resolve-Path $directory)) $command_wrapped = "${cygwin_bin}\bash.exe --login -c 'cd $cygwin_directory ; $command'" - + Write-Host "Executing <$command> in <$cygwin_directory>" Invoke-Expression $command_wrapped @@ -73,10 +75,18 @@ switch -Wildcard ($env:Platform) { $mingw_path = Get-MinGWBin + if ($env:Platform -like 'MinGWClang*') + { + $toolchain_filename = Get-ClangToolchainFilename + $toolchain_path = (Join-Path (Split-Path $MyInvocation.MyCommand.Path) "..\cmake\Toolchains\$toolchain_filename") + $toolchain = "-DCMAKE_TOOLCHAIN_FILE=$toolchain_path -DCPPUTEST_WERROR=OFF" + } + # Add mingw to the path Add-PathFolder $mingw_path - Invoke-BuildCommand "cmake -G 'MinGW Makefiles' .." 'cpputest_build' + Invoke-BuildCommand "cmake --version" + Invoke-BuildCommand "cmake -G 'MinGW Makefiles' -DCMAKE_CXX_STANDARD=17 $toolchain .." 'cpputest_build' Invoke-BuildCommand "mingw32-make all" 'cpputest_build' Remove-PathFolder $mingw_path diff --git a/scripts/appveyor_ci_test.ps1 b/scripts/appveyor_ci_test.ps1 index 423395117..830542932 100644 --- a/scripts/appveyor_ci_test.ps1 +++ b/scripts/appveyor_ci_test.ps1 @@ -37,8 +37,12 @@ function Invoke-Tests($executable) { # Run tests and output the results using junit $TestCommand = "$executable -ojunit" - Write-Host $TestCommand + Write-Host $TestCommand -NoNewline Invoke-Expression $TestCommand + Write-Host " - return code: $LASTEXITCODE" + if ($LASTEXITCODE -lt 0) { + Write-Error "Runtime Exception during test execution" + } } function Invoke-CygwinTests($executable) @@ -94,10 +98,10 @@ switch -Wildcard ($env:Platform) { $mingw_path = Get-MinGWBin - Add-PathFolder $mingw_path - Invoke-Tests '.\cpputest_build\tests\CppUTestTests.exe' + Set-Path "$mingw_path;C:\Windows;C:\Windows\System32" + Invoke-Tests '.\cpputest_build\tests\CppUTest\CppUTestTests.exe' Invoke-Tests '.\cpputest_build\tests\CppUTestExt\CppUTestExtTests.exe' - Remove-PathFolder $mingw_path + Restore-Path } default diff --git a/scripts/appveyor_helpers.ps1 b/scripts/appveyor_helpers.ps1 index 8f6e0dd67..af08f21ca 100644 --- a/scripts/appveyor_helpers.ps1 +++ b/scripts/appveyor_helpers.ps1 @@ -18,6 +18,16 @@ function Get-MinGWBin() { } } +# Helper function to provide the toolchain file for clang +function Get-ClangToolchainFilename() { + if ($env:Platform -like '*64') { + Write-Output 'clang+mingw-win64.toolchain.cmake' + } + else { + Write-Output 'clang+mingw-win32.toolchain.cmake' + } +} + # Helper function to provide the bin-folder path to cygwin function Get-CygwinBin() { if ($env:Platform -like '*64') { @@ -74,3 +84,13 @@ function Remove-PathFolder($folder) $env:Path = $pathFolders -join ";" } +function Set-Path($newPath) +{ + $env:RestorePath = $env:Path + $env:Path = $newPath +} + +function Restore-Path() +{ + $env:Path = $env:RestorePath +} diff --git a/scripts/create_docker_images_and_containers b/scripts/create_docker_images_and_containers new file mode 100755 index 000000000..ab4ec05b6 --- /dev/null +++ b/scripts/create_docker_images_and_containers @@ -0,0 +1,37 @@ +#!/bin/bash +#$1 is the container name + +checkForCppUTestToolsEnvVariable() { + if [ -z "$CPPUTEST_HOME" ] ; then + echo "CPPUTEST_HOME not set. You must set CPPUTEST_HOME to the top level CppUTest directory" + exit 1 + fi + if [ ! -d "$CPPUTEST_HOME" ] ; then + echo "CPPUTEST_HOME not set to a directory. You must set CPPUTEST_HOME to the top level CppUTest directory" + exit 2 + fi +} + +checkForImageNameParameter() { + if [ -z "$container" ] ; then + echo "Container name parameter not set. Check the docker directory. It should be the extension of the Dockerfile. e.g. ubuntu" + exit 1 + fi + if [ ! -f "$CPPUTEST_HOME/docker/Dockerfile.$container" ] ; then + echo "The Dockerfile docker/Dockerfile.$container doesn't exist. Typo?" + exit 2 + fi +} + + +container=$1 +checkForCppUTestToolsEnvVariable +checkForImageNameParameter + +docker build -f $CPPUTEST_HOME/docker/Dockerfile.$container --tag cpputest/$container:latest . +docker container rm cpputest_$container +docker create -it -v$CPPUTEST_HOME:/cpputest -e "CPPUTEST_HOME=/cpputest" --name cpputest_$container cpputest/$container:latest + +echo "You can run your container through: docker start -i cpputest_. E.g. docker start -i cpputest_$container" + + diff --git a/scripts/dos_build_test.sh b/scripts/dos_build_test.sh new file mode 100755 index 000000000..cf10fe5a9 --- /dev/null +++ b/scripts/dos_build_test.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail +# get current dir even if the script is sourced +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" + +export CPPUTEST_HOME="$DIR/../" +export WATCOM=./watcom +export PATH=$PATH:$WATCOM/binl + +if [ ! -d "$WATCOM" ]; then + git clone https://github.com/cpputest/watcom-compiler.git "$WATCOM" +fi + +make -f "$CPPUTEST_HOME/platforms/Dos/Makefile" clean +make -f "$CPPUTEST_HOME/platforms/Dos/Makefile" +make -f "$CPPUTEST_HOME/platforms/Dos/Makefile" test diff --git a/scripts/filterGcov.sh b/scripts/filterGcov.sh index 2f6ec1d41..b3ff67fee 100755 --- a/scripts/filterGcov.sh +++ b/scripts/filterGcov.sh @@ -22,7 +22,7 @@ getRidOfCruft() { sed '-e s/^Lines.*://g' \ '-e s/^[0-9]\./ &/g' \ '-e s/^[0-9][0-9]\./ &/g' \ - '-e s/of.*File/ /g' \ + '-e s/of.\w[^'File']*File/ /g' \ "-e s/'//g" \ '-e s/^.*\/usr\/.*$//g' \ '-e s/^.*\.$//g' diff --git a/scripts/templates/ProjectTemplate/Project.cproject b/scripts/templates/ProjectTemplate/Project.cproject index df56e1665..a3fb56605 100644 --- a/scripts/templates/ProjectTemplate/Project.cproject +++ b/scripts/templates/ProjectTemplate/Project.cproject @@ -30,6 +30,7 @@ @@ -37,12 +38,14 @@ diff --git a/scripts/templates/ProjectTemplate/ProjectMakefile b/scripts/templates/ProjectTemplate/ProjectMakefile index 68747610f..f426016c8 100644 --- a/scripts/templates/ProjectTemplate/ProjectMakefile +++ b/scripts/templates/ProjectTemplate/ProjectMakefile @@ -32,7 +32,6 @@ INCLUDE_DIRS =\ include \ include/* \ $(CPPUTEST_HOME)/include/ \ - $(CPPUTEST_HOME)/include/Platforms/Gcc\ mocks CPPUTEST_WARNINGFLAGS = -Wall -Werror -Wswitch-default diff --git a/scripts/travis_ci_build.sh b/scripts/travis_ci_build.sh deleted file mode 100755 index 0d5efa9b4..000000000 --- a/scripts/travis_ci_build.sh +++ /dev/null @@ -1,86 +0,0 @@ -#!/bin/bash -# Script run in the travis CI -set -ex - -if [ "x$BUILD" = "xautotools" ]; then - autoreconf -i .. - ../configure - echo "CONFIGURATION DONE. Compiling now." - make check_all - - make dist - make dist-zip - - if [ "x$CXX" = "xg++" ]; then - echo "Deploy please" -# gem install travis_github_deployer -# cd .. && travis_github_deployer -v || exit 1 - fi; -fi - -if [ "x$BUILD" = "xcmake" ]; then - cmake .. -DCMAKE_BUILD_TYPE=$CMAKE_BUILD_TYPE - make - ctest -V - - if [ "x$CXX" != "xg++" ]; then - cmake .. -DC++11=ON -DCMAKE_BUILD_TYPE=$CMAKE_BUILD_TYPE - make - ctest -V - fi -fi - -if [ "x$BUILD" = "xautotools_gtest" ]; then - autoreconf -i .. - ../configure - - make check_gtest -fi - -if [ "x$BUILD" = "xcmake_gtest" ]; then - wget https://googlemock.googlecode.com/files/gmock-1.6.0.zip - unzip gmock-1.6.0.zip -d $TRAVIS_BUILD_DIR - cd $TRAVIS_BUILD_DIR/gmock-1.6.0 - ./configure && make - cd - - - export GMOCK_HOME=$TRAVIS_BUILD_DIR/gmock-1.6.0 - export GTEST_HOME=$TRAVIS_BUILD_DIR/gmock-1.6.0/gtest - cmake .. -DGMOCK=ON - make - ctest -V -fi - -if [ "x$BUILD" = "xtest_report" ]; then - autoreconf -i .. - ../configure - make check - ./CppUTestTests -ojunit - ./CppUTestExtTests -ojunit - cp ../scripts/generate_junit_report_ant.xml . - ant -f generate_junit_report_ant.xml -fi - -if [ "x$BUILD" = "xcmake_coverage" ]; then - pip install cpp-coveralls --user `whoami` - - cmake .. -DCMAKE_BUILD_TYPE=$CMAKE_BUILD_TYPE -DCOVERAGE=ON -DLONGLONG=ON - make - ctest - - coveralls -b . -r .. -i "src" -i "include" --gcov-options="-lbc" || true -fi - -if [ "x$BUILD" = "xmake_dos" ]; then - wget ftp://ftp.openwatcom.org/pub/open-watcom-c-linux-1.9 -O /tmp/watcom.zip - mkdir -p watcom && unzip -aqd watcom /tmp/watcom.zip && chmod -R +x watcom/binl - export PATH=$PATH:$PWD/watcom/binl - export WATCOM=$PWD/watcom - export CPPUTEST_HOME=$TRAVIS_BUILD_DIR - export CC=wcl - export CXX=wcl - $CC --version - make -f ../platforms/Dos/Makefile || exit 1 - ../platforms/Dos/alltests.sh || exit 1 - fi - diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 000000000..8bee1d9b8 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,4 @@ +add_subdirectory(CppUTest) +if (CPPUTEST_EXTENSIONS) + add_subdirectory(CppUTestExt) +endif () diff --git a/src/CppUTest/CMakeIntegration-README.md b/src/CppUTest/CMakeIntegration-README.md new file mode 100644 index 000000000..74ec44aaa --- /dev/null +++ b/src/CppUTest/CMakeIntegration-README.md @@ -0,0 +1,110 @@ +# CMake Integration + +## FetchContent + +CMake can automatically download and integrate CppUTest with +[`FetchContent`](https://cmake.org/cmake/help/latest/module/FetchContent.html). +This is the recommended strategy for CMake integration. + +```cmake +cmake_minimum_required(VERSION 3.11) +project(trying_CppUtest) + +include(FetchContent) +FetchContent_Declare( + CppUTest + GIT_REPOSITORY https://github.com/cpputest/cpputest.git + GIT_TAG master # or use release tag, eg. v4.0 + # FIND_PACKAGE_ARGS # Recent CMake versions can integrate FetchContent with find_package + # https://cmake.org/cmake/help/latest/module/FetchContent.html#integrating-with-find-package +) + +# Either set CPPUTEST_PLATFORM to off and # provide a project-specific +# platform.cpp, assign # one of the provided platforms under +# src/Platforms/ # (as shown below), or let CppUTest +# select an appropriate default. +set(CPPUTEST_PLATFORM Gcc STRING BOOL "Platform implementation") + +FetchContent_MakeAvailable(CppUTest) + +add_executable(trying_CppUtest main.cpp) + +target_link_libraries(trying_CppUtest + PRIVATE + CppUTest::CppUTest + #or CppUTest::CppUTestExt +) + +include(CTest) # Enable testing + +# automatically discover CppUTest tests +include(CppUTest) +cpputest_discover_tests(trying_CppUtest) +``` + +## System install + +If CppUTest has been installed on the system, it can be integrated with +[`find_package`](https://cmake.org/cmake/help/latest/command/find_package.html). +The target platform will be the same as the development host. +This is useful for managing a common +CppUTest installation with the system's package manager. + +```cmake +cmake_minimum_required(VERSION 3.10) +project(trying_CppUtest) + +find_package(CppUTest REQUIRED) + +add_executable(trying_CppUtest main.cpp) + +target_link_libraries(trying_CppUtest + PRIVATE + CppUTest + #or CppUTestExt +) + +include(CTest) # Enable testing + +# automatically discover CppUTest tests +include(CppUTest) +cpputest_discover_tests(trying_CppUtest) +``` + +## Shared directory + +It is possible to integrate CppUTest from a local directory. This may be useful +if CppUTest is being built for a target platform other than that of the +development host and CMake 3.11 is not available. The following is an example +how an external project can refer to this CMakeLists.txt to build CppUTest as a +library and include it as a target dependency. + +```cmake +cmake_minimum_required(VERSION 3.10) +project(trying_CppUtest) + +SET(CppUTestRootDirectory /path/to/cpputest) + +# Either set CPPUTEST_PLATFORM to one of the provided platforms under +# /src/Platforms/, or provide a project-specific +# platform.cpp (as shown below) +set(CPPUTEST_PLATFORM OFF CACHE BOOL "Platform implementation") +add_subdirectory(${CppUTestRootDirectory} CppUTest) +target_sources(CppUTest + PRIVATE + ${PROJECT_SOURCE_DIR}/UtestPlatform.cpp +) + +add_executable(trying_CppUtest main.cpp) +target_link_libraries(trying_CppUtest + PRIVATE + CppUTest::CppUTest + #or CppUTest::CppUTestExt +) + +include(CTest) # Enable testing + +# automatically discover CppUTest tests +include(CppUTest) +cpputest_discover_tests(trying_CppUtest) +``` diff --git a/src/CppUTest/CMakeLists.txt b/src/CppUTest/CMakeLists.txt index 736777f5e..f7c737b0c 100644 --- a/src/CppUTest/CMakeLists.txt +++ b/src/CppUTest/CMakeLists.txt @@ -1,10 +1,11 @@ -set(CppUTest_src +add_library(CppUTest CommandLineArguments.cpp MemoryLeakWarningPlugin.cpp TestHarness_c.cpp TestRegistry.cpp CommandLineTestRunner.cpp SimpleString.cpp + SimpleStringInternalCache.cpp TestMemoryAllocator.cpp TestResult.cpp JUnitTestOutput.cpp @@ -17,44 +18,110 @@ set(CppUTest_src TestTestingFixture.cpp SimpleMutex.cpp Utest.cpp - ../Platforms/${CPP_PLATFORM}/UtestPlatform.cpp + ${PROJECT_SOURCE_DIR}/include/CppUTest/CommandLineArguments.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/PlatformSpecificFunctions.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/TestMemoryAllocator.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/CommandLineTestRunner.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/PlatformSpecificFunctions_c.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/TestOutput.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/CppUTestConfig.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/SimpleString.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/SimpleStringInternalCache.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/TestPlugin.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/JUnitTestOutput.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/TeamCityTestOutput.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/StandardCLibrary.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/TestRegistry.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/MemoryLeakDetector.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/TestFailure.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/TestResult.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/MemoryLeakDetectorMallocMacros.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/TestFilter.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/TestTestingFixture.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/MemoryLeakDetectorNewMacros.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/MemoryLeakDetectorForceInclude.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/TestHarness.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/Utest.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/MemoryLeakWarningPlugin.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/TestHarness_c.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/UtestMacros.h + ${PROJECT_SOURCE_DIR}/include/CppUTest/SimpleMutex.h ) -set(CppUTest_headers - ${CppUTestRootDirectory}/include/CppUTest/CommandLineArguments.h - ${CppUTestRootDirectory}/include/CppUTest/PlatformSpecificFunctions.h - ${CppUTestRootDirectory}/include/CppUTest/TestMemoryAllocator.h - ${CppUTestRootDirectory}/include/CppUTest/CommandLineTestRunner.h - ${CppUTestRootDirectory}/include/CppUTest/PlatformSpecificFunctions_c.h - ${CppUTestRootDirectory}/include/CppUTest/TestOutput.h - ${CppUTestRootDirectory}/include/CppUTest/CppUTestConfig.h - ${CppUTestRootDirectory}/include/CppUTest/SimpleString.h - ${CppUTestRootDirectory}/include/CppUTest/TestPlugin.h - ${CppUTestRootDirectory}/include/CppUTest/JUnitTestOutput.h - ${CppUTestRootDirectory}/include/CppUTest/TeamCityTestOutput.h - ${CppUTestRootDirectory}/include/CppUTest/StandardCLibrary.h - ${CppUTestRootDirectory}/include/CppUTest/TestRegistry.h - ${CppUTestRootDirectory}/include/CppUTest/MemoryLeakDetector.h - ${CppUTestRootDirectory}/include/CppUTest/TestFailure.h - ${CppUTestRootDirectory}/include/CppUTest/TestResult.h - ${CppUTestRootDirectory}/include/CppUTest/MemoryLeakDetectorMallocMacros.h - ${CppUTestRootDirectory}/include/CppUTest/TestFilter.h - ${CppUTestRootDirectory}/include/CppUTest/TestTestingFixture.h - ${CppUTestRootDirectory}/include/CppUTest/MemoryLeakDetectorNewMacros.h - ${CppUTestRootDirectory}/include/CppUTest/TestHarness.h - ${CppUTestRootDirectory}/include/CppUTest/Utest.h - ${CppUTestRootDirectory}/include/CppUTest/MemoryLeakWarningPlugin.h - ${CppUTestRootDirectory}/include/CppUTest/TestHarness_c.h - ${CppUTestRootDirectory}/include/CppUTest/UtestMacros.h +#[[Set CPPUTEST_PLATFORM in a parent CMakeLists.txt if reusing one of the provided platforms, else supply the missing definitions]] +if(CPPUTEST_PLATFORM) + target_sources(CppUTest + PRIVATE + ${CMAKE_CURRENT_LIST_DIR}/../Platforms/${CPPUTEST_PLATFORM}/UtestPlatform.cpp + ) +endif() + +if(CPPUTEST_PLATFORM STREQUAL "c2000") + target_include_directories(CppUTest + PUBLIC + $ + ) +elseif(CPPUTEST_PLATFORM STREQUAL "Iar") + target_compile_options(CppUTest + PRIVATE + --dlib_config full + ) +endif() + +if (MINGW) + include(CheckStructHasMember) + check_struct_has_member("struct timespec" tv_sec time.h HAVE_STRUCT_TIMESPEC LANGUAGE CXX) +endif() + +#[[Arrange for the include directory to be added to the include paths of any CMake target depending on CppUTest.]] +target_include_directories(CppUTest + PUBLIC + $ + $ +) + +target_compile_definitions(CppUTest + PRIVATE + $<$:STDC_WANT_SECURE_LIB> + # Apply workaround for MinGW timespec redefinition (pthread.h / time.h). + $<$:_TIMESPEC_DEFINED> ) -add_library(CppUTest STATIC ${CppUTest_src} ${CppUTest_headers}) -if (WIN32) - target_link_libraries(CppUTest winmm.lib) -endif (WIN32) -install(FILES ${CppUTest_headers} DESTINATION include/CppUTest) -install(TARGETS CppUTest - EXPORT CppUTestTargets - RUNTIME DESTINATION bin - LIBRARY DESTINATION lib - ARCHIVE DESTINATION lib) +set(THREADS_PREFER_PTHREAD_FLAG ON) +find_package(Threads) + +target_link_libraries(CppUTest + PRIVATE + $<$:winmm> + $<$:${CMAKE_THREAD_LIBS_INIT}> +) + +add_library(CppUTest::CppUTest ALIAS CppUTest) + +if(NOT CPPUTEST_MEM_LEAK_DETECTION_DISABLED) + if(MSVC) + set(force_include "/FI") + elseif(CMAKE_CXX_COMPILER_ID STREQUAL "IAR") + set(force_include "--preinclude=") + else() + set(force_include "-include") + endif() + target_compile_options(CppUTest + PUBLIC + ${force_include}CppUTest/MemoryLeakDetectorForceInclude.h + ) +endif() + +# Installation +if(PROJECT_IS_TOP_LEVEL) + install( + TARGETS CppUTest + EXPORT CppUTestTargets + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + ) + install( + DIRECTORY "${PROJECT_SOURCE_DIR}/include/CppUTest" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" + ) +endif() diff --git a/src/CppUTest/CommandLineArguments.cpp b/src/CppUTest/CommandLineArguments.cpp old mode 100755 new mode 100644 index e0b993bcd..e3d1a8cbe --- a/src/CppUTest/CommandLineArguments.cpp +++ b/src/CppUTest/CommandLineArguments.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -29,8 +29,11 @@ #include "CppUTest/CommandLineArguments.h" #include "CppUTest/PlatformSpecificFunctions.h" -CommandLineArguments::CommandLineArguments(int ac, const char** av) : - ac_(ac), av_(av), verbose_(false), color_(false), runTestsAsSeperateProcess_(false), listTestGroupNames_(false), listTestGroupAndCaseNames_(false), runIgnored_(false), repeat_(1), groupFilters_(NULL), nameFilters_(NULL), outputType_(OUTPUT_ECLIPSE) +CommandLineArguments::CommandLineArguments(int ac, const char *const *av) : + ac_(ac), av_(av), needHelp_(false), verbose_(false), veryVerbose_(false), color_(false), runTestsAsSeperateProcess_(false), + listTestGroupNames_(false), listTestGroupAndCaseNames_(false), listTestLocations_(false), runIgnored_(false), reversing_(false), + crashOnFail_(false), rethrowExceptions_(true), shuffling_(false), shufflingPreSeeded_(false), repeat_(1), shuffleSeed_(0), + groupFilters_(NULLPTR), nameFilters_(NULLPTR), outputType_(OUTPUT_ECLIPSE) { } @@ -54,26 +57,40 @@ bool CommandLineArguments::parse(TestPlugin* plugin) for (int i = 1; i < ac_; i++) { SimpleString argument = av_[i]; - if (argument == "-v") verbose_ = true; + if (argument == "-h") { + needHelp_ = true; + correctParameters = false; + } + else if (argument == "-v") verbose_ = true; + else if (argument == "-vv") veryVerbose_ = true; else if (argument == "-c") color_ = true; else if (argument == "-p") runTestsAsSeperateProcess_ = true; + else if (argument == "-b") reversing_ = true; else if (argument == "-lg") listTestGroupNames_ = true; else if (argument == "-ln") listTestGroupAndCaseNames_ = true; + else if (argument == "-ll") listTestLocations_ = true; else if (argument == "-ri") runIgnored_ = true; - else if (argument.startsWith("-r")) SetRepeatCount(ac_, av_, i); - else if (argument.startsWith("-g")) AddGroupFilter(ac_, av_, i); - else if (argument.startsWith("-sg")) AddStrictGroupFilter(ac_, av_, i); - else if (argument.startsWith("-xg")) AddExcludeGroupFilter(ac_, av_, i); - else if (argument.startsWith("-xsg")) AddExcludeStrictGroupFilter(ac_, av_, i); - else if (argument.startsWith("-n")) AddNameFilter(ac_, av_, i); - else if (argument.startsWith("-sn")) AddStrictNameFilter(ac_, av_, i); - else if (argument.startsWith("-xn")) AddExcludeNameFilter(ac_, av_, i); - else if (argument.startsWith("-xsn")) AddExcludeStrictNameFilter(ac_, av_, i); - else if (argument.startsWith("TEST(")) AddTestToRunBasedOnVerboseOutput(ac_, av_, i, "TEST("); - else if (argument.startsWith("IGNORE_TEST(")) AddTestToRunBasedOnVerboseOutput(ac_, av_, i, "IGNORE_TEST("); - else if (argument.startsWith("-o")) correctParameters = SetOutputType(ac_, av_, i); + else if (argument == "-f") crashOnFail_ = true; + else if ((argument == "-e") || (argument == "-ci")) rethrowExceptions_ = false; + else if (argument.startsWith("-r")) setRepeatCount(ac_, av_, i); + else if (argument.startsWith("-g")) addGroupFilter(ac_, av_, i); + else if (argument.startsWith("-t")) correctParameters = addGroupDotNameFilter(ac_, av_, i, "-t", false, false); + else if (argument.startsWith("-st")) correctParameters = addGroupDotNameFilter(ac_, av_, i, "-st", true, false); + else if (argument.startsWith("-xt")) correctParameters = addGroupDotNameFilter(ac_, av_, i, "-xt", false, true); + else if (argument.startsWith("-xst")) correctParameters = addGroupDotNameFilter(ac_, av_, i, "-xst", true, true); + else if (argument.startsWith("-sg")) addStrictGroupFilter(ac_, av_, i); + else if (argument.startsWith("-xg")) addExcludeGroupFilter(ac_, av_, i); + else if (argument.startsWith("-xsg")) addExcludeStrictGroupFilter(ac_, av_, i); + else if (argument.startsWith("-n")) addNameFilter(ac_, av_, i); + else if (argument.startsWith("-sn")) addStrictNameFilter(ac_, av_, i); + else if (argument.startsWith("-xn")) addExcludeNameFilter(ac_, av_, i); + else if (argument.startsWith("-xsn")) addExcludeStrictNameFilter(ac_, av_, i); + else if (argument.startsWith("-s")) correctParameters = setShuffle(ac_, av_, i); + else if (argument.startsWith("TEST(")) addTestToRunBasedOnVerboseOutput(ac_, av_, i, "TEST("); + else if (argument.startsWith("IGNORE_TEST(")) addTestToRunBasedOnVerboseOutput(ac_, av_, i, "IGNORE_TEST("); + else if (argument.startsWith("-o")) correctParameters = setOutputType(ac_, av_, i); else if (argument.startsWith("-p")) correctParameters = plugin->parseAllArguments(ac_, av_, i); - else if (argument.startsWith("-k")) SetPackageName(ac_, av_, i); + else if (argument.startsWith("-k")) setPackageName(ac_, av_, i); else correctParameters = false; if (correctParameters == false) { @@ -85,7 +102,67 @@ bool CommandLineArguments::parse(TestPlugin* plugin) const char* CommandLineArguments::usage() const { - return "usage [-v] [-c] [-p] [-lg] [-ln] [-ri] [-r#] [-g|sg|xg|xsg groupName]... [-n|sn|xn|xsn testName]... [\"TEST(groupName, testName)\"]... [-o{normal, junit, teamcity}] [-k packageName]\n"; + return "use -h for more extensive help\n" + "usage [-h] [-v] [-vv] [-c] [-p] [-lg] [-ln] [-ll] [-ri] [-r[<#>]] [-f] [-e] [-ci]\n" + " [-g|sg|xg|xsg ]... [-n|sn|xn|xsn ]... [-t|st|xt|xst .]...\n" + " [-b] [-s []] [\"[IGNORE_]TEST(, )\"]...\n" + " [-o{normal|eclipse|junit|teamcity}] [-k ]\n"; +} + +const char* CommandLineArguments::help() const +{ + return + "Thanks for using CppUTest.\n" + "\n" + "Options that do not run tests but query:\n" + " -h - this wonderful help screen. Joy!\n" + " -lg - print a list of group names, separated by spaces\n" + " -ln - print a list of test names in the form of group.name, separated by spaces\n" + " -ll - print a list of test names in the form of group.name.test_file_path.line\n" + "\n" + "Options that change the output format:\n" + " -c - colorize output, print green if OK, or red if failed\n" + " -v - verbose, print each test name as it runs\n" + " -vv - very verbose, print internal information during test run\n" + "\n" + "Options that change the output location:\n" + " -onormal - no output to files\n" + " -oeclipse - equivalent to -onormal\n" + " -oteamcity - output to xml files (as the name suggests, for TeamCity)\n" + " -ojunit - output to JUnit ant plugin style xml files (for CI systems)\n" + " -k - add a package name in JUnit output (for classification in CI systems)\n" + "\n" + "\n" + "Options that control which tests are run:\n" + " -g - only run tests whose group contains \n" + " -n - only run tests whose name contains \n" + " -t . - only run tests whose group and name contain and \n" + " -sg - only run tests whose group exactly matches \n" + " -sn - only run tests whose name exactly matches \n" + " -st . - only run tests whose group and name exactly match and \n" + " -xg - exclude tests whose group contains \n" + " -xn - exclude tests whose name contains \n" + " -xt . - exclude tests whose group and name contain and \n" + " -xsg - exclude tests whose group exactly matches \n" + " -xsn - exclude tests whose name exactly matches \n" + " -xst . - exclude tests whose group and name exactly match and \n" + " \"[IGNORE_]TEST(, )\"\n" + " - only run tests whose group and name exactly match and \n" + " (this can be used to copy-paste output from the -v option on the command line)\n" + "\n" + "Options that control how the tests are run:\n" + " -p - run tests in a separate process\n" + " -b - run the tests backwards, reversing the normal way\n" + " -s [] - shuffle tests randomly (randomization seed is optional, must be greater than 0)\n" + " -r[<#>] - repeat the tests <#> times (or twice if <#> is not specified)\n" + " -f - Cause the tests to crash on failure (to allow the test to be debugged if necessary)\n" + " -e - do not rethrow unexpected exceptions on failure\n" + " -ci - continuous integration mode (equivalent to -e)\n"; +} + +bool CommandLineArguments::needHelp() const +{ + return needHelp_; } bool CommandLineArguments::isVerbose() const @@ -93,6 +170,11 @@ bool CommandLineArguments::isVerbose() const return verbose_; } +bool CommandLineArguments::isVeryVerbose() const +{ + return veryVerbose_; +} + bool CommandLineArguments::isColor() const { return color_; @@ -108,6 +190,11 @@ bool CommandLineArguments::isListingTestGroupAndCaseNames() const return listTestGroupAndCaseNames_; } +bool CommandLineArguments::isListingTestLocations() const +{ + return listTestLocations_; +} + bool CommandLineArguments::isRunIgnored() const { return runIgnored_; @@ -119,11 +206,36 @@ bool CommandLineArguments::runTestsInSeperateProcess() const } -int CommandLineArguments::getRepeatCount() const +size_t CommandLineArguments::getRepeatCount() const { return repeat_; } +bool CommandLineArguments::isReversing() const +{ + return reversing_; +} + +bool CommandLineArguments::isCrashingOnFail() const +{ + return crashOnFail_; +} + +bool CommandLineArguments::isRethrowingExceptions() const +{ + return rethrowExceptions_; +} + +bool CommandLineArguments::isShuffling() const +{ + return shuffling_; +} + +size_t CommandLineArguments::getShuffleSeed() const +{ + return shuffleSeed_; +} + const TestFilter* CommandLineArguments::getGroupFilters() const { return groupFilters_; @@ -134,14 +246,14 @@ const TestFilter* CommandLineArguments::getNameFilters() const return nameFilters_; } -void CommandLineArguments::SetRepeatCount(int ac, const char** av, int& i) +void CommandLineArguments::setRepeatCount(int ac, const char *const *av, int& i) { repeat_ = 0; SimpleString repeatParameter(av[i]); - if (repeatParameter.size() > 2) repeat_ = SimpleString::AtoI(av[i] + 2); + if (repeatParameter.size() > 2) repeat_ = (size_t) (SimpleString::AtoI(av[i] + 2)); else if (i + 1 < ac) { - repeat_ = SimpleString::AtoI(av[i + 1]); + repeat_ = (size_t) (SimpleString::AtoI(av[i + 1])); if (repeat_ != 0) i++; } @@ -149,7 +261,29 @@ void CommandLineArguments::SetRepeatCount(int ac, const char** av, int& i) } -SimpleString CommandLineArguments::getParameterField(int ac, const char** av, int& i, const SimpleString& parameterName) +bool CommandLineArguments::setShuffle(int ac, const char * const *av, int& i) +{ + shuffling_ = true; + shuffleSeed_ = (unsigned int)GetPlatformSpecificTimeInMillis(); + if (shuffleSeed_ == 0) shuffleSeed_++; + + SimpleString shuffleParameter = av[i]; + if (shuffleParameter.size() > 2) { + shufflingPreSeeded_ = true; + shuffleSeed_ = SimpleString::AtoU(av[i] + 2); + } else if (i + 1 < ac) { + unsigned int parsedParameter = SimpleString::AtoU(av[i + 1]); + if (parsedParameter != 0) + { + shufflingPreSeeded_ = true; + shuffleSeed_ = parsedParameter; + i++; + } + } + return (shuffleSeed_ != 0); +} + +SimpleString CommandLineArguments::getParameterField(int ac, const char * const *av, int& i, const SimpleString& parameterName) { size_t parameterLength = parameterName.size(); SimpleString parameter(av[i]); @@ -158,27 +292,53 @@ SimpleString CommandLineArguments::getParameterField(int ac, const char** av, in return ""; } -void CommandLineArguments::AddGroupFilter(int ac, const char** av, int& i) +void CommandLineArguments::addGroupFilter(int ac, const char *const *av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-g")); groupFilters_ = groupFilter->add(groupFilters_); } -void CommandLineArguments::AddStrictGroupFilter(int ac, const char** av, int& i) +bool CommandLineArguments::addGroupDotNameFilter(int ac, const char *const *av, int& i, const SimpleString& parameterName, + bool strict, bool exclude) +{ + SimpleString groupDotName = getParameterField(ac, av, i, parameterName); + SimpleStringCollection collection; + groupDotName.split(".", collection); + + if (collection.size() != 2) return false; + + TestFilter* groupFilter = new TestFilter(collection[0].subString(0, collection[0].size()-1)); + TestFilter* nameFilter = new TestFilter(collection[1]); + if (strict) + { + groupFilter->strictMatching(); + nameFilter->strictMatching(); + } + if (exclude) + { + groupFilter->invertMatching(); + nameFilter->invertMatching(); + } + groupFilters_ = groupFilter->add(groupFilters_); + nameFilters_ = nameFilter->add(nameFilters_); + return true; +} + +void CommandLineArguments::addStrictGroupFilter(int ac, const char *const *av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-sg")); groupFilter->strictMatching(); groupFilters_ = groupFilter->add(groupFilters_); } -void CommandLineArguments::AddExcludeGroupFilter(int ac, const char** av, int& i) +void CommandLineArguments::addExcludeGroupFilter(int ac, const char *const *av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-xg")); groupFilter->invertMatching(); groupFilters_ = groupFilter->add(groupFilters_); } -void CommandLineArguments::AddExcludeStrictGroupFilter(int ac, const char** av, int& i) +void CommandLineArguments::addExcludeStrictGroupFilter(int ac, const char *const *av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-xsg")); groupFilter->strictMatching(); @@ -186,27 +346,27 @@ void CommandLineArguments::AddExcludeStrictGroupFilter(int ac, const char** av, groupFilters_ = groupFilter->add(groupFilters_); } -void CommandLineArguments::AddNameFilter(int ac, const char** av, int& i) +void CommandLineArguments::addNameFilter(int ac, const char *const *av, int& i) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, i, "-n")); nameFilters_ = nameFilter->add(nameFilters_); } -void CommandLineArguments::AddStrictNameFilter(int ac, const char** av, int& index) +void CommandLineArguments::addStrictNameFilter(int ac, const char *const *av, int& index) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, index, "-sn")); nameFilter->strictMatching(); nameFilters_= nameFilter->add(nameFilters_); } -void CommandLineArguments::AddExcludeNameFilter(int ac, const char** av, int& index) +void CommandLineArguments::addExcludeNameFilter(int ac, const char *const *av, int& index) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, index, "-xn")); nameFilter->invertMatching(); nameFilters_= nameFilter->add(nameFilters_); } -void CommandLineArguments::AddExcludeStrictNameFilter(int ac, const char** av, int& index) +void CommandLineArguments::addExcludeStrictNameFilter(int ac, const char *const *av, int& index) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, index, "-xsn")); nameFilter->invertMatching(); @@ -214,11 +374,11 @@ void CommandLineArguments::AddExcludeStrictNameFilter(int ac, const char** av, i nameFilters_= nameFilter->add(nameFilters_); } -void CommandLineArguments::AddTestToRunBasedOnVerboseOutput(int ac, const char** av, int& index, const char* parameterName) +void CommandLineArguments::addTestToRunBasedOnVerboseOutput(int ac, const char *const *av, int& index, const char* parameterName) { SimpleString wholename = getParameterField(ac, av, index, parameterName); SimpleString testname = wholename.subStringFromTill(',', ')'); - testname = testname.subString(2, testname.size()); + testname = testname.subString(2); TestFilter* namefilter = new TestFilter(testname); TestFilter* groupfilter = new TestFilter(wholename.subStringFromTill(wholename.at(0), ',')); namefilter->strictMatching(); @@ -227,7 +387,7 @@ void CommandLineArguments::AddTestToRunBasedOnVerboseOutput(int ac, const char** nameFilters_ = namefilter->add(nameFilters_); } -void CommandLineArguments::SetPackageName(int ac, const char** av, int& i) +void CommandLineArguments::setPackageName(int ac, const char *const *av, int& i) { SimpleString packageName = getParameterField(ac, av, i, "-k"); if (packageName.size() == 0) return; @@ -235,7 +395,7 @@ void CommandLineArguments::SetPackageName(int ac, const char** av, int& i) packageName_ = packageName; } -bool CommandLineArguments::SetOutputType(int ac, const char** av, int& i) +bool CommandLineArguments::setOutputType(int ac, const char *const *av, int& i) { SimpleString outputType = getParameterField(ac, av, i, "-o"); if (outputType.size() == 0) return false; diff --git a/src/CppUTest/CommandLineTestRunner.cpp b/src/CppUTest/CommandLineTestRunner.cpp old mode 100755 new mode 100644 index 43d2dec5c..b50e897e7 --- a/src/CppUTest/CommandLineTestRunner.cpp +++ b/src/CppUTest/CommandLineTestRunner.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,10 +34,10 @@ int CommandLineTestRunner::RunAllTests(int ac, char** av) { - return RunAllTests(ac, (const char**) av); + return RunAllTests(ac, (const char *const *) av); } -int CommandLineTestRunner::RunAllTests(int ac, const char** av) +int CommandLineTestRunner::RunAllTests(int ac, const char *const *av) { int result = 0; ConsoleTestOutput backupOutput; @@ -58,8 +58,8 @@ int CommandLineTestRunner::RunAllTests(int ac, const char** av) return result; } -CommandLineTestRunner::CommandLineTestRunner(int ac, const char** av, TestRegistry* registry) : - output_(NULL), arguments_(NULL), registry_(registry) +CommandLineTestRunner::CommandLineTestRunner(int ac, const char *const *av, TestRegistry* registry) : + output_(NULLPTR), arguments_(NULLPTR), registry_(registry) { arguments_ = new CommandLineArguments(ac, av); } @@ -72,7 +72,7 @@ CommandLineTestRunner::~CommandLineTestRunner() int CommandLineTestRunner::runAllTestsMain() { - int testResult = 0; + int testResult = 1; SetPointerPlugin pPlugin(DEF_PLUGIN_SET_POINTER); registry_->installPlugin(&pPlugin); @@ -88,19 +88,24 @@ void CommandLineTestRunner::initializeTestRun() { registry_->setGroupFilters(arguments_->getGroupFilters()); registry_->setNameFilters(arguments_->getNameFilters()); - - if (arguments_->isVerbose()) output_->verbose(); + + if (arguments_->isVerbose()) output_->verbose(TestOutput::level_verbose); + if (arguments_->isVeryVerbose()) output_->verbose(TestOutput::level_veryVerbose); if (arguments_->isColor()) output_->color(); if (arguments_->runTestsInSeperateProcess()) registry_->setRunTestsInSeperateProcess(); if (arguments_->isRunIgnored()) registry_->setRunIgnored(); + if (arguments_->isCrashingOnFail()) UtestShell::setCrashOnFail(); + + UtestShell::setRethrowExceptions( arguments_->isRethrowingExceptions() ); } int CommandLineTestRunner::runAllTests() { initializeTestRun(); - int loopCount = 0; - int failureCount = 0; - int repeat_ = arguments_->getRepeatCount(); + size_t loopCount = 0; + size_t failedTestCount = 0; + size_t failedExecutionCount = 0; + size_t repeatCount = arguments_->getRepeatCount(); if (arguments_->isListingTestGroupNames()) { @@ -116,14 +121,36 @@ int CommandLineTestRunner::runAllTests() return 0; } - while (loopCount++ < repeat_) { - output_->printTestRun(loopCount, repeat_); + if (arguments_->isListingTestLocations()) + { TestResult tr(*output_); - registry_->runAllTests(tr); - failureCount += tr.getFailureCount(); + registry_->listTestLocations(tr); + return 0; } - return failureCount; + if (arguments_->isReversing()) + registry_->reverseTests(); + + if (arguments_->isShuffling()) + { + output_->print("Test order shuffling enabled with seed: "); + output_->print(arguments_->getShuffleSeed()); + output_->print("\n"); + } + while (loopCount++ < repeatCount) { + + if (arguments_->isShuffling()) + registry_->shuffleTests(arguments_->getShuffleSeed()); + + output_->printTestRun(loopCount, repeatCount); + TestResult tr(*output_); + registry_->runAllTests(tr); + failedTestCount += tr.getFailureCount(); + if (tr.isFailure()) { + failedExecutionCount++; + } + } + return (int) (failedTestCount != 0 ? failedTestCount : failedExecutionCount); } TestOutput* CommandLineTestRunner::createTeamCityOutput() @@ -134,7 +161,7 @@ TestOutput* CommandLineTestRunner::createTeamCityOutput() TestOutput* CommandLineTestRunner::createJUnitOutput(const SimpleString& packageName) { JUnitTestOutput* junitOutput = new JUnitTestOutput; - if (junitOutput != NULL) { + if (junitOutput != NULLPTR) { junitOutput->setPackageName(packageName); } return junitOutput; @@ -157,13 +184,13 @@ bool CommandLineTestRunner::parseArguments(TestPlugin* plugin) { if (!arguments_->parse(plugin)) { output_ = createConsoleOutput(); - output_->print(arguments_->usage()); + output_->print((arguments_->needHelp()) ? arguments_->help() : arguments_->usage()); return false; } if (arguments_->isJUnitOutput()) { output_= createJUnitOutput(arguments_->getPackageName()); - if (arguments_->isVerbose()) + if (arguments_->isVerbose() || arguments_->isVeryVerbose()) output_ = createCompositeOutput(output_, createConsoleOutput()); } else if (arguments_->isTeamCityOutput()) { output_ = createTeamCityOutput(); diff --git a/src/CppUTest/JUnitTestOutput.cpp b/src/CppUTest/JUnitTestOutput.cpp index 929f9dd8f..f509d9b72 100644 --- a/src/CppUTest/JUnitTestOutput.cpp +++ b/src/CppUTest/JUnitTestOutput.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,28 +34,32 @@ struct JUnitTestCaseResultNode { JUnitTestCaseResultNode() : - execTime_(0), failure_(0), ignored_(false), next_(0) + execTime_(0), failure_(NULLPTR), ignored_(false), lineNumber_ (0), checkCount_ (0), next_(NULLPTR) { } SimpleString name_; - long execTime_; + size_t execTime_; TestFailure* failure_; bool ignored_; + SimpleString file_; + size_t lineNumber_; + size_t checkCount_; JUnitTestCaseResultNode* next_; }; struct JUnitTestGroupResult { JUnitTestGroupResult() : - testCount_(0), failureCount_(0), startTime_(0), groupExecTime_(0), head_(0), tail_(0) + testCount_(0), failureCount_(0), totalCheckCount_(0), startTime_(0), groupExecTime_(0), head_(NULLPTR), tail_(NULLPTR) { } - int testCount_; - int failureCount_; - long startTime_; - long groupExecTime_; + size_t testCount_; + size_t failureCount_; + size_t totalCheckCount_; + size_t startTime_; + size_t groupExecTime_; SimpleString group_; JUnitTestCaseResultNode* head_; JUnitTestCaseResultNode* tail_; @@ -66,6 +70,7 @@ struct JUnitTestOutputImpl JUnitTestGroupResult results_; PlatformSpecificFile file_; SimpleString package_; + SimpleString stdOutput_; }; JUnitTestOutput::JUnitTestOutput() : @@ -87,13 +92,12 @@ void JUnitTestOutput::resetTestGroupResult() JUnitTestCaseResultNode* cur = impl_->results_.head_; while (cur) { JUnitTestCaseResultNode* tmp = cur->next_; - ; delete cur->failure_; delete cur; cur = tmp; } - impl_->results_.head_ = 0; - impl_->results_.tail_ = 0; + impl_->results_.head_ = NULLPTR; + impl_->results_.tail_ = NULLPTR; } void JUnitTestOutput::printTestsStarted() @@ -106,8 +110,8 @@ void JUnitTestOutput::printCurrentGroupStarted(const UtestShell& /*test*/) void JUnitTestOutput::printCurrentTestEnded(const TestResult& result) { - impl_->results_.tail_->execTime_ - = result.getCurrentTestTotalExecutionTime(); + impl_->results_.tail_->execTime_ = result.getCurrentTestTotalExecutionTime(); + impl_->results_.tail_->checkCount_ = result.getCheckCount(); } void JUnitTestOutput::printTestsEnded(const TestResult& /*result*/) @@ -125,9 +129,9 @@ void JUnitTestOutput::printCurrentTestStarted(const UtestShell& test) { impl_->results_.testCount_++; impl_->results_.group_ = test.getGroup(); - impl_->results_.startTime_ = GetPlatformSpecificTimeInMillis(); + impl_->results_.startTime_ = (size_t) GetPlatformSpecificTimeInMillis(); - if (impl_->results_.tail_ == 0) { + if (impl_->results_.tail_ == NULLPTR) { impl_->results_.head_ = impl_->results_.tail_ = new JUnitTestCaseResultNode; } @@ -136,6 +140,8 @@ void JUnitTestOutput::printCurrentTestStarted(const UtestShell& test) impl_->results_.tail_ = impl_->results_.tail_->next_; } impl_->results_.tail_->name_ = test.getName(); + impl_->results_.tail_->file_ = test.getFile(); + impl_->results_.tail_->lineNumber_ = test.getLineNumber(); if (!test.willRun()) { impl_->results_.tail_->ignored_ = true; } @@ -144,15 +150,29 @@ void JUnitTestOutput::printCurrentTestStarted(const UtestShell& test) SimpleString JUnitTestOutput::createFileName(const SimpleString& group) { SimpleString fileName = "cpputest_"; + if (!impl_->package_.isEmpty()) { + fileName += impl_->package_; + fileName += "_"; + } fileName += group; - fileName.replace('/', '_'); - fileName += ".xml"; - return fileName; + return encodeFileName(fileName) + ".xml"; +} + +SimpleString JUnitTestOutput::encodeFileName(const SimpleString& fileName) +{ + // special character list based on: https://en.wikipedia.org/wiki/Filename + static const char* const forbiddenCharacters = "/\\?%*:|\"<>"; + + SimpleString result = fileName; + for (const char* sym = forbiddenCharacters; *sym; ++sym) { + result.replace(*sym, '_'); + } + return result; } void JUnitTestOutput::setPackageName(const SimpleString& package) { - if (impl_ != NULL) { + if (impl_ != NULLPTR) { impl_->package_ = package; } } @@ -168,9 +188,9 @@ void JUnitTestOutput::writeTestSuiteSummary() buf = StringFromFormat( "\n", - impl_->results_.failureCount_, + (int)impl_->results_.failureCount_, impl_->results_.group_.asCharString(), - impl_->results_.testCount_, + (int) impl_->results_.testCount_, (int) (impl_->results_.groupExecTime_ / 1000), (int) (impl_->results_.groupExecTime_ % 1000), GetPlatformSpecificTimeString()); writeToFile(buf.asCharString()); @@ -182,18 +202,37 @@ void JUnitTestOutput::writeProperties() writeToFile("\n"); } +SimpleString JUnitTestOutput::encodeXmlText(const SimpleString& textbody) +{ + SimpleString buf = textbody.asCharString(); + buf.replace("&", "&"); + buf.replace("\"", """); + buf.replace("<", "<"); + buf.replace(">", ">"); + buf.replace("\r", " "); + buf.replace("\n", " "); + return buf; +} + void JUnitTestOutput::writeTestCases() { JUnitTestCaseResultNode* cur = impl_->results_.head_; + while (cur) { SimpleString buf = StringFromFormat( - "\n", + "\n", impl_->package_.asCharString(), - impl_->package_.isEmpty() == true ? "" : ".", + impl_->package_.isEmpty() ? "" : ".", impl_->results_.group_.asCharString(), - cur->name_.asCharString(), (int) (cur->execTime_ / 1000), (int)(cur->execTime_ % 1000)); + cur->name_.asCharString(), + (int) (cur->checkCount_ - impl_->results_.totalCheckCount_), + (int) (cur->execTime_ / 1000), (int)(cur->execTime_ % 1000), + cur->file_.asCharString(), + (int) cur->lineNumber_); writeToFile(buf.asCharString()); + impl_->results_.totalCheckCount_ = cur->checkCount_; + if (cur->failure_) { writeFailure(cur); } @@ -207,25 +246,23 @@ void JUnitTestOutput::writeTestCases() void JUnitTestOutput::writeFailure(JUnitTestCaseResultNode* node) { - SimpleString message = node->failure_->getMessage().asCharString(); - message.replace('"', '\''); - message.replace('<', '['); - message.replace('>', ']'); - message.replace("&", "&"); - message.replace("\n", "{newline}"); SimpleString buf = StringFromFormat( "\n", node->failure_->getFileName().asCharString(), - node->failure_->getFailureLineNumber(), message.asCharString()); + (int) node->failure_->getFailureLineNumber(), + encodeXmlText(node->failure_->getMessage()).asCharString()); writeToFile(buf.asCharString()); writeToFile("\n"); } + void JUnitTestOutput::writeFileEnding() { - writeToFile("\n"); + writeToFile(""); + writeToFile(encodeXmlText(impl_->stdOutput_)); + writeToFile("\n"); writeToFile("\n"); - writeToFile(""); + writeToFile("\n"); } void JUnitTestOutput::writeTestGroupToFile() @@ -245,14 +282,19 @@ void JUnitTestOutput::printBuffer(const char*) { } -void JUnitTestOutput::print(const char*) +void JUnitTestOutput::print(const char *output) { + impl_->stdOutput_ += output; } void JUnitTestOutput::print(long) { } +void JUnitTestOutput::print(size_t) +{ +} + void JUnitTestOutput::flush() { } @@ -261,7 +303,7 @@ void JUnitTestOutput::flush() void JUnitTestOutput::printFailure(const TestFailure& failure) { - if (impl_->results_.tail_->failure_ == 0) { + if (impl_->results_.tail_->failure_ == NULLPTR) { impl_->results_.failureCount_++; impl_->results_.tail_->failure_ = new TestFailure(failure); } diff --git a/src/CppUTest/MemoryLeakDetector.cpp b/src/CppUTest/MemoryLeakDetector.cpp index 19cab29c9..89e45908e 100644 --- a/src/CppUTest/MemoryLeakDetector.cpp +++ b/src/CppUTest/MemoryLeakDetector.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,7 +30,9 @@ #include "CppUTest/PlatformSpecificFunctions.h" #include "CppUTest/SimpleMutex.h" -#define UNKNOWN ((char*)("")) +static const char* UNKNOWN = ""; + +static const char GuardBytes[] = {'B','A','S'}; SimpleStringBuffer::SimpleStringBuffer() : positions_filled_(0), write_limit_(SIMPLE_STRING_BUFFER_LEN-1) @@ -46,13 +48,12 @@ void SimpleStringBuffer::clear() void SimpleStringBuffer::add(const char* format, ...) { - int count = 0; - size_t positions_left = write_limit_ - positions_filled_; - if (positions_left <= 0) return; + const size_t positions_left = write_limit_ - positions_filled_; + if (positions_left == 0) return; va_list arguments; va_start(arguments, format); - count = PlatformSpecificVSNprintf(buffer_ + positions_filled_, positions_left+1, format, arguments); + const int count = PlatformSpecificVSNprintf(buffer_ + positions_filled_, positions_left+1, format, arguments); if (count > 0) positions_filled_ += (size_t) count; if (positions_filled_ > write_limit_) positions_filled_ = write_limit_; va_end(arguments); @@ -63,7 +64,7 @@ void SimpleStringBuffer::addMemoryDump(const void* memory, size_t memorySize) const unsigned char* byteMemory = (const unsigned char*)memory; const size_t maxLineBytes = 16; size_t currentPos = 0; - size_t p; + size_t p; while (currentPos < memorySize) { add(" %04lx: ", (unsigned long) currentPos); @@ -134,14 +135,14 @@ MemoryLeakOutputStringBuffer::MemoryLeakOutputStringBuffer() { } -void MemoryLeakOutputStringBuffer::addAllocationLocation(const char* allocationFile, int allocationLineNumber, size_t allocationSize, TestMemoryAllocator* allocator) +void MemoryLeakOutputStringBuffer::addAllocationLocation(const char* allocationFile, size_t allocationLineNumber, size_t allocationSize, TestMemoryAllocator* allocator) { - outputBuffer_.add(" allocated at file: %s line: %d size: %lu type: %s\n", allocationFile, allocationLineNumber, (unsigned long) allocationSize, allocator->alloc_name()); + outputBuffer_.add(" allocated at file: %s line: %d size: %lu type: %s\n", allocationFile, (int) allocationLineNumber, (unsigned long) allocationSize, allocator->alloc_name()); } -void MemoryLeakOutputStringBuffer::addDeallocationLocation(const char* freeFile, int freeLineNumber, TestMemoryAllocator* allocator) +void MemoryLeakOutputStringBuffer::addDeallocationLocation(const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* allocator) { - outputBuffer_.add(" deallocated at file: %s line: %d type: %s\n", freeFile, freeLineNumber, allocator->free_name()); + outputBuffer_.add(" deallocated at file: %s line: %d type: %s\n", freeFile, (int) freeLineNumber, allocator->free_name()); } void MemoryLeakOutputStringBuffer::addNoMemoryLeaksMessage() @@ -168,7 +169,7 @@ void MemoryLeakOutputStringBuffer::reportMemoryLeak(MemoryLeakDetectorNode* leak total_leaks_++; outputBuffer_.add("Alloc num (%u) Leak size: %lu Allocated at: %s and line: %d. Type: \"%s\"\n\tMemory: <%p> Content:\n", - leak->number_, (unsigned long) leak->size_, leak->file_, leak->line_, leak->allocator_->alloc_name(), (void*) leak->memory_); + leak->number_, (unsigned long) leak->size_, leak->file_, (int) leak->line_, leak->allocator_->alloc_name(), (void*) leak->memory_); outputBuffer_.addMemoryDump(leak->memory_, leak->size_); if (SimpleString::StrCmp(leak->allocator_->alloc_name(), (const char*) "malloc") == 0) @@ -205,9 +206,9 @@ void MemoryLeakOutputStringBuffer::addErrorMessageForTooMuchLeaks() outputBuffer_.add(MEM_LEAK_TOO_MUCH); } -void MemoryLeakOutputStringBuffer::addMemoryLeakFooter(int amountOfLeaks) +void MemoryLeakOutputStringBuffer::addMemoryLeakFooter(size_t amountOfLeaks) { - outputBuffer_.add("%s %d\n", MEM_LEAK_FOOTER, amountOfLeaks); + outputBuffer_.add("%s %d\n", MEM_LEAK_FOOTER, (int) amountOfLeaks); } void MemoryLeakOutputStringBuffer::addWarningForUsingMalloc() @@ -215,22 +216,22 @@ void MemoryLeakOutputStringBuffer::addWarningForUsingMalloc() outputBuffer_.add(MEM_LEAK_ADDITION_MALLOC_WARNING); } -void MemoryLeakOutputStringBuffer::reportDeallocateNonAllocatedMemoryFailure(const char* freeFile, int freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) +void MemoryLeakOutputStringBuffer::reportDeallocateNonAllocatedMemoryFailure(const char* freeFile, size_t freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) { reportFailure("Deallocating non-allocated memory\n", "", 0, 0, NullUnknownAllocator::defaultAllocator(), freeFile, freeLine, freeAllocator, reporter); } -void MemoryLeakOutputStringBuffer::reportAllocationDeallocationMismatchFailure(MemoryLeakDetectorNode* node, const char* freeFile, int freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) +void MemoryLeakOutputStringBuffer::reportAllocationDeallocationMismatchFailure(MemoryLeakDetectorNode* node, const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) { reportFailure("Allocation/deallocation type mismatch\n", node->file_, node->line_, node->size_, node->allocator_, freeFile, freeLineNumber, freeAllocator, reporter); } -void MemoryLeakOutputStringBuffer::reportMemoryCorruptionFailure(MemoryLeakDetectorNode* node, const char* freeFile, int freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) +void MemoryLeakOutputStringBuffer::reportMemoryCorruptionFailure(MemoryLeakDetectorNode* node, const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) { reportFailure("Memory corruption (written out of bounds?)\n", node->file_, node->line_, node->size_, node->allocator_, freeFile, freeLineNumber, freeAllocator, reporter); } -void MemoryLeakOutputStringBuffer::reportFailure(const char* message, const char* allocFile, int allocLine, size_t allocSize, TestMemoryAllocator* allocAllocator, const char* freeFile, int freeLine, +void MemoryLeakOutputStringBuffer::reportFailure(const char* message, const char* allocFile, size_t allocLine, size_t allocSize, TestMemoryAllocator* allocAllocator, const char* freeFile, size_t freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) { outputBuffer_.add("%s", message); @@ -252,13 +253,14 @@ void MemoryLeakOutputStringBuffer::clear() //////////////////////// -void MemoryLeakDetectorNode::init(char* memory, unsigned number, size_t size, TestMemoryAllocator* allocator, MemLeakPeriod period, const char* file, int line) +void MemoryLeakDetectorNode::init(char* memory, unsigned number, size_t size, TestMemoryAllocator* allocator, MemLeakPeriod period, unsigned char allocation_stage, const char* file, size_t line) { number_ = number; memory_ = memory; size_ = size; allocator_ = allocator; period_ = period; + allocation_stage_ = allocation_stage; file_ = file; line_ = line; } @@ -270,10 +272,15 @@ bool MemoryLeakDetectorList::isInPeriod(MemoryLeakDetectorNode* node, MemLeakPer return period == mem_leak_period_all || node->period_ == period || (node->period_ != mem_leak_period_disabled && period == mem_leak_period_enabled); } +bool MemoryLeakDetectorList::isInAllocationStage(MemoryLeakDetectorNode* node, unsigned char allocation_stage) +{ + return node->allocation_stage_ == allocation_stage; +} + void MemoryLeakDetectorList::clearAllAccounting(MemLeakPeriod period) { MemoryLeakDetectorNode* cur = head_; - MemoryLeakDetectorNode* prev = 0; + MemoryLeakDetectorNode* prev = NULLPTR; while (cur) { if (isInPeriod(cur, period)) { @@ -301,7 +308,7 @@ void MemoryLeakDetectorList::addNewNode(MemoryLeakDetectorNode* node) MemoryLeakDetectorNode* MemoryLeakDetectorList::removeNode(char* memory) { MemoryLeakDetectorNode* cur = head_; - MemoryLeakDetectorNode* prev = 0; + MemoryLeakDetectorNode* prev = NULLPTR; while (cur) { if (cur->memory_ == memory) { if (prev) { @@ -316,7 +323,7 @@ MemoryLeakDetectorNode* MemoryLeakDetectorList::removeNode(char* memory) prev = cur; cur = cur->next_; } - return 0; + return NULLPTR; } MemoryLeakDetectorNode* MemoryLeakDetectorList::retrieveNode(char* memory) @@ -327,14 +334,21 @@ MemoryLeakDetectorNode* MemoryLeakDetectorList::retrieveNode(char* memory) return cur; cur = cur->next_; } - return NULL; + return NULLPTR; } MemoryLeakDetectorNode* MemoryLeakDetectorList::getLeakFrom(MemoryLeakDetectorNode* node, MemLeakPeriod period) { for (MemoryLeakDetectorNode* cur = node; cur; cur = cur->next_) if (isInPeriod(cur, period)) return cur; - return 0; + return NULLPTR; +} + +MemoryLeakDetectorNode* MemoryLeakDetectorList::getLeakForAllocationStageFrom(MemoryLeakDetectorNode* node, unsigned char allocation_stage) +{ + for (MemoryLeakDetectorNode* cur = node; cur; cur = cur->next_) + if (isInAllocationStage(cur, allocation_stage)) return cur; + return NULLPTR; } MemoryLeakDetectorNode* MemoryLeakDetectorList::getFirstLeak(MemLeakPeriod period) @@ -342,14 +356,26 @@ MemoryLeakDetectorNode* MemoryLeakDetectorList::getFirstLeak(MemLeakPeriod perio return getLeakFrom(head_, period); } +MemoryLeakDetectorNode* MemoryLeakDetectorList::getFirstLeakForAllocationStage(unsigned char allocation_stage) +{ + return getLeakForAllocationStageFrom(head_, allocation_stage); +} + MemoryLeakDetectorNode* MemoryLeakDetectorList::getNextLeak(MemoryLeakDetectorNode* node, MemLeakPeriod period) { return getLeakFrom(node->next_, period); } -int MemoryLeakDetectorList::getTotalLeaks(MemLeakPeriod period) +MemoryLeakDetectorNode* MemoryLeakDetectorList::getNextLeakForAllocationStage(MemoryLeakDetectorNode* node, unsigned char allocation_stage) { - int total_leaks = 0; + return getLeakForAllocationStageFrom(node->next_, allocation_stage); +} + + + +size_t MemoryLeakDetectorList::getTotalLeaks(MemLeakPeriod period) +{ + size_t total_leaks = 0; for (MemoryLeakDetectorNode* node = head_; node; node = node->next_) { if (isInPeriod(node, period)) total_leaks++; } @@ -384,9 +410,9 @@ MemoryLeakDetectorNode* MemoryLeakDetectorTable::retrieveNode(char* memory) return table_[hash(memory)].retrieveNode(memory); } -int MemoryLeakDetectorTable::getTotalLeaks(MemLeakPeriod period) +size_t MemoryLeakDetectorTable::getTotalLeaks(MemLeakPeriod period) { - int total_leaks = 0; + size_t total_leaks = 0; for (int i = 0; i < hash_prime; i++) total_leaks += table_[i].getTotalLeaks(period); return total_leaks; @@ -398,7 +424,16 @@ MemoryLeakDetectorNode* MemoryLeakDetectorTable::getFirstLeak(MemLeakPeriod peri MemoryLeakDetectorNode* node = table_[i].getFirstLeak(period); if (node) return node; } - return 0; + return NULLPTR; +} + +MemoryLeakDetectorNode* MemoryLeakDetectorTable::getFirstLeakForAllocationStage(unsigned char allocation_stage) +{ + for (int i = 0; i < hash_prime; i++) { + MemoryLeakDetectorNode* node = table_[i].getFirstLeakForAllocationStage(allocation_stage); + if (node) return node; + } + return NULLPTR; } MemoryLeakDetectorNode* MemoryLeakDetectorTable::getNextLeak(MemoryLeakDetectorNode* leak, MemLeakPeriod period) @@ -411,7 +446,20 @@ MemoryLeakDetectorNode* MemoryLeakDetectorTable::getNextLeak(MemoryLeakDetectorN node = table_[i].getFirstLeak(period); if (node) return node; } - return 0; + return NULLPTR; +} + +MemoryLeakDetectorNode* MemoryLeakDetectorTable::getNextLeakForAllocationStage(MemoryLeakDetectorNode* leak, unsigned char allocation_stage) +{ + unsigned long i = hash(leak->memory_); + MemoryLeakDetectorNode* node = table_[i].getNextLeakForAllocationStage(leak, allocation_stage); + if (node) return node; + + for (++i; i < hash_prime; i++) { + node = table_[i].getFirstLeakForAllocationStage(allocation_stage); + if (node) return node; + } + return NULLPTR; } ///////////////////////////////////////////////////////////// @@ -421,6 +469,7 @@ MemoryLeakDetector::MemoryLeakDetector(MemoryLeakFailure* reporter) doAllocationTypeChecking_ = true; allocationSequenceNumber_ = 1; current_period_ = mem_leak_period_disabled; + current_allocation_stage_ = 0; reporter_ = reporter; mutex_ = new SimpleMutex; } @@ -449,6 +498,11 @@ void MemoryLeakDetector::stopChecking() current_period_ = mem_leak_period_enabled; } +unsigned char MemoryLeakDetector::getCurrentAllocationStage() const +{ + return current_allocation_stage_; +} + void MemoryLeakDetector::enable() { current_period_ = mem_leak_period_enabled; @@ -474,6 +528,16 @@ unsigned MemoryLeakDetector::getCurrentAllocationNumber() return allocationSequenceNumber_; } +void MemoryLeakDetector::increaseAllocationStage() +{ + current_allocation_stage_++; +} + +void MemoryLeakDetector::decreaseAllocationStage() +{ + current_allocation_stage_--; +} + SimpleMutex *MemoryLeakDetector::getMutex() { return mutex_; @@ -481,7 +545,11 @@ SimpleMutex *MemoryLeakDetector::getMutex() static size_t calculateVoidPointerAlignedSize(size_t size) { +#ifndef CPPUTEST_DISABLE_MEM_CORRUPTION_CHECK return (sizeof(void*) - (size % sizeof(void*))) + size; +#else + return size; +#endif } size_t MemoryLeakDetector::sizeOfMemoryWithCorruptionInfo(size_t size) @@ -494,17 +562,17 @@ MemoryLeakDetectorNode* MemoryLeakDetector::getNodeFromMemoryPointer(char* memor return (MemoryLeakDetectorNode*) (void*) (memory + sizeOfMemoryWithCorruptionInfo(memory_size)); } -void MemoryLeakDetector::storeLeakInformation(MemoryLeakDetectorNode * node, char *new_memory, size_t size, TestMemoryAllocator *allocator, const char *file, int line) +void MemoryLeakDetector::storeLeakInformation(MemoryLeakDetectorNode * node, char *new_memory, size_t size, TestMemoryAllocator *allocator, const char *file, size_t line) { - node->init(new_memory, allocationSequenceNumber_++, size, allocator, current_period_, file, line); + node->init(new_memory, allocationSequenceNumber_++, size, allocator, current_period_, current_allocation_stage_, file, line); addMemoryCorruptionInformation(node->memory_ + node->size_); memoryTable_.addNewNode(node); } -char* MemoryLeakDetector::reallocateMemoryAndLeakInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately) +char* MemoryLeakDetector::reallocateMemoryAndLeakInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, size_t line, bool allocatNodesSeperately) { char* new_memory = reallocateMemoryWithAccountingInformation(allocator, memory, size, file, line, allocatNodesSeperately); - if (new_memory == NULL) return NULL; + if (new_memory == NULLPTR) return NULLPTR; MemoryLeakDetectorNode *node = createMemoryLeakAccountingInformation(allocator, size, new_memory, allocatNodesSeperately); storeLeakInformation(node, new_memory, size, allocator, file, line); @@ -513,21 +581,25 @@ char* MemoryLeakDetector::reallocateMemoryAndLeakInformation(TestMemoryAllocator void MemoryLeakDetector::invalidateMemory(char* memory) { +#ifndef CPPUTEST_DISABLE_HEAP_POISON MemoryLeakDetectorNode* node = memoryTable_.retrieveNode(memory); if (node) PlatformSpecificMemset(memory, 0xCD, node->size_); +#endif } void MemoryLeakDetector::addMemoryCorruptionInformation(char* memory) { - memory[0] = 'B'; - memory[1] = 'A'; - memory[2] = 'S'; + for (size_t i=0; iisOfEqualType(alloc_allocator); } -void MemoryLeakDetector::checkForCorruption(MemoryLeakDetectorNode* node, const char* file, int line, TestMemoryAllocator* allocator, bool allocateNodesSeperately) +void MemoryLeakDetector::checkForCorruption(MemoryLeakDetectorNode* node, const char* file, size_t line, TestMemoryAllocator* allocator, bool allocateNodesSeperately) { - if (!matchingAllocation(node->allocator_, allocator)) - outputBuffer_.reportAllocationDeallocationMismatchFailure(node, file, line, allocator, reporter_); + if (!matchingAllocation(node->allocator_->actualAllocator(), allocator->actualAllocator())) + outputBuffer_.reportAllocationDeallocationMismatchFailure(node, file, line, allocator->actualAllocator(), reporter_); else if (!validMemoryCorruptionInformation(node->memory_ + node->size_)) - outputBuffer_.reportMemoryCorruptionFailure(node, file, line, allocator, reporter_); + outputBuffer_.reportMemoryCorruptionFailure(node, file, line, allocator->actualAllocator(), reporter_); else if (allocateNodesSeperately) allocator->freeMemoryLeakNode((char*) node); } @@ -552,13 +624,13 @@ char* MemoryLeakDetector::allocMemory(TestMemoryAllocator* allocator, size_t siz return allocMemory(allocator, size, UNKNOWN, 0, allocatNodesSeperately); } -char* MemoryLeakDetector::allocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, size_t size, const char* file, int line, bool allocatNodesSeperately) +char* MemoryLeakDetector::allocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, size_t size, const char* file, size_t line, bool allocatNodesSeperately) { if (allocatNodesSeperately) return allocator->alloc_memory(sizeOfMemoryWithCorruptionInfo(size), file, line); else return allocator->alloc_memory(sizeOfMemoryWithCorruptionInfo(size) + sizeof(MemoryLeakDetectorNode), file, line); } -char* MemoryLeakDetector::reallocateMemoryWithAccountingInformation(TestMemoryAllocator* /*allocator*/, char* memory, size_t size, const char* /*file*/, int /*line*/, bool allocatNodesSeperately) +char* MemoryLeakDetector::reallocateMemoryWithAccountingInformation(TestMemoryAllocator* /*allocator*/, char* memory, size_t size, const char* /*file*/, size_t /*line*/, bool allocatNodesSeperately) { if (allocatNodesSeperately) return (char*) PlatformSpecificRealloc(memory, sizeOfMemoryWithCorruptionInfo(size)); else return (char*) PlatformSpecificRealloc(memory, sizeOfMemoryWithCorruptionInfo(size) + sizeof(MemoryLeakDetectorNode)); @@ -570,8 +642,11 @@ MemoryLeakDetectorNode* MemoryLeakDetector::createMemoryLeakAccountingInformatio else return getNodeFromMemoryPointer(memory, size); } -char* MemoryLeakDetector::allocMemory(TestMemoryAllocator* allocator, size_t size, const char* file, int line, bool allocatNodesSeperately) +char* MemoryLeakDetector::allocMemory(TestMemoryAllocator* allocator, size_t size, const char* file, size_t line, bool allocatNodesSeperately) { +#ifdef CPPUTEST_DISABLE_MEM_CORRUPTION_CHECK + allocatNodesSeperately = true; +#endif /* With malloc, it is harder to guarantee that the allocator free is called. * This is because operator new is overloaded via linker symbols, but malloc just via #defines. * If the same allocation is used and the wrong free is called, it will deallocate the memory leak information @@ -580,7 +655,7 @@ char* MemoryLeakDetector::allocMemory(TestMemoryAllocator* allocator, size_t siz */ char* memory = allocateMemoryWithAccountingInformation(allocator, size, file, line, allocatNodesSeperately); - if (memory == NULL) return NULL; + if (memory == NULLPTR) return NULLPTR; MemoryLeakDetectorNode* node = createMemoryLeakAccountingInformation(allocator, size, memory, allocatNodesSeperately); storeLeakInformation(node, memory, size, allocator, file, line); @@ -593,18 +668,22 @@ void MemoryLeakDetector::removeMemoryLeakInformationWithoutCheckingOrDeallocatin if (allocatNodesSeperately) allocator->freeMemoryLeakNode( (char*) node); } -void MemoryLeakDetector::deallocMemory(TestMemoryAllocator* allocator, void* memory, const char* file, int line, bool allocatNodesSeperately) +void MemoryLeakDetector::deallocMemory(TestMemoryAllocator* allocator, void* memory, const char* file, size_t line, bool allocatNodesSeperately) { - if (memory == 0) return; + if (memory == NULLPTR) return; MemoryLeakDetectorNode* node = memoryTable_.removeNode((char*) memory); - if (node == NULL) { + if (node == NULLPTR) { outputBuffer_.reportDeallocateNonAllocatedMemoryFailure(file, line, allocator, reporter_); return; } +#ifdef CPPUTEST_DISABLE_MEM_CORRUPTION_CHECK + allocatNodesSeperately = true; +#endif if (!allocator->hasBeenDestroyed()) { + size_t size = node->size_; checkForCorruption(node, file, line, allocator, allocatNodesSeperately); - allocator->free_memory((char*) memory, file, line); + allocator->free_memory((char*) memory, size, file, line); } } @@ -613,13 +692,28 @@ void MemoryLeakDetector::deallocMemory(TestMemoryAllocator* allocator, void* mem deallocMemory(allocator, (char*) memory, UNKNOWN, 0, allocatNodesSeperately); } -char* MemoryLeakDetector::reallocMemory(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately) +void MemoryLeakDetector::deallocAllMemoryInCurrentAllocationStage() +{ + char* memory = NULLPTR; + MemoryLeakDetectorNode* node = memoryTable_.getFirstLeakForAllocationStage(current_allocation_stage_); + while (node) { + memory = node->memory_; + TestMemoryAllocator* allocator = node->allocator_; + node = memoryTable_.getNextLeakForAllocationStage(node, current_allocation_stage_); + deallocMemory(allocator, memory, __FILE__, __LINE__); + } +} + +char* MemoryLeakDetector::reallocMemory(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, size_t line, bool allocatNodesSeperately) { +#ifdef CPPUTEST_DISABLE_MEM_CORRUPTION_CHECK + allocatNodesSeperately = true; +#endif if (memory) { MemoryLeakDetectorNode* node = memoryTable_.removeNode(memory); - if (node == NULL) { + if (node == NULLPTR) { outputBuffer_.reportDeallocateNonAllocatedMemoryFailure(file, line, allocator, reporter_); - return NULL; + return NULLPTR; } checkForCorruption(node, file, line, allocator, allocatNodesSeperately); } @@ -656,7 +750,7 @@ void MemoryLeakDetector::markCheckingPeriodLeaksAsNonCheckingPeriod() } } -int MemoryLeakDetector::totalMemoryLeaks(MemLeakPeriod period) +size_t MemoryLeakDetector::totalMemoryLeaks(MemLeakPeriod period) { return memoryTable_.getTotalLeaks(period); } diff --git a/src/CppUTest/MemoryLeakWarningPlugin.cpp b/src/CppUTest/MemoryLeakWarningPlugin.cpp index 00d6e164a..e954d6338 100644 --- a/src/CppUTest/MemoryLeakWarningPlugin.cpp +++ b/src/CppUTest/MemoryLeakWarningPlugin.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -44,80 +44,83 @@ class MemLeakScopedMutex ScopedMutexLock lock; }; -static void* threadsafe_mem_leak_malloc(size_t size, const char* file, int line) +static void* threadsafe_mem_leak_malloc(size_t size, const char* file, size_t line) { MemLeakScopedMutex lock; return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentMallocAllocator(), size, file, line, true); } -static void threadsafe_mem_leak_free(void* buffer, const char* file, int line) +static void threadsafe_mem_leak_free(void* buffer, const char* file, size_t line) { MemLeakScopedMutex lock; MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) buffer); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentMallocAllocator(), (char*) buffer, file, line, true); } -static void* threadsafe_mem_leak_realloc(void* memory, size_t size, const char* file, int line) +static void* threadsafe_mem_leak_realloc(void* memory, size_t size, const char* file, size_t line) { MemLeakScopedMutex lock; return MemoryLeakWarningPlugin::getGlobalDetector()->reallocMemory(getCurrentMallocAllocator(), (char*) memory, size, file, line, true); } -static void* mem_leak_malloc(size_t size, const char* file, int line) +static void* mem_leak_malloc(size_t size, const char* file, size_t line) { return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentMallocAllocator(), size, file, line, true); } -static void mem_leak_free(void* buffer, const char* file, int line) +static void mem_leak_free(void* buffer, const char* file, size_t line) { MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) buffer); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentMallocAllocator(), (char*) buffer, file, line, true); } -static void* mem_leak_realloc(void* memory, size_t size, const char* file, int line) +static void* mem_leak_realloc(void* memory, size_t size, const char* file, size_t line) { return MemoryLeakWarningPlugin::getGlobalDetector()->reallocMemory(getCurrentMallocAllocator(), (char*) memory, size, file, line, true); } #endif -static void* normal_malloc(size_t size, const char*, int) +static void* normal_malloc(size_t size, const char*, size_t) { return PlatformSpecificMalloc(size); } -static void* normal_realloc(void* memory, size_t size, const char*, int) +static void* normal_realloc(void* memory, size_t size, const char*, size_t) { return PlatformSpecificRealloc(memory, size); } -static void normal_free(void* buffer, const char*, int) +static void normal_free(void* buffer, const char*, size_t) { PlatformSpecificFree(buffer); } #if CPPUTEST_USE_MEM_LEAK_DETECTION -static void *(*malloc_fptr)(size_t size, const char* file, int line) = mem_leak_malloc; -static void (*free_fptr)(void* mem, const char* file, int line) = mem_leak_free; -static void*(*realloc_fptr)(void* memory, size_t size, const char* file, int line) = mem_leak_realloc; +static void *(*malloc_fptr)(size_t size, const char* file, size_t line) = mem_leak_malloc; +static void (*free_fptr)(void* mem, const char* file, size_t line) = mem_leak_free; +static void*(*realloc_fptr)(void* memory, size_t size, const char* file, size_t line) = mem_leak_realloc; +static void *(*saved_malloc_fptr)(size_t size, const char* file, size_t line) = mem_leak_malloc; +static void (*saved_free_fptr)(void* mem, const char* file, size_t line) = mem_leak_free; +static void*(*saved_realloc_fptr)(void* memory, size_t size, const char* file, size_t line) = mem_leak_realloc; #else -static void *(*malloc_fptr)(size_t size, const char* file, int line) = normal_malloc; -static void (*free_fptr)(void* mem, const char* file, int line) = normal_free; -static void*(*realloc_fptr)(void* memory, size_t size, const char* file, int line) = normal_realloc; +static void *(*malloc_fptr)(size_t size, const char* file, size_t line) = normal_malloc; +static void (*free_fptr)(void* mem, const char* file, size_t line) = normal_free; +static void*(*realloc_fptr)(void* memory, size_t size, const char* file, size_t line) = normal_realloc; #endif -void* cpputest_malloc_location_with_leak_detection(size_t size, const char* file, int line) +void* cpputest_malloc_location_with_leak_detection(size_t size, const char* file, size_t line) { return malloc_fptr(size, file, line); } -void* cpputest_realloc_location_with_leak_detection(void* memory, size_t size, const char* file, int line) +void* cpputest_realloc_location_with_leak_detection(void* memory, size_t size, const char* file, size_t line) { return realloc_fptr(memory, size, file, line); } -void cpputest_free_location_with_leak_detection(void* buffer, const char* file, int line) +void cpputest_free_location_with_leak_detection(void* buffer, const char* file, size_t line) { free_fptr(buffer, file, line); } @@ -127,13 +130,13 @@ void cpputest_free_location_with_leak_detection(void* buffer, const char* file, #if CPPUTEST_USE_MEM_LEAK_DETECTION #undef new -#if CPPUTEST_USE_STD_CPP_LIB -#define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) if (memory == NULL) throw std::bad_alloc(); +#if CPPUTEST_HAVE_EXCEPTIONS +#define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) if ((memory) == NULLPTR) throw CPPUTEST_BAD_ALLOC() #else #define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) #endif -static void* threadsafe_mem_leak_operator_new (size_t size) UT_THROW(std::bad_alloc) +static void* threadsafe_mem_leak_operator_new (size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { MemLeakScopedMutex lock; void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size); @@ -147,15 +150,15 @@ static void* threadsafe_mem_leak_operator_new_nothrow (size_t size) UT_NOTHROW return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size); } -static void* threadsafe_mem_leak_operator_new_debug (size_t size, const char* file, int line) UT_THROW(std::bad_alloc) +static void* threadsafe_mem_leak_operator_new_debug (size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { MemLeakScopedMutex lock; - void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size, (char*) file, line); + void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size, file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } -static void* threadsafe_mem_leak_operator_new_array (size_t size) UT_THROW(std::bad_alloc) +static void* threadsafe_mem_leak_operator_new_array (size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { MemLeakScopedMutex lock; void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size); @@ -169,10 +172,10 @@ static void* threadsafe_mem_leak_operator_new_array_nothrow (size_t size) UT_NOT return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size); } -static void* threadsafe_mem_leak_operator_new_array_debug (size_t size, const char* file, int line) UT_THROW(std::bad_alloc) +static void* threadsafe_mem_leak_operator_new_array_debug (size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { MemLeakScopedMutex lock; - void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, (char*) file, line); + void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } @@ -192,7 +195,7 @@ static void threadsafe_mem_leak_operator_delete_array (void* mem) UT_NOTHROW } -static void* mem_leak_operator_new (size_t size) UT_THROW(std::bad_alloc) +static void* mem_leak_operator_new (size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); @@ -204,14 +207,14 @@ static void* mem_leak_operator_new_nothrow (size_t size) UT_NOTHROW return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size); } -static void* mem_leak_operator_new_debug (size_t size, const char* file, int line) UT_THROW(std::bad_alloc) +static void* mem_leak_operator_new_debug (size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { - void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size, (char*) file, line); + void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size, file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } -static void* mem_leak_operator_new_array (size_t size) UT_THROW(std::bad_alloc) +static void* mem_leak_operator_new_array (size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); @@ -223,9 +226,9 @@ static void* mem_leak_operator_new_array_nothrow (size_t size) UT_NOTHROW return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size); } -static void* mem_leak_operator_new_array_debug (size_t size, const char* file, int line) UT_THROW(std::bad_alloc) +static void* mem_leak_operator_new_array_debug (size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { - void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, (char*) file, line); + void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } @@ -242,7 +245,7 @@ static void mem_leak_operator_delete_array (void* mem) UT_NOTHROW MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewArrayAllocator(), (char*) mem); } -static void* normal_operator_new (size_t size) UT_THROW(std::bad_alloc) +static void* normal_operator_new (size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { void* memory = PlatformSpecificMalloc(size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); @@ -254,14 +257,14 @@ static void* normal_operator_new_nothrow (size_t size) UT_NOTHROW return PlatformSpecificMalloc(size); } -static void* normal_operator_new_debug (size_t size, const char* /*file*/, int /*line*/) UT_THROW(std::bad_alloc) +static void* normal_operator_new_debug (size_t size, const char* /*file*/, size_t /*line*/) UT_THROW(CPPUTEST_BAD_ALLOC) { void* memory = PlatformSpecificMalloc(size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } -static void* normal_operator_new_array (size_t size) UT_THROW(std::bad_alloc) +static void* normal_operator_new_array (size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { void* memory = PlatformSpecificMalloc(size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); @@ -273,7 +276,7 @@ static void* normal_operator_new_array_nothrow (size_t size) UT_NOTHROW return PlatformSpecificMalloc(size); } -static void* normal_operator_new_array_debug (size_t size, const char* /*file*/, int /*line*/) UT_THROW(std::bad_alloc) +static void* normal_operator_new_array_debug (size_t size, const char* /*file*/, size_t /*line*/) UT_THROW(CPPUTEST_BAD_ALLOC) { void* memory = PlatformSpecificMalloc(size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); @@ -290,21 +293,36 @@ static void normal_operator_delete_array (void* mem) UT_NOTHROW PlatformSpecificFree(mem); } -static void *(*operator_new_fptr)(size_t size) UT_THROW(std::bad_alloc) = mem_leak_operator_new; +static void *(*operator_new_fptr)(size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new; static void *(*operator_new_nothrow_fptr)(size_t size) UT_NOTHROW = mem_leak_operator_new_nothrow; -static void *(*operator_new_debug_fptr)(size_t size, const char* file, int line) UT_THROW(std::bad_alloc) = mem_leak_operator_new_debug; -static void *(*operator_new_array_fptr)(size_t size) UT_THROW(std::bad_alloc) = mem_leak_operator_new_array; +static void *(*operator_new_debug_fptr)(size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_debug; +static void *(*operator_new_array_fptr)(size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_array; static void *(*operator_new_array_nothrow_fptr)(size_t size) UT_NOTHROW = mem_leak_operator_new_array_nothrow; -static void *(*operator_new_array_debug_fptr)(size_t size, const char* file, int line) UT_THROW(std::bad_alloc) = mem_leak_operator_new_array_debug; +static void *(*operator_new_array_debug_fptr)(size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_array_debug; static void (*operator_delete_fptr)(void* mem) UT_NOTHROW = mem_leak_operator_delete; static void (*operator_delete_array_fptr)(void* mem) UT_NOTHROW = mem_leak_operator_delete_array; -void* operator new(size_t size) UT_THROW(std::bad_alloc) +static void *(*saved_operator_new_fptr)(size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new; +static void *(*saved_operator_new_nothrow_fptr)(size_t size) UT_NOTHROW = mem_leak_operator_new_nothrow; +static void *(*saved_operator_new_debug_fptr)(size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_debug; +static void *(*saved_operator_new_array_fptr)(size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_array; +static void *(*saved_operator_new_array_nothrow_fptr)(size_t size) UT_NOTHROW = mem_leak_operator_new_array_nothrow; +static void *(*saved_operator_new_array_debug_fptr)(size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_array_debug; +static void (*saved_operator_delete_fptr)(void* mem) UT_NOTHROW = mem_leak_operator_delete; +static void (*saved_operator_delete_array_fptr)(void* mem) UT_NOTHROW = mem_leak_operator_delete_array; +static int save_counter = 0; + +void* operator new(size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { return operator_new_fptr(size); } -void* operator new(size_t size, const char* file, int line) UT_THROW(std::bad_alloc) +void* operator new(size_t size, const char* file, int line) UT_THROW(CPPUTEST_BAD_ALLOC) +{ + return operator_new_debug_fptr(size, file, (size_t)line); +} + +void* operator new(size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { return operator_new_debug_fptr(size, file, line); } @@ -319,17 +337,29 @@ void operator delete(void* mem, const char*, int) UT_NOTHROW operator_delete_fptr(mem); } +void operator delete(void* mem, const char*, size_t) UT_NOTHROW +{ + operator_delete_fptr(mem); +} + +#if __cplusplus >= 201402L void operator delete (void* mem, size_t) UT_NOTHROW { operator_delete_fptr(mem); } +#endif -void* operator new[](size_t size) UT_THROW(std::bad_alloc) +void* operator new[](size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { return operator_new_array_fptr(size); } -void* operator new [](size_t size, const char* file, int line) UT_THROW(std::bad_alloc) +void* operator new [](size_t size, const char* file, int line) UT_THROW(CPPUTEST_BAD_ALLOC) +{ + return operator_new_array_debug_fptr(size, file, (size_t)line); +} + +void* operator new [](size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { return operator_new_array_debug_fptr(size, file, line); } @@ -344,10 +374,17 @@ void operator delete[](void* mem, const char*, int) UT_NOTHROW operator_delete_array_fptr(mem); } +void operator delete[](void* mem, const char*, size_t) UT_NOTHROW +{ + operator_delete_array_fptr(mem); +} + +#if __cplusplus >= 201402L void operator delete[] (void* mem, size_t) UT_NOTHROW { operator_delete_array_fptr(mem); } +#endif #if CPPUTEST_USE_STD_CPP_LIB @@ -356,11 +393,21 @@ void* operator new(size_t size, const std::nothrow_t&) UT_NOTHROW return operator_new_nothrow_fptr(size); } +void operator delete(void* mem, const std::nothrow_t&) UT_NOTHROW +{ + operator_delete_fptr(mem); +} + void* operator new[](size_t size, const std::nothrow_t&) UT_NOTHROW { return operator_new_array_nothrow_fptr(size); } +void operator delete[](void* mem, const std::nothrow_t&) UT_NOTHROW +{ + operator_delete_array_fptr(mem); +} + #else /* Have a similar method. This avoid unused operator_new_nothrow_fptr warning */ @@ -399,7 +446,7 @@ void MemoryLeakWarningPlugin::turnOffNewDeleteOverloads() #endif } -void MemoryLeakWarningPlugin::turnOnNewDeleteOverloads() +void MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads() { #if CPPUTEST_USE_MEM_LEAK_DETECTION operator_new_fptr = mem_leak_operator_new; @@ -416,15 +463,6 @@ void MemoryLeakWarningPlugin::turnOnNewDeleteOverloads() #endif } -bool MemoryLeakWarningPlugin::areNewDeleteOverloaded() -{ -#if CPPUTEST_USE_MEM_LEAK_DETECTION - return operator_new_fptr == mem_leak_operator_new; -#else - return false; -#endif -} - void MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads() { #if CPPUTEST_USE_MEM_LEAK_DETECTION @@ -442,6 +480,52 @@ void MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads() #endif } +bool MemoryLeakWarningPlugin::areNewDeleteOverloaded() +{ +#if CPPUTEST_USE_MEM_LEAK_DETECTION + return operator_new_fptr == mem_leak_operator_new || operator_new_fptr == threadsafe_mem_leak_operator_new; +#else + return false; +#endif +} + +void MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads() +{ +#if CPPUTEST_USE_MEM_LEAK_DETECTION + if (++save_counter > 1) return; + saved_operator_new_fptr = operator_new_fptr; + saved_operator_new_nothrow_fptr = operator_new_nothrow_fptr; + saved_operator_new_debug_fptr = operator_new_debug_fptr; + saved_operator_new_array_fptr = operator_new_array_fptr; + saved_operator_new_array_nothrow_fptr = operator_new_array_nothrow_fptr; + saved_operator_new_array_debug_fptr = operator_new_array_debug_fptr; + saved_operator_delete_fptr = operator_delete_fptr; + saved_operator_delete_array_fptr = operator_delete_array_fptr; + saved_malloc_fptr = malloc_fptr; + saved_realloc_fptr = realloc_fptr; + saved_free_fptr = free_fptr; + turnOffNewDeleteOverloads(); +#endif +} + +void MemoryLeakWarningPlugin::restoreNewDeleteOverloads() +{ +#if CPPUTEST_USE_MEM_LEAK_DETECTION + if (--save_counter > 0) return; + operator_new_fptr = saved_operator_new_fptr; + operator_new_nothrow_fptr = saved_operator_new_nothrow_fptr; + operator_new_debug_fptr = saved_operator_new_debug_fptr; + operator_new_array_fptr = saved_operator_new_array_fptr; + operator_new_array_nothrow_fptr = saved_operator_new_array_nothrow_fptr; + operator_new_array_debug_fptr = saved_operator_new_array_debug_fptr; + operator_delete_fptr = saved_operator_delete_fptr; + operator_delete_array_fptr = saved_operator_delete_array_fptr; + malloc_fptr = saved_malloc_fptr; + realloc_fptr = saved_realloc_fptr; + free_fptr = saved_free_fptr; +#endif +} + void crash_on_allocation_number(unsigned alloc_number) { static CrashOnAllocationAllocator crashAllocator; @@ -454,30 +538,29 @@ void crash_on_allocation_number(unsigned alloc_number) class MemoryLeakWarningReporter: public MemoryLeakFailure { public: - virtual ~MemoryLeakWarningReporter() + virtual ~MemoryLeakWarningReporter() CPPUTEST_DESTRUCTOR_OVERRIDE { } - virtual void fail(char* fail_string) + virtual void fail(char* fail_string) CPPUTEST_OVERRIDE { UtestShell* currentTest = UtestShell::getCurrent(); - currentTest->failWith(FailFailure(currentTest, currentTest->getName().asCharString(), currentTest->getLineNumber(), fail_string), TestTerminatorWithoutExceptions()); + currentTest->failWith(FailFailure(currentTest, currentTest->getName().asCharString(), currentTest->getLineNumber(), fail_string), UtestShell::getCurrentTestTerminatorWithoutExceptions()); } // LCOV_EXCL_LINE }; -static MemoryLeakFailure* globalReporter = 0; -static MemoryLeakDetector* globalDetector = 0; +static MemoryLeakFailure* globalReporter = NULLPTR; +static MemoryLeakDetector* globalDetector = NULLPTR; MemoryLeakDetector* MemoryLeakWarningPlugin::getGlobalDetector() { - if (globalDetector == 0) { - bool newDeleteOverloaded = areNewDeleteOverloaded(); - turnOffNewDeleteOverloads(); + if (globalDetector == NULLPTR) { + saveAndDisableNewDeleteOverloads(); globalReporter = new MemoryLeakWarningReporter; globalDetector = new MemoryLeakDetector(globalReporter); - if (newDeleteOverloaded) turnOnNewDeleteOverloads(); + restoreNewDeleteOverloads(); } return globalDetector; } @@ -503,11 +586,11 @@ void MemoryLeakWarningPlugin::destroyGlobalDetector() turnOffNewDeleteOverloads(); delete globalDetector; delete globalReporter; - globalDetector = NULL; + globalDetector = NULLPTR; } -MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::firstPlugin_ = 0; +MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::firstPlugin_ = NULLPTR; MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::getFirstPlugin() { @@ -524,7 +607,7 @@ void MemoryLeakWarningPlugin::ignoreAllLeaksInTest() ignoreAllWarnings_ = true; } -void MemoryLeakWarningPlugin::expectLeaksInTest(int n) +void MemoryLeakWarningPlugin::expectLeaksInTest(size_t n) { expectedLeaks_ = n; } @@ -532,7 +615,7 @@ void MemoryLeakWarningPlugin::expectLeaksInTest(int n) MemoryLeakWarningPlugin::MemoryLeakWarningPlugin(const SimpleString& name, MemoryLeakDetector* localDetector) : TestPlugin(name), ignoreAllWarnings_(false), destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_(false), expectedLeaks_(0) { - if (firstPlugin_ == 0) firstPlugin_ = this; + if (firstPlugin_ == NULLPTR) firstPlugin_ = this; if (localDetector) memLeakDetector_ = localDetector; else memLeakDetector_ = getGlobalDetector(); @@ -557,20 +640,24 @@ void MemoryLeakWarningPlugin::preTestAction(UtestShell& /*test*/, TestResult& re void MemoryLeakWarningPlugin::postTestAction(UtestShell& test, TestResult& result) { memLeakDetector_->stopChecking(); - int leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_checking); + size_t leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_checking); if (!ignoreAllWarnings_ && expectedLeaks_ != leaks && failureCount_ == result.getFailureCount()) { - TestFailure f(&test, memLeakDetector_->report(mem_leak_period_checking)); - result.addFailure(f); + if(MemoryLeakWarningPlugin::areNewDeleteOverloaded()) { + TestFailure f(&test, memLeakDetector_->report(mem_leak_period_checking)); + result.addFailure(f); + } else if(expectedLeaks_ > 0) { + result.print(StringFromFormat("Warning: Expected %d leak(s), but leak detection was disabled", (int) expectedLeaks_).asCharString()); + } } memLeakDetector_->markCheckingPeriodLeaksAsNonCheckingPeriod(); ignoreAllWarnings_ = false; expectedLeaks_ = 0; } -const char* MemoryLeakWarningPlugin::FinalReport(int toBeDeletedLeaks) +const char* MemoryLeakWarningPlugin::FinalReport(size_t toBeDeletedLeaks) { - int leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_enabled); + size_t leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_enabled); if (leaks != toBeDeletedLeaks) return memLeakDetector_->report(mem_leak_period_enabled); return ""; } diff --git a/src/CppUTest/SimpleMutex.cpp b/src/CppUTest/SimpleMutex.cpp index a1f4d7027..8fd9c887f 100644 --- a/src/CppUTest/SimpleMutex.cpp +++ b/src/CppUTest/SimpleMutex.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/src/CppUTest/SimpleString.cpp b/src/CppUTest/SimpleString.cpp index b63fcc935..a62491e32 100644 --- a/src/CppUTest/SimpleString.cpp +++ b/src/CppUTest/SimpleString.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,11 +30,83 @@ #include "CppUTest/PlatformSpecificFunctions.h" #include "CppUTest/TestMemoryAllocator.h" -TestMemoryAllocator* SimpleString::stringAllocator_ = NULL; +GlobalSimpleStringAllocatorStash::GlobalSimpleStringAllocatorStash() + : originalAllocator_(NULLPTR) +{ +} + +void GlobalSimpleStringAllocatorStash::save() +{ + originalAllocator_ = SimpleString::getStringAllocator(); +} + +void GlobalSimpleStringAllocatorStash::restore() +{ + SimpleString::setStringAllocator(originalAllocator_); +} + + +GlobalSimpleStringMemoryAccountant::GlobalSimpleStringMemoryAccountant() + : allocator_(NULLPTR) +{ + accountant_ = new MemoryAccountant(); +} + +GlobalSimpleStringMemoryAccountant::~GlobalSimpleStringMemoryAccountant() +{ + restoreAllocator(); + + delete accountant_; + delete allocator_; +} + +void GlobalSimpleStringMemoryAccountant::restoreAllocator() +{ + if (allocator_ && (SimpleString::getStringAllocator() == allocator_)) + SimpleString::setStringAllocator(allocator_->originalAllocator()); +} + +void GlobalSimpleStringMemoryAccountant::useCacheSizes(size_t cacheSizes[], size_t length) +{ + accountant_->useCacheSizes(cacheSizes, length); +} + +void GlobalSimpleStringMemoryAccountant::start() +{ + if (allocator_ != NULLPTR) + return; + + allocator_ = new AccountingTestMemoryAllocator(*accountant_, SimpleString::getStringAllocator()); + + SimpleString::setStringAllocator(allocator_); +} + +void GlobalSimpleStringMemoryAccountant::stop() +{ + if (allocator_ == NULLPTR) + FAIL("Global SimpleString allocator stopped without starting"); + + if (SimpleString::getStringAllocator() != allocator_) + FAIL("GlobalStrimpleStringMemoryAccountant: allocator has changed between start and stop!"); + + restoreAllocator(); +} + +SimpleString GlobalSimpleStringMemoryAccountant::report() +{ + return accountant_->report(); +} + +AccountingTestMemoryAllocator* GlobalSimpleStringMemoryAccountant::getAllocator() +{ + return allocator_; +} + +TestMemoryAllocator* SimpleString::stringAllocator_ = NULLPTR; TestMemoryAllocator* SimpleString::getStringAllocator() { - if (stringAllocator_ == NULL) + if (stringAllocator_ == NULLPTR) return defaultNewArrayAllocator(); return stringAllocator_; } @@ -45,14 +117,14 @@ void SimpleString::setStringAllocator(TestMemoryAllocator* allocator) } /* Avoid using the memory leak detector INSIDE SimpleString as its used inside the detector */ -char* SimpleString::allocStringBuffer(size_t _size, const char* file, int line) +char* SimpleString::allocStringBuffer(size_t _size, const char* file, size_t line) { return getStringAllocator()->alloc_memory(_size, file, line); } -void SimpleString::deallocStringBuffer(char* str, const char* file, int line) +void SimpleString::deallocStringBuffer(char* str, size_t size, const char* file, size_t line) { - getStringAllocator()->free_memory(str, file, line); + getStringAllocator()->free_memory(str, size, file, line); } char* SimpleString::getEmptyString() const @@ -62,6 +134,20 @@ char* SimpleString::getEmptyString() const return empty; } +// does not support + or - prefixes +unsigned SimpleString::AtoU(const char* str) +{ + while (isSpace(*str)) str++; + + unsigned result = 0; + for(; isDigit(*str) && *str >= '0'; str++) + { + result *= 10; + result += static_cast(*str - '0'); + } + return result; +} + int SimpleString::AtoI(const char* str) { while (isSpace(*str)) str++; @@ -80,9 +166,11 @@ int SimpleString::AtoI(const char* str) int SimpleString::StrCmp(const char* s1, const char* s2) { - while(*s1 && *s1 == *s2) - s1++, s2++; - return *(unsigned char *) s1 - *(unsigned char *) s2; + while(*s1 && *s1 == *s2) { + ++s1; + ++s2; + } + return *(const unsigned char *) s1 - *(const unsigned char *) s2; } size_t SimpleString::StrLen(const char* str) @@ -95,29 +183,33 @@ size_t SimpleString::StrLen(const char* str) int SimpleString::StrNCmp(const char* s1, const char* s2, size_t n) { while (n && *s1 && *s1 == *s2) { - n--, s1++, s2++; + --n; + ++s1; + ++s2; } - return n ? *(unsigned char *) s1 - *(unsigned char *) s2 : 0; + return n ? *(const unsigned char *) s1 - *(const unsigned char *) s2 : 0; } char* SimpleString::StrNCpy(char* s1, const char* s2, size_t n) { char* result = s1; - if((NULL == s1) || (0 == n)) return result; + if((NULLPTR == s1) || (0 == n)) return result; - while ((*s1++ = *s2++) && --n != 0) - ; + *s1 = *s2; + while ((--n != 0) && *s1){ + *++s1 = *++s2; + } return result; } -char* SimpleString::StrStr(const char* s1, const char* s2) +const char* SimpleString::StrStr(const char* s1, const char* s2) { - if(!*s2) return (char*) s1; + if(!*s2) return s1; for (; *s1; s1++) if (StrNCmp(s1, s2, StrLen(s2)) == 0) - return (char*) s1; - return NULL; + return s1; + return NULLPTR; } char SimpleString::ToLower(char ch) @@ -131,28 +223,87 @@ int SimpleString::MemCmp(const void* s1, const void *s2, size_t n) const unsigned char* p2 = (const unsigned char*) s2; while (n--) - if (*p1 != *p2) + if (*p1 != *p2) { return *p1 - *p2; - else - p1++, p2++; + } else { + ++p1; + ++p2; + } return 0; } -SimpleString::SimpleString(const char *otherBuffer) +void SimpleString::deallocateInternalBuffer() { - if (otherBuffer == 0) { - buffer_ = getEmptyString(); - } - else { - buffer_ = copyToNewBuffer(otherBuffer); + if (buffer_) { + deallocStringBuffer(buffer_, bufferSize_, __FILE__, __LINE__); + buffer_ = NULLPTR; + bufferSize_ = 0; } } +void SimpleString::setInternalBufferAsEmptyString() +{ + deallocateInternalBuffer(); + + bufferSize_ = 1; + buffer_ = getEmptyString(); +} + +void SimpleString::copyBufferToNewInternalBuffer(const char* otherBuffer, size_t bufferSize) +{ + deallocateInternalBuffer(); + + bufferSize_ = bufferSize; + buffer_ = copyToNewBuffer(otherBuffer, bufferSize_); +} + +void SimpleString::setInternalBufferToNewBuffer(size_t bufferSize) +{ + deallocateInternalBuffer(); + + bufferSize_ = bufferSize; + buffer_ = allocStringBuffer(bufferSize_, __FILE__, __LINE__); + buffer_[0] = '\0'; +} + +void SimpleString::setInternalBufferTo(char* buffer, size_t bufferSize) +{ + deallocateInternalBuffer(); + + bufferSize_ = bufferSize; + buffer_ = buffer; +} + +void SimpleString::copyBufferToNewInternalBuffer(const SimpleString& otherBuffer) +{ + copyBufferToNewInternalBuffer(otherBuffer.buffer_, otherBuffer.size() + 1); +} + +void SimpleString::copyBufferToNewInternalBuffer(const char* otherBuffer) +{ + copyBufferToNewInternalBuffer(otherBuffer, StrLen(otherBuffer) + 1); +} + +const char* SimpleString::getBuffer() const +{ + return buffer_; +} + +SimpleString::SimpleString(const char *otherBuffer) + : buffer_(NULLPTR), bufferSize_(0) +{ + if (otherBuffer == NULLPTR) + setInternalBufferAsEmptyString(); + else + copyBufferToNewInternalBuffer(otherBuffer); +} + SimpleString::SimpleString(const char *other, size_t repeatCount) + : buffer_(NULLPTR), bufferSize_(0) { size_t otherStringLength = StrLen(other); - size_t len = otherStringLength * repeatCount + 1; - buffer_ = allocStringBuffer(len, __FILE__, __LINE__); + setInternalBufferToNewBuffer(otherStringLength * repeatCount + 1); + char* next = buffer_; for (size_t i = 0; i < repeatCount; i++) { StrNCpy(next, other, otherStringLength + 1); @@ -162,22 +313,21 @@ SimpleString::SimpleString(const char *other, size_t repeatCount) } SimpleString::SimpleString(const SimpleString& other) + : buffer_(NULLPTR), bufferSize_(0) { - buffer_ = copyToNewBuffer(other.buffer_); + copyBufferToNewInternalBuffer(other.getBuffer()); } SimpleString& SimpleString::operator=(const SimpleString& other) { - if (this != &other) { - deallocStringBuffer(buffer_, __FILE__, __LINE__); - buffer_ = copyToNewBuffer(other.buffer_); - } + if (this != &other) + copyBufferToNewInternalBuffer(other); return *this; } bool SimpleString::contains(const SimpleString& other) const { - return StrStr(buffer_, other.buffer_) != 0; + return StrStr(getBuffer(), other.getBuffer()) != NULLPTR; } bool SimpleString::containsNoCase(const SimpleString& other) const @@ -187,28 +337,36 @@ bool SimpleString::containsNoCase(const SimpleString& other) const bool SimpleString::startsWith(const SimpleString& other) const { - if (StrLen(other.buffer_) == 0) return true; + if (other.size() == 0) return true; else if (size() == 0) return false; - else return StrStr(buffer_, other.buffer_) == buffer_; + else return StrStr(getBuffer(), other.getBuffer()) == getBuffer(); } bool SimpleString::endsWith(const SimpleString& other) const { - size_t buffer_length = size(); - size_t other_buffer_length = StrLen(other.buffer_); - if (other_buffer_length == 0) return true; - if (buffer_length == 0) return false; - if (buffer_length < other_buffer_length) return false; - return StrCmp(buffer_ + buffer_length - other_buffer_length, other.buffer_) == 0; + size_t length = size(); + size_t other_length = other.size(); + + if (other_length == 0) return true; + if (length == 0) return false; + if (length < other_length) return false; + + return StrCmp(getBuffer() + length - other_length, other.getBuffer()) == 0; } size_t SimpleString::count(const SimpleString& substr) const { size_t num = 0; - char* str = buffer_; - while (*str && (str = StrStr(str, substr.buffer_))) { - num++; + const char* str = getBuffer(); + const char* strpart = NULLPTR; + if (*str){ + strpart = StrStr(str, substr.getBuffer()); + } + while (*str && strpart) { + str = strpart; str++; + num++; + strpart = StrStr(str, substr.getBuffer()); } return num; } @@ -219,11 +377,11 @@ void SimpleString::split(const SimpleString& delimiter, SimpleStringCollection& size_t extraEndToken = (endsWith(delimiter)) ? 0 : 1U; col.allocate(num + extraEndToken); - char* str = buffer_; - char* prev; + const char* str = getBuffer(); + const char* prev; for (size_t i = 0; i < num; ++i) { prev = str; - str = StrStr(str, delimiter.buffer_) + 1; + str = StrStr(str, delimiter.getBuffer()) + 1; col[i] = SimpleString(prev).subString(0, size_t (str - prev)); } if (extraEndToken) { @@ -235,13 +393,16 @@ void SimpleString::replace(char to, char with) { size_t s = size(); for (size_t i = 0; i < s; i++) { - if (buffer_[i] == to) buffer_[i] = with; + if (getBuffer()[i] == to) buffer_[i] = with; } } void SimpleString::replace(const char* to, const char* with) { size_t c = count(to); + if (c == 0) { + return; + } size_t len = size(); size_t tolen = StrLen(to); size_t withlen = StrLen(with); @@ -251,25 +412,86 @@ void SimpleString::replace(const char* to, const char* with) if (newsize > 1) { char* newbuf = allocStringBuffer(newsize, __FILE__, __LINE__); for (size_t i = 0, j = 0; i < len;) { - if (StrNCmp(&buffer_[i], to, tolen) == 0) { + if (StrNCmp(&getBuffer()[i], to, tolen) == 0) { StrNCpy(&newbuf[j], with, withlen + 1); j += withlen; i += tolen; } else { - newbuf[j] = buffer_[i]; + newbuf[j] = getBuffer()[i]; j++; i++; } } - deallocStringBuffer(buffer_, __FILE__, __LINE__); - buffer_ = newbuf; - buffer_[newsize - 1] = '\0'; + newbuf[newsize - 1] = '\0'; + setInternalBufferTo(newbuf, newsize); } - else { - deallocStringBuffer(buffer_, __FILE__, __LINE__); - buffer_ = getEmptyString(); + else + setInternalBufferAsEmptyString(); +} + +SimpleString SimpleString::printable() const +{ + static const char* shortEscapeCodes[] = + { + "\\a", + "\\b", + "\\t", + "\\n", + "\\v", + "\\f", + "\\r" + }; + + SimpleString result; + result.setInternalBufferToNewBuffer(getPrintableSize() + 1); + + size_t str_size = size(); + size_t j = 0; + for (size_t i = 0; i < str_size; i++) + { + char c = buffer_[i]; + if (isControlWithShortEscapeSequence(c)) + { + StrNCpy(&result.buffer_[j], shortEscapeCodes[(unsigned char)(c - '\a')], 2); + j += 2; + } + else if (isControl(c)) + { + SimpleString hexEscapeCode = StringFromFormat("\\x%02X ", c); + StrNCpy(&result.buffer_[j], hexEscapeCode.asCharString(), 4); + j += 4; + } + else + { + result.buffer_[j] = c; + j++; + } } + result.buffer_[j] = 0; + + return result; +} + +size_t SimpleString::getPrintableSize() const +{ + size_t str_size = size(); + size_t printable_str_size = str_size; + + for (size_t i = 0; i < str_size; i++) + { + char c = buffer_[i]; + if (isControlWithShortEscapeSequence(c)) + { + printable_str_size += 1; + } + else if (isControl(c)) + { + printable_str_size += 3; + } + } + + return printable_str_size; } SimpleString SimpleString::lowerCase() const @@ -278,19 +500,19 @@ SimpleString SimpleString::lowerCase() const size_t str_size = str.size(); for (size_t i = 0; i < str_size; i++) - str.buffer_[i] = ToLower(str.buffer_[i]); + str.buffer_[i] = ToLower(str.getBuffer()[i]); return str; } const char *SimpleString::asCharString() const { - return buffer_; + return getBuffer(); } size_t SimpleString::size() const { - return StrLen(buffer_); + return StrLen(getBuffer()); } bool SimpleString::isEmpty() const @@ -298,10 +520,9 @@ bool SimpleString::isEmpty() const return size() == 0; } - SimpleString::~SimpleString() { - deallocStringBuffer(buffer_, __FILE__, __LINE__); + deallocateInternalBuffer(); } bool operator==(const SimpleString& left, const SimpleString& right) @@ -322,14 +543,14 @@ bool operator!=(const SimpleString& left, const SimpleString& right) SimpleString SimpleString::operator+(const SimpleString& rhs) const { - SimpleString t(buffer_); - t += rhs.buffer_; + SimpleString t(getBuffer()); + t += rhs.getBuffer(); return t; } SimpleString& SimpleString::operator+=(const SimpleString& rhs) { - return operator+=(rhs.buffer_); + return operator+=(rhs.getBuffer()); } SimpleString& SimpleString::operator+=(const char* rhs) @@ -337,10 +558,10 @@ SimpleString& SimpleString::operator+=(const char* rhs) size_t originalSize = this->size(); size_t additionalStringSize = StrLen(rhs) + 1; size_t sizeOfNewString = originalSize + additionalStringSize; - char* tbuffer = copyToNewBuffer(this->buffer_, sizeOfNewString); + char* tbuffer = copyToNewBuffer(this->getBuffer(), sizeOfNewString); StrNCpy(tbuffer + originalSize, rhs, additionalStringSize); - deallocStringBuffer(this->buffer_, __FILE__, __LINE__); - this->buffer_ = tbuffer; + + setInternalBufferTo(tbuffer, sizeOfNewString); return *this; } @@ -361,7 +582,7 @@ SimpleString SimpleString::subString(size_t beginPos, size_t amount) const { if (beginPos > size()-1) return ""; - SimpleString newString = buffer_ + beginPos; + SimpleString newString = getBuffer() + beginPos; if (newString.size() > amount) newString.buffer_[amount] = '\0'; @@ -376,7 +597,7 @@ SimpleString SimpleString::subString(size_t beginPos) const char SimpleString::at(size_t pos) const { - return buffer_[pos]; + return getBuffer()[pos]; } size_t SimpleString::find(char ch) const @@ -388,7 +609,7 @@ size_t SimpleString::findFrom(size_t starting_position, char ch) const { size_t length = size(); for (size_t i = starting_position; i < length; i++) - if (buffer_[i] == ch) return i; + if (at(i) == ch) return i; return npos; } @@ -405,21 +626,20 @@ SimpleString SimpleString::subStringFromTill(char startChar, char lastExcludedCh char* SimpleString::copyToNewBuffer(const char* bufferToCopy, size_t bufferSize) { - if(bufferSize == 0) bufferSize = StrLen(bufferToCopy) + 1; - char* newBuffer = allocStringBuffer(bufferSize, __FILE__, __LINE__); StrNCpy(newBuffer, bufferToCopy, bufferSize); newBuffer[bufferSize-1] = '\0'; return newBuffer; } + void SimpleString::copyToBuffer(char* bufferToCopy, size_t bufferSize) const { - if (bufferToCopy == NULL || bufferSize == 0) return; + if (bufferToCopy == NULLPTR || bufferSize == 0) return; - size_t sizeToCopy = (bufferSize-1 < size()) ? bufferSize : size(); + size_t sizeToCopy = (bufferSize-1 < size()) ? (bufferSize-1) : size(); - StrNCpy(bufferToCopy, buffer_, sizeToCopy); + StrNCpy(bufferToCopy, getBuffer(), sizeToCopy); bufferToCopy[sizeToCopy] = '\0'; } @@ -438,6 +658,16 @@ bool SimpleString::isUpper(char ch) return 'A' <= ch && 'Z' >= ch; } +bool SimpleString::isControl(char ch) +{ + return ch < ' ' || ch == char(0x7F); +} + +bool SimpleString::isControlWithShortEscapeSequence(char ch) +{ + return '\a' <= ch && '\r' >= ch; +} + SimpleString StringFrom(bool value) { return SimpleString(StringFromFormat("%s", value ? "true" : "false")); @@ -450,7 +680,12 @@ SimpleString StringFrom(const char *value) SimpleString StringFromOrNull(const char * expected) { - return (expected) ? StringFrom(expected) : "(null)"; + return (expected) ? StringFrom(expected) : StringFrom("(null)"); +} + +SimpleString PrintableStringFromOrNull(const char * expected) +{ + return (expected) ? StringFrom(expected).printable() : StringFrom("(null)"); } SimpleString StringFrom(int value) @@ -475,7 +710,12 @@ SimpleString StringFrom(void (*value)()) SimpleString HexStringFrom(long value) { - return StringFromFormat("%lx", value); + return HexStringFrom((unsigned long)value); +} + +SimpleString HexStringFrom(int value) +{ + return HexStringFrom((unsigned int)value); } SimpleString HexStringFrom(signed char value) @@ -493,7 +733,55 @@ SimpleString HexStringFrom(unsigned long value) return StringFromFormat("%lx", value); } -#ifdef CPPUTEST_USE_LONG_LONG +SimpleString HexStringFrom(unsigned int value) +{ + return StringFromFormat("%x", value); +} + +SimpleString BracketsFormattedHexStringFrom(int value) +{ + return BracketsFormattedHexString(HexStringFrom(value)); +} + +SimpleString BracketsFormattedHexStringFrom(unsigned int value) +{ + return BracketsFormattedHexString(HexStringFrom(value)); +} + +SimpleString BracketsFormattedHexStringFrom(long value) +{ + return BracketsFormattedHexString(HexStringFrom(value)); +} + + +SimpleString BracketsFormattedHexStringFrom(unsigned long value) +{ + return BracketsFormattedHexString(HexStringFrom(value)); +} + +SimpleString BracketsFormattedHexStringFrom(signed char value) +{ + return BracketsFormattedHexString(HexStringFrom(value)); +} + +SimpleString BracketsFormattedHexString(SimpleString hexString) +{ + return SimpleString("(0x") + hexString + ")" ; +} + +/* + * ARM compiler has only partial support for C++11. + * Specifically nullptr_t is not officially supported + */ +#if __cplusplus > 199711L && !defined __arm__ && CPPUTEST_USE_STD_CPP_LIB +SimpleString StringFrom(const std::nullptr_t value) +{ + (void) value; + return "(null)"; +} +#endif + +#if CPPUTEST_USE_LONG_LONG SimpleString StringFrom(cpputest_longlong value) { @@ -502,12 +790,12 @@ SimpleString StringFrom(cpputest_longlong value) SimpleString StringFrom(cpputest_ulonglong value) { - return StringFromFormat("%llu (0x%llx)", value, value); + return StringFromFormat("%llu", value); } SimpleString HexStringFrom(cpputest_longlong value) { - return StringFromFormat("%llx", value); + return HexStringFrom((cpputest_ulonglong)value); } SimpleString HexStringFrom(cpputest_ulonglong value) @@ -525,6 +813,17 @@ SimpleString HexStringFrom(void (*value)()) return HexStringFrom((cpputest_ulonglong) value); } +SimpleString BracketsFormattedHexStringFrom(cpputest_longlong value) +{ + return BracketsFormattedHexString(HexStringFrom(value)); +} + + +SimpleString BracketsFormattedHexStringFrom(cpputest_ulonglong value) +{ + return BracketsFormattedHexString(HexStringFrom(value)); +} + #else /* CPPUTEST_USE_LONG_LONG */ static long convertPointerToLongValue(const void* value) @@ -579,6 +878,17 @@ SimpleString HexStringFrom(void (*value)()) return StringFromFormat("%lx", convertFunctionPointerToLongValue(value)); } +SimpleString BracketsFormattedHexStringFrom(cpputest_longlong) +{ + return ""; +} + + +SimpleString BracketsFormattedHexStringFrom(cpputest_ulonglong) +{ + return ""; +} + #endif /* CPPUTEST_USE_LONG_LONG */ SimpleString StringFrom(double value, int precision) @@ -614,7 +924,7 @@ SimpleString StringFromFormat(const char* format, ...) SimpleString StringFrom(unsigned int i) { - return StringFromFormat("%10u (0x%08x)", i, i); + return StringFromFormat("%u", i); } #if CPPUTEST_USE_STD_CPP_LIB @@ -630,14 +940,9 @@ SimpleString StringFrom(const std::string& value) SimpleString StringFrom(unsigned long i) { - return StringFromFormat("%lu (0x%lx)", i, i); + return StringFromFormat("%lu", i); } -//Kludge to get a va_copy in VC++ V6 -#ifndef va_copy -#define va_copy(copy, original) copy = original; -#endif - SimpleString VStringFromFormat(const char* format, va_list args) { va_list argsCopy; @@ -659,7 +964,7 @@ SimpleString VStringFromFormat(const char* format, va_list args) PlatformSpecificVSNprintf(newBuffer, newBufferSize, format, argsCopy); resultString = SimpleString(newBuffer); - SimpleString::deallocStringBuffer(newBuffer, __FILE__, __LINE__); + SimpleString::deallocStringBuffer(newBuffer, newBufferSize, __FILE__, __LINE__); } va_end(argsCopy); return resultString; @@ -679,7 +984,7 @@ SimpleString StringFromBinary(const unsigned char* value, size_t size) SimpleString StringFromBinaryOrNull(const unsigned char* value, size_t size) { - return (value) ? StringFromBinary(value, size) : "(null)"; + return (value) ? StringFromBinary(value, size) : StringFrom("(null)"); } SimpleString StringFromBinaryWithSize(const unsigned char* value, size_t size) @@ -696,7 +1001,7 @@ SimpleString StringFromBinaryWithSize(const unsigned char* value, size_t size) SimpleString StringFromBinaryWithSizeOrNull(const unsigned char* value, size_t size) { - return (value) ? StringFromBinaryWithSize(value, size) : "(null)"; + return (value) ? StringFromBinaryWithSize(value, size) : StringFrom("(null)"); } SimpleString StringFromMaskedBits(unsigned long value, unsigned long mask, size_t byteCount) @@ -726,19 +1031,17 @@ SimpleString StringFromMaskedBits(unsigned long value, unsigned long mask, size_ SimpleString StringFromOrdinalNumber(unsigned int number) { - unsigned int onesDigit = number % 10; - - const char* suffix; - if (number >= 11 && number <= 13) { - suffix = "th"; - } else if (3 == onesDigit) { - suffix = "rd"; - } else if (2 == onesDigit) { - suffix = "nd"; - } else if (1 == onesDigit) { - suffix = "st"; - } else { - suffix = "th"; + const char* suffix = "th"; + + if ((number < 11) || (number > 13)) { + unsigned int const onesDigit = number % 10; + if (3 == onesDigit) { + suffix = "rd"; + } else if (2 == onesDigit) { + suffix = "nd"; + } else if (1 == onesDigit) { + suffix = "st"; + } } return StringFromFormat("%u%s", number, suffix); @@ -746,7 +1049,7 @@ SimpleString StringFromOrdinalNumber(unsigned int number) SimpleStringCollection::SimpleStringCollection() { - collection_ = 0; + collection_ = NULLPTR; size_ = 0; } diff --git a/src/CppUTest/SimpleStringInternalCache.cpp b/src/CppUTest/SimpleStringInternalCache.cpp new file mode 100644 index 000000000..2964a2d2c --- /dev/null +++ b/src/CppUTest/SimpleStringInternalCache.cpp @@ -0,0 +1,312 @@ +/* + * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "CppUTest/TestHarness.h" +#include "CppUTest/SimpleStringInternalCache.h" + +struct SimpleStringMemoryBlock +{ + SimpleStringMemoryBlock* next_; + char* memory_; +}; + +struct SimpleStringInternalCacheNode +{ + size_t size_; + SimpleStringMemoryBlock* freeMemoryHead_; + SimpleStringMemoryBlock* usedMemoryHead_; +}; + +SimpleStringInternalCache::SimpleStringInternalCache() + : allocator_(defaultMallocAllocator()), cache_(NULLPTR), nonCachedAllocations_(NULLPTR), hasWarnedAboutDeallocations(false) +{ + cache_ = createInternalCacheNodes(); +} + +SimpleStringInternalCache::~SimpleStringInternalCache() +{ + allocator_ = defaultMallocAllocator(); + destroyInternalCacheNode(cache_); +} + +void SimpleStringInternalCache::setAllocator(TestMemoryAllocator* allocator) +{ + allocator_ = allocator; +} + +SimpleStringInternalCacheNode* SimpleStringInternalCache::createInternalCacheNodes() +{ + SimpleStringInternalCacheNode* node = (SimpleStringInternalCacheNode*) (void*) allocator_->alloc_memory(sizeof(SimpleStringInternalCacheNode) * amountOfInternalCacheNodes, __FILE__, __LINE__); + + for (int i = 0; i < amountOfInternalCacheNodes; i++) { + node[i].freeMemoryHead_ = NULLPTR; + node[i].usedMemoryHead_ = NULLPTR; + } + node[0].size_ = 32; + node[1].size_ = 64; + node[2].size_ = 96; + node[3].size_ = 128; + node[4].size_ = 256; + return node; +} + +bool SimpleStringInternalCache::isCached(size_t size) +{ + return size <= 256; +} + +size_t SimpleStringInternalCache::getIndexForCache(size_t size) +{ + for (size_t i = 0; i < amountOfInternalCacheNodes; i++) + if (size <= cache_[i].size_) + return i; + return 0; // LCOV_EXCL_LINE +} + +SimpleStringInternalCacheNode* SimpleStringInternalCache::getCacheNodeFromSize(size_t size) +{ + size_t index = getIndexForCache(size); + return &cache_[index]; +} + +void SimpleStringInternalCache::destroyInternalCacheNode(SimpleStringInternalCacheNode * node) +{ + allocator_->free_memory((char*) node, sizeof(SimpleStringInternalCacheNode) * amountOfInternalCacheNodes, __FILE__, __LINE__); +} + +SimpleStringMemoryBlock* SimpleStringInternalCache::createSimpleStringMemoryBlock(size_t size, SimpleStringMemoryBlock* next) +{ + SimpleStringMemoryBlock* block = (SimpleStringMemoryBlock*) (void*) allocator_->alloc_memory(sizeof(SimpleStringMemoryBlock) , __FILE__, __LINE__); + block->memory_ = allocator_->alloc_memory(size , __FILE__, __LINE__); + block->next_ = next; + return block; +} + +void SimpleStringInternalCache::destroySimpleStringMemoryBlock(SimpleStringMemoryBlock * block, size_t size) +{ + allocator_->free_memory(block->memory_, size, __FILE__, __LINE__); + allocator_->free_memory((char*) block, sizeof(SimpleStringMemoryBlock), __FILE__, __LINE__); +} + +void SimpleStringInternalCache::destroySimpleStringMemoryBlockList(SimpleStringMemoryBlock * block, size_t size) +{ + SimpleStringMemoryBlock* current = block; + while (current) { + SimpleStringMemoryBlock* next = current->next_; + destroySimpleStringMemoryBlock(current, size); + current = next; + } +} + +SimpleStringMemoryBlock* SimpleStringInternalCache::addToSimpleStringMemoryBlockList(SimpleStringMemoryBlock* newBlock, SimpleStringMemoryBlock* previousHead) +{ + newBlock->next_ = previousHead; + return newBlock; +} + +bool SimpleStringInternalCache::hasFreeBlocksOfSize(size_t size) +{ + return getCacheNodeFromSize(size)->freeMemoryHead_ != NULLPTR; +} + +SimpleStringMemoryBlock* SimpleStringInternalCache::reserveCachedBlockFrom(SimpleStringInternalCacheNode* node) +{ + SimpleStringMemoryBlock* block = node->freeMemoryHead_; + node->freeMemoryHead_ = block->next_; + node->usedMemoryHead_ = addToSimpleStringMemoryBlockList(block, node->usedMemoryHead_); + return block; +} + +SimpleStringMemoryBlock* SimpleStringInternalCache::allocateNewCacheBlockFrom(SimpleStringInternalCacheNode* node) +{ + SimpleStringMemoryBlock* block = createSimpleStringMemoryBlock(node->size_, node->usedMemoryHead_); + node->usedMemoryHead_ = addToSimpleStringMemoryBlockList(block, node->usedMemoryHead_); + return block; +} + +void SimpleStringInternalCache::printDeallocatingUnknownMemory(char* memory) +{ + if (!hasWarnedAboutDeallocations) { + hasWarnedAboutDeallocations = true; + UtestShell::getCurrent()->print(StringFromFormat("\nWARNING: Attempting to deallocate a String buffer that was allocated while not caching. Ignoring it!\n" + "This is likely due statics and will cause problems.\n" + "Only warning once to avoid recursive warnings.\n" + "String we are deallocating: \"%s\"\n", memory).asCharString(), __FILE__, __LINE__); + } +} + +void SimpleStringInternalCache::releaseCachedBlockFrom(char* memory, SimpleStringInternalCacheNode* node) +{ + if (node->usedMemoryHead_ && node->usedMemoryHead_->memory_ == memory) { + SimpleStringMemoryBlock* block = node->usedMemoryHead_; + node->usedMemoryHead_ = node->usedMemoryHead_->next_; + node->freeMemoryHead_ = addToSimpleStringMemoryBlockList(block, node->freeMemoryHead_); + return; + } + + for (SimpleStringMemoryBlock* block = node->usedMemoryHead_; block; block = block->next_) { + if (block->next_ && block->next_->memory_ == memory) { + SimpleStringMemoryBlock* blockToFree = block->next_; + block->next_ = block->next_->next_; + node->freeMemoryHead_ = addToSimpleStringMemoryBlockList(blockToFree, node->freeMemoryHead_); + return; + } + } + printDeallocatingUnknownMemory(memory); + +} + +void SimpleStringInternalCache::releaseNonCachedMemory(char* memory, size_t size) +{ + if (nonCachedAllocations_ && nonCachedAllocations_->memory_ == memory) { + SimpleStringMemoryBlock* block = nonCachedAllocations_; + nonCachedAllocations_ = block->next_; + destroySimpleStringMemoryBlock(block, size); + return; + } + + for (SimpleStringMemoryBlock* block = nonCachedAllocations_; block; block = block->next_) { + if (block->next_ && block->next_->memory_ == memory) { + SimpleStringMemoryBlock* blockToFree = block->next_; + block->next_ = block->next_->next_; + destroySimpleStringMemoryBlock(blockToFree, size); + return; + } + } + + printDeallocatingUnknownMemory(memory); +} + +char* SimpleStringInternalCache::alloc(size_t size) +{ + if (isCached(size)) { + if (hasFreeBlocksOfSize(size)) + return reserveCachedBlockFrom(getCacheNodeFromSize(size))->memory_; + else + return allocateNewCacheBlockFrom(getCacheNodeFromSize(size))->memory_; + } + + nonCachedAllocations_ = createSimpleStringMemoryBlock(size, nonCachedAllocations_); + return nonCachedAllocations_->memory_; +} + +void SimpleStringInternalCache::dealloc(char* memory, size_t size) +{ + if (isCached(size)) { + size_t index = getIndexForCache(size); + SimpleStringInternalCacheNode* cacheNode = &cache_[index]; + releaseCachedBlockFrom(memory, cacheNode); + return; + } + releaseNonCachedMemory(memory, size); +} + +void SimpleStringInternalCache::clearCache() +{ + for (size_t i = 0; i < amountOfInternalCacheNodes; i++) { + destroySimpleStringMemoryBlockList(cache_[i].freeMemoryHead_, cache_[i].size_); + cache_[i].freeMemoryHead_ = NULLPTR; + } +} + +void SimpleStringInternalCache::clearAllIncludingCurrentlyUsedMemory() +{ + for (size_t i = 0; i < amountOfInternalCacheNodes; i++) { + destroySimpleStringMemoryBlockList(cache_[i].freeMemoryHead_, cache_[i].size_); + destroySimpleStringMemoryBlockList(cache_[i].usedMemoryHead_, cache_[i].size_); + cache_[i].freeMemoryHead_ = NULLPTR; + cache_[i].usedMemoryHead_ = NULLPTR; + } + + destroySimpleStringMemoryBlockList(nonCachedAllocations_, 0); + nonCachedAllocations_ = NULLPTR; +} + +GlobalSimpleStringCache::GlobalSimpleStringCache() +{ + allocator_ = new SimpleStringCacheAllocator(cache_, SimpleString::getStringAllocator()); + SimpleString::setStringAllocator(allocator_); +} + +GlobalSimpleStringCache::~GlobalSimpleStringCache() +{ + SimpleString::setStringAllocator(allocator_->originalAllocator()); + cache_.clearAllIncludingCurrentlyUsedMemory(); + delete allocator_; +} + +TestMemoryAllocator* GlobalSimpleStringCache::getAllocator() +{ + return allocator_; +} + +SimpleStringCacheAllocator::SimpleStringCacheAllocator(SimpleStringInternalCache& cache, TestMemoryAllocator* origAllocator) + : cache_(cache), originalAllocator_(origAllocator) +{ + cache_.setAllocator(origAllocator); +} + +SimpleStringCacheAllocator::~SimpleStringCacheAllocator() +{ + cache_.setAllocator(NULLPTR); +} + +char* SimpleStringCacheAllocator::alloc_memory(size_t size, const char*, size_t) +{ + return cache_.alloc(size); +} + +void SimpleStringCacheAllocator::free_memory(char* memory, size_t size, const char*, size_t) +{ + cache_.dealloc(memory, size); +} + +const char* SimpleStringCacheAllocator::name() const +{ + return "SimpleStringCacheAllocator"; +} + +const char* SimpleStringCacheAllocator::alloc_name() const +{ + return originalAllocator_->alloc_name(); +} + +const char* SimpleStringCacheAllocator::free_name() const +{ + return originalAllocator_->free_name(); +} + +TestMemoryAllocator* SimpleStringCacheAllocator::actualAllocator() +{ + return originalAllocator_->actualAllocator(); +} + +TestMemoryAllocator* SimpleStringCacheAllocator::originalAllocator() +{ + return originalAllocator_; +} + diff --git a/src/CppUTest/TeamCityTestOutput.cpp b/src/CppUTest/TeamCityTestOutput.cpp index 779bc6eb4..faa775363 100644 --- a/src/CppUTest/TeamCityTestOutput.cpp +++ b/src/CppUTest/TeamCityTestOutput.cpp @@ -1,7 +1,7 @@ #include "CppUTest/TestHarness.h" #include "CppUTest/TeamCityTestOutput.h" -TeamCityTestOutput::TeamCityTestOutput() : currtest_(0), currGroup_() +TeamCityTestOutput::TeamCityTestOutput() : currtest_(NULLPTR), currGroup_() { } @@ -12,11 +12,11 @@ TeamCityTestOutput::~TeamCityTestOutput() void TeamCityTestOutput::printCurrentTestStarted(const UtestShell& test) { print("##teamcity[testStarted name='"); - print(test.getName().asCharString()); + printEscaped(test.getName().asCharString()); print("']\n"); if (!test.willRun()) { print("##teamcity[testIgnored name='"); - print(test.getName().asCharString()); + printEscaped(test.getName().asCharString()); print("']\n"); } currtest_ = &test; @@ -28,7 +28,7 @@ void TeamCityTestOutput::printCurrentTestEnded(const TestResult& res) return; print("##teamcity[testFinished name='"); - print(currtest_->getName().asCharString()); + printEscaped(currtest_->getName().asCharString()); print("' duration='"); print(res.getCurrentTestTotalExecutionTime()); print("']\n"); @@ -38,7 +38,7 @@ void TeamCityTestOutput::printCurrentGroupStarted(const UtestShell& test) { currGroup_ = test.getGroup(); print("##teamcity[testSuiteStarted name='"); - print(currGroup_.asCharString()); + printEscaped(currGroup_.asCharString()); print("']\n"); } @@ -48,7 +48,7 @@ void TeamCityTestOutput::printCurrentGroupEnded(const TestResult& /*res*/) return; print("##teamcity[testSuiteFinished name='"); - print(currGroup_.asCharString()); + printEscaped(currGroup_.asCharString()); print("']\n"); } @@ -80,7 +80,7 @@ void TeamCityTestOutput::printEscaped(const char* s) void TeamCityTestOutput::printFailure(const TestFailure& failure) { print("##teamcity[testFailed name='"); - print(failure.getTestNameOnly().asCharString()); + printEscaped(failure.getTestNameOnly().asCharString()); print("' message='"); if (failure.isOutsideTestFile() || failure.isInHelperFunction()) { print("TEST failed ("); @@ -90,7 +90,7 @@ void TeamCityTestOutput::printFailure(const TestFailure& failure) print("): "); } - print(failure.getFileName().asCharString()); + printEscaped(failure.getFileName().asCharString()); print(":"); print(failure.getFailureLineNumber()); diff --git a/src/CppUTest/TestFailure.cpp b/src/CppUTest/TestFailure.cpp index a077578dd..a3a9bb82e 100644 --- a/src/CppUTest/TestFailure.cpp +++ b/src/CppUTest/TestFailure.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -31,36 +31,15 @@ #include "CppUTest/SimpleString.h" #include "CppUTest/PlatformSpecificFunctions.h" -static SimpleString removeAllPrintableCharactersFrom(const SimpleString& str) -{ - size_t bufferSize = str.size()+1; - char* buffer = (char*) PlatformSpecificMalloc(bufferSize); - str.copyToBuffer(buffer, bufferSize); - - for (size_t i = 0; i < bufferSize-1; i++) - if (buffer[i] != '\t' && buffer[i] != '\n') - buffer[i] = ' '; - - SimpleString result(buffer); - PlatformSpecificFree(buffer); - return result; -} +#if CPPUTEST_USE_STD_CPP_LIB +#include +#if defined(__GNUC__) +#include +#include +#endif +#endif -static SimpleString addMarkerToString(const SimpleString& str, int markerPos) -{ - size_t bufferSize = str.size()+1; - char* buffer = (char*) PlatformSpecificMalloc(bufferSize); - str.copyToBuffer(buffer, bufferSize); - - buffer[markerPos] = '^'; - - SimpleString result(buffer); - PlatformSpecificFree(buffer); - return result; - -} - -TestFailure::TestFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& theMessage) : +TestFailure::TestFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& theMessage) : testName_(test->getFormattedName()), testNameOnly_(test->getName()), fileName_(fileName), lineNumber_(lineNumber), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_(theMessage) { } @@ -70,7 +49,7 @@ TestFailure::TestFailure(UtestShell* test, const SimpleString& theMessage) : { } -TestFailure::TestFailure(UtestShell* test, const char* fileName, int lineNum) : +TestFailure::TestFailure(UtestShell* test, const char* fileName, size_t lineNum) : testName_(test->getFormattedName()), testNameOnly_(test->getName()), fileName_(fileName), lineNumber_(lineNum), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_("no message") { } @@ -105,12 +84,12 @@ SimpleString TestFailure::getTestNameOnly() const return testNameOnly_; } -int TestFailure::getFailureLineNumber() const +size_t TestFailure::getFailureLineNumber() const { return lineNumber_; } -int TestFailure::getTestLineNumber() const +size_t TestFailure::getTestLineNumber() const { return testLineNumber_; } @@ -135,25 +114,21 @@ SimpleString TestFailure::createButWasString(const SimpleString& expected, const return StringFromFormat("expected <%s>\n\tbut was <%s>", expected.asCharString(), actual.asCharString()); } -SimpleString TestFailure::createDifferenceAtPosString(const SimpleString& actual, size_t position, DifferenceFormat format) +SimpleString TestFailure::createDifferenceAtPosString(const SimpleString& actual, size_t offset, size_t reportedPosition) { SimpleString result; const size_t extraCharactersWindow = 20; const size_t halfOfExtraCharactersWindow = extraCharactersWindow / 2; - const size_t actualOffset = (format == DIFFERENCE_STRING) ? position : (position * 3 + 1); SimpleString paddingForPreventingOutOfBounds (" ", halfOfExtraCharactersWindow); SimpleString actualString = paddingForPreventingOutOfBounds + actual + paddingForPreventingOutOfBounds; - SimpleString differentString = StringFromFormat("difference starts at position %lu at: <", (unsigned long) position); + SimpleString differentString = StringFromFormat("difference starts at position %lu at: <", (unsigned long) reportedPosition); result += "\n"; - result += StringFromFormat("\t%s%s>\n", differentString.asCharString(), actualString.subString(actualOffset, extraCharactersWindow).asCharString()); + result += StringFromFormat("\t%s%s>\n", differentString.asCharString(), actualString.subString(offset, extraCharactersWindow).asCharString()); - SimpleString markString = actualString.subString(actualOffset, halfOfExtraCharactersWindow+1); - markString = removeAllPrintableCharactersFrom(markString); - markString = addMarkerToString(markString, halfOfExtraCharactersWindow); - result += StringFromFormat("\t%s%s", SimpleString(" ", differentString.size()).asCharString(), markString.asCharString()); + result += StringFromFormat("\t%s^", SimpleString(" ", (differentString.size() + halfOfExtraCharactersWindow)).asCharString()); return result; } @@ -162,14 +137,18 @@ SimpleString TestFailure::createUserText(const SimpleString& text) SimpleString userMessage = ""; if (!text.isEmpty()) { - userMessage += "Message: "; + //This is a kludge to turn off "Message: " for this case. + //I don't think "Message: " adds anything, as you get to see the + //message. I propose we remove "Message: " lead in + if (!text.startsWith("LONGS_EQUAL")) + userMessage += "Message: "; userMessage += text; userMessage += "\n\t"; } return userMessage; } -EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text) : +EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); @@ -177,7 +156,7 @@ EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, int lineNum message_ += createButWasString(StringFromOrNull(expected), StringFromOrNull(actual)); } -EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text) +EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); @@ -185,7 +164,7 @@ EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, int lineNum message_ += createButWasString(expected, actual); } -DoublesEqualFailure::DoublesEqualFailure(UtestShell* test, const char* fileName, int lineNumber, double expected, double actual, double threshold, const SimpleString& text) +DoublesEqualFailure::DoublesEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, double expected, double actual, double threshold, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); @@ -199,20 +178,36 @@ DoublesEqualFailure::DoublesEqualFailure(UtestShell* test, const char* fileName, message_ += "\n\tCannot make comparisons with Nan"; } -CheckEqualFailure::CheckEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text) +CheckEqualFailure::CheckEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); + SimpleString printableExpected = PrintableStringFromOrNull(expected.asCharString()); + SimpleString printableActual = PrintableStringFromOrNull(actual.asCharString()); + + message_ += createButWasString(printableExpected, printableActual); + size_t failStart; - for (failStart = 0; actual.asCharString()[failStart] == expected.asCharString()[failStart]; failStart++) + for (failStart = 0; actual.at(failStart) == expected.at(failStart); failStart++) ; - message_ += createButWasString(expected, actual); - message_ += createDifferenceAtPosString(actual, failStart); + size_t failStartPrintable; + for (failStartPrintable = 0; printableActual.at(failStartPrintable) == printableExpected.at(failStartPrintable); failStartPrintable++) + ; + message_ += createDifferenceAtPosString(printableActual, failStartPrintable, failStart); +} +ComparisonFailure::ComparisonFailure(UtestShell *test, const char *fileName, size_t lineNumber, const SimpleString& checkString, const SimpleString &comparisonString, const SimpleString &text) +: TestFailure(test, fileName, lineNumber) +{ + message_ = createUserText(text); + message_ += checkString; + message_ += "("; + message_ += comparisonString; + message_ += ") failed"; } -ContainsFailure::ContainsFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text) +ContainsFailure::ContainsFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); @@ -220,7 +215,7 @@ ContainsFailure::ContainsFailure(UtestShell* test, const char* fileName, int lin message_ += StringFromFormat("actual <%s>\n\tdid not contain <%s>", actual.asCharString(), expected.asCharString()); } -CheckFailure::CheckFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& checkString, const SimpleString& conditionString, const SimpleString& text) +CheckFailure::CheckFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& checkString, const SimpleString& conditionString, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); @@ -231,148 +226,150 @@ CheckFailure::CheckFailure(UtestShell* test, const char* fileName, int lineNumbe message_ += ") failed"; } -FailFailure::FailFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& message) : TestFailure(test, fileName, lineNumber) +FailFailure::FailFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& message) : TestFailure(test, fileName, lineNumber) { message_ = message; } -LongsEqualFailure::LongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, long expected, long actual, const SimpleString& text) +LongsEqualFailure::LongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, long expected, long actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); - SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom(expected); - SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); - SimpleString::padStringsToSameLength(aHex, eHex, '0'); - SimpleString actualReported = aDecimal + " 0x" + aHex; - SimpleString expectedReported = eDecimal + " 0x" + eHex; + SimpleString actualReported = aDecimal + " " + BracketsFormattedHexStringFrom(actual); + SimpleString expectedReported = eDecimal + " " + BracketsFormattedHexStringFrom(expected); message_ += createButWasString(expectedReported, actualReported); } -UnsignedLongsEqualFailure::UnsignedLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, unsigned long expected, unsigned long actual, const SimpleString& text) +UnsignedLongsEqualFailure::UnsignedLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, unsigned long expected, unsigned long actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); - SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom(expected); - SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); - SimpleString::padStringsToSameLength(aHex, eHex, '0'); - SimpleString actualReported = aDecimal + " 0x" + aHex; - SimpleString expectedReported = eDecimal + " 0x" + eHex; + SimpleString actualReported = aDecimal + " " + BracketsFormattedHexStringFrom(actual); + SimpleString expectedReported = eDecimal + " " + BracketsFormattedHexStringFrom(expected); + message_ += createButWasString(expectedReported, actualReported); } -LongLongsEqualFailure::LongLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, cpputest_longlong expected, cpputest_longlong actual, const SimpleString& text) +LongLongsEqualFailure::LongLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, cpputest_longlong expected, cpputest_longlong actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); - SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom(expected); - SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); - SimpleString::padStringsToSameLength(aHex, eHex, '0'); - SimpleString actualReported = aDecimal + " 0x" + aHex; - SimpleString expectedReported = eDecimal + " 0x" + eHex; + SimpleString actualReported = aDecimal + " " + BracketsFormattedHexStringFrom(actual); + SimpleString expectedReported = eDecimal + " " + BracketsFormattedHexStringFrom(expected); message_ += createButWasString(expectedReported, actualReported); } -UnsignedLongLongsEqualFailure::UnsignedLongLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, cpputest_ulonglong expected, cpputest_ulonglong actual, const SimpleString& text) +UnsignedLongLongsEqualFailure::UnsignedLongLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, cpputest_ulonglong expected, cpputest_ulonglong actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); - SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom(expected); - SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); - SimpleString::padStringsToSameLength(aHex, eHex, '0'); - SimpleString actualReported = aDecimal + " 0x" + aHex; - SimpleString expectedReported = eDecimal + " 0x" + eHex; + SimpleString actualReported = aDecimal + " " + BracketsFormattedHexStringFrom(actual); + SimpleString expectedReported = eDecimal + " " + BracketsFormattedHexStringFrom(expected); message_ += createButWasString(expectedReported, actualReported); } -SignedBytesEqualFailure::SignedBytesEqualFailure (UtestShell* test, const char* fileName, int lineNumber, signed char expected, signed char actual, const SimpleString& text) +SignedBytesEqualFailure::SignedBytesEqualFailure (UtestShell* test, const char* fileName, size_t lineNumber, signed char expected, signed char actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom((int)actual); - SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom((int)expected); - SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); - SimpleString::padStringsToSameLength(aHex, eHex, '0'); - SimpleString actualReported = aDecimal + " 0x" + aHex; - SimpleString expectedReported = eDecimal + " 0x" + eHex; + SimpleString actualReported = aDecimal + " " + BracketsFormattedHexStringFrom(actual); + SimpleString expectedReported = eDecimal + " " + BracketsFormattedHexStringFrom(expected); message_ += createButWasString(expectedReported, actualReported); } -StringEqualFailure::StringEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text) +StringEqualFailure::StringEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); - message_ += createButWasString(StringFromOrNull(expected), StringFromOrNull(actual)); + SimpleString printableExpected = PrintableStringFromOrNull(expected); + SimpleString printableActual = PrintableStringFromOrNull(actual); + + message_ += createButWasString(printableExpected, printableActual); if((expected) && (actual)) { size_t failStart; for (failStart = 0; actual[failStart] == expected[failStart]; failStart++) ; - message_ += createDifferenceAtPosString(actual, failStart); + size_t failStartPrintable; + for (failStartPrintable = 0; printableActual.at(failStartPrintable) == printableExpected.at(failStartPrintable); failStartPrintable++) + ; + message_ += createDifferenceAtPosString(printableActual, failStartPrintable, failStart); } } -StringEqualNoCaseFailure::StringEqualNoCaseFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text) +StringEqualNoCaseFailure::StringEqualNoCaseFailure(UtestShell* test, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); - message_ += createButWasString(StringFromOrNull(expected), StringFromOrNull(actual)); + SimpleString printableExpected = PrintableStringFromOrNull(expected); + SimpleString printableActual = PrintableStringFromOrNull(actual); + + message_ += createButWasString(printableExpected, printableActual); if((expected) && (actual)) { size_t failStart; for (failStart = 0; SimpleString::ToLower(actual[failStart]) == SimpleString::ToLower(expected[failStart]); failStart++) ; - message_ += createDifferenceAtPosString(actual, failStart); + size_t failStartPrintable; + for (failStartPrintable = 0; + SimpleString::ToLower(printableActual.at(failStartPrintable)) == SimpleString::ToLower(printableExpected.at(failStartPrintable)); + failStartPrintable++) + ; + message_ += createDifferenceAtPosString(printableActual, failStartPrintable, failStart); } } -BinaryEqualFailure::BinaryEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const unsigned char* expected, +BinaryEqualFailure::BinaryEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const unsigned char* expected, const unsigned char* actual, size_t size, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); - message_ += createButWasString(StringFromBinaryOrNull(expected, size), StringFromBinaryOrNull(actual, size)); + SimpleString actualHex = StringFromBinaryOrNull(actual, size); + + message_ += createButWasString(StringFromBinaryOrNull(expected, size), actualHex); if ((expected) && (actual)) { size_t failStart; for (failStart = 0; actual[failStart] == expected[failStart]; failStart++) ; - message_ += createDifferenceAtPosString(StringFromBinary(actual, size), failStart, DIFFERENCE_BINARY); + message_ += createDifferenceAtPosString(actualHex, (failStart * 3 + 1), failStart); } } -BitsEqualFailure::BitsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, unsigned long expected, unsigned long actual, +BitsEqualFailure::BitsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { @@ -381,11 +378,55 @@ BitsEqualFailure::BitsEqualFailure(UtestShell* test, const char* fileName, int l message_ += createButWasString(StringFromMaskedBits(expected, mask, byteCount), StringFromMaskedBits(actual, mask, byteCount)); } -FeatureUnsupportedFailure::FeatureUnsupportedFailure(UtestShell* test, const char* fileName, int lineNumber, +FeatureUnsupportedFailure::FeatureUnsupportedFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& featureName, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); - message_ += StringFromFormat("The feature \"%s\" is not supported in this environment or with the feature set selected when building the library.", featureName.asCharString());; + message_ += StringFromFormat("The feature \"%s\" is not supported in this environment or with the feature set selected when building the library.", featureName.asCharString()); +} + +#if CPPUTEST_HAVE_EXCEPTIONS +UnexpectedExceptionFailure::UnexpectedExceptionFailure(UtestShell* test) +: TestFailure(test, "Unexpected exception of unknown type was thrown.") +{ +} + +#if CPPUTEST_USE_STD_CPP_LIB +#if CPPUTEST_HAVE_RTTI +static SimpleString getExceptionTypeName(const std::exception &e) +{ + const char *name = typeid(e).name(); +#if defined(__GNUC__) && (__cplusplus >= 201103L) + int status = -1; + + std::unique_ptr demangledName( + abi::__cxa_demangle(name, NULLPTR, NULLPTR, &status), + std::free ); + + return (status==0) ? demangledName.get() : name; +#else + return name; +#endif +} +#endif // CPPUTEST_HAVE_RTTI + +UnexpectedExceptionFailure::UnexpectedExceptionFailure(UtestShell* test, const std::exception &e) +: TestFailure( + test, +#if CPPUTEST_HAVE_RTTI + StringFromFormat( + "Unexpected exception of type '%s' was thrown: %s", + getExceptionTypeName(e).asCharString(), + e.what() + ) +#else + "Unexpected exception of unknown type was thrown." +#endif +) +{ + (void) e; } +#endif // CPPUTEST_USE_STD_CPP_LIB +#endif // CPPUTEST_HAVE_EXCEPTIONS diff --git a/src/CppUTest/TestFilter.cpp b/src/CppUTest/TestFilter.cpp index a684c0891..326767afc 100644 --- a/src/CppUTest/TestFilter.cpp +++ b/src/CppUTest/TestFilter.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -28,16 +28,16 @@ #include "CppUTest/CppUTestConfig.h" #include "CppUTest/TestFilter.h" -TestFilter::TestFilter() : strictMatching_(false), invertMatching_(false), next_(NULL) +TestFilter::TestFilter() : strictMatching_(false), invertMatching_(false), next_(NULLPTR) { } -TestFilter::TestFilter(const SimpleString& filter) : strictMatching_(false), invertMatching_(false), next_(NULL) +TestFilter::TestFilter(const SimpleString& filter) : strictMatching_(false), invertMatching_(false), next_(NULLPTR) { filter_ = filter; } -TestFilter::TestFilter(const char* filter) : strictMatching_(false), invertMatching_(false), next_(NULL) +TestFilter::TestFilter(const char* filter) : strictMatching_(false), invertMatching_(false), next_(NULLPTR) { filter_ = filter; } diff --git a/src/CppUTest/TestHarness_c.cpp b/src/CppUTest/TestHarness_c.cpp index 6fb9d3c29..149c8fbb6 100644 --- a/src/CppUTest/TestHarness_c.cpp +++ b/src/CppUTest/TestHarness_c.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,60 +34,94 @@ extern "C" { +void CHECK_EQUAL_C_BOOL_LOCATION(int expected, int actual, const char* text, const char* fileName, size_t lineNumber) +{ + UtestShell::getCurrent()->assertEquals(!!expected != !!actual, expected ? "true" : "false", actual ? "true" : "false", text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); +} + +void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, const char* text, const char* fileName, size_t lineNumber) +{ + UtestShell::getCurrent()->assertLongsEqual((long)expected, (long)actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); +} + +void CHECK_EQUAL_C_UINT_LOCATION(unsigned int expected, unsigned int actual, const char* text, const char* fileName, size_t lineNumber) +{ + UtestShell::getCurrent()->assertUnsignedLongsEqual((unsigned long)expected, (unsigned long)actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); +} + +void CHECK_EQUAL_C_LONG_LOCATION(long expected, long actual, const char* text, const char* fileName, size_t lineNumber) +{ + UtestShell::getCurrent()->assertLongsEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); +} + +void CHECK_EQUAL_C_ULONG_LOCATION(unsigned long expected, unsigned long actual, const char* text, const char* fileName, size_t lineNumber) +{ + UtestShell::getCurrent()->assertUnsignedLongsEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); +} + +void CHECK_EQUAL_C_LONGLONG_LOCATION(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char* fileName, size_t lineNumber) +{ + UtestShell::getCurrent()->assertLongLongsEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); +} + +void CHECK_EQUAL_C_ULONGLONG_LOCATION(cpputest_ulonglong expected, cpputest_ulonglong actual, const char* text, const char* fileName, size_t lineNumber) +{ + UtestShell::getCurrent()->assertUnsignedLongLongsEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); +} -void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, const char* fileName, int lineNumber) +void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* text, const char* fileName, size_t lineNumber) { - UtestShell::getCurrent()->assertLongsEqual((long)expected, (long)actual, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); + UtestShell::getCurrent()->assertDoublesEqual(expected, actual, threshold, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } -void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* fileName, int lineNumber) +void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* text, const char* fileName, size_t lineNumber) { - UtestShell::getCurrent()->assertDoublesEqual(expected, actual, threshold, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); + UtestShell::getCurrent()->assertEquals(((expected) != (actual)), StringFrom(expected).asCharString(), StringFrom(actual).asCharString(), text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } -void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* fileName, int lineNumber) +extern void CHECK_EQUAL_C_UBYTE_LOCATION(unsigned char expected, unsigned char actual, const char* text, const char* fileName, size_t lineNumber)\ { - UtestShell::getCurrent()->assertEquals(((expected) != (actual)), StringFrom(expected).asCharString(), StringFrom(actual).asCharString(), NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); + UtestShell::getCurrent()->assertEquals(((expected) != (actual)),StringFrom((int)expected).asCharString(), StringFrom((int) actual).asCharString(), text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } -extern void CHECK_EQUAL_C_UBYTE_LOCATION(unsigned char expected, unsigned char actual, const char* fileName, int lineNumber)\ +void CHECK_EQUAL_C_SBYTE_LOCATION(char signed expected, signed char actual, const char* text, const char* fileName, size_t lineNumber) { - UtestShell::getCurrent()->assertEquals(((expected) != (actual)),StringFrom((int)expected).asCharString(), StringFrom((int) actual).asCharString(), NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); + UtestShell::getCurrent()->assertEquals(((expected) != (actual)),StringFrom((int)expected).asCharString(), StringFrom((int) actual).asCharString(), text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } -void CHECK_EQUAL_C_SBYTE_LOCATION(char signed expected, signed char actual, const char* fileName, int lineNumber) +void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber) { - UtestShell::getCurrent()->assertEquals(((expected) != (actual)),StringFrom((int)expected).asCharString(), StringFrom((int) actual).asCharString(), NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); + UtestShell::getCurrent()->assertCstrEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } -void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* fileName, int lineNumber) +void CHECK_EQUAL_C_POINTER_LOCATION(const void* expected, const void* actual, const char* text, const char* fileName, size_t lineNumber) { - UtestShell::getCurrent()->assertCstrEqual(expected, actual, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); + UtestShell::getCurrent()->assertPointersEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } -void CHECK_EQUAL_C_POINTER_LOCATION(const void* expected, const void* actual, const char* fileName, int lineNumber) +extern void CHECK_EQUAL_C_MEMCMP_LOCATION(const void* expected, const void* actual, size_t size, const char* text, const char* fileName, size_t lineNumber) { - UtestShell::getCurrent()->assertPointersEqual(expected, actual, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); + UtestShell::getCurrent()->assertBinaryEqual(expected, actual, size, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } -extern void CHECK_EQUAL_C_BITS_LOCATION(unsigned int expected, unsigned int actual, unsigned int mask, size_t size, const char* fileName, int lineNumber) +extern void CHECK_EQUAL_C_BITS_LOCATION(unsigned int expected, unsigned int actual, unsigned int mask, size_t size, const char* text, const char* fileName, size_t lineNumber) { - UtestShell::getCurrent()->assertBitsEqual(expected, actual, mask, size, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); + UtestShell::getCurrent()->assertBitsEqual(expected, actual, mask, size, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } -void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, int lineNumber) +void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, size_t lineNumber) { - UtestShell::getCurrent()->fail(text, fileName, lineNumber, TestTerminatorWithoutExceptions()); + UtestShell::getCurrent()->fail(text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } // LCOV_EXCL_LINE -void FAIL_C_LOCATION(const char* fileName, int lineNumber) +void FAIL_C_LOCATION(const char* fileName, size_t lineNumber) { - UtestShell::getCurrent()->fail("", fileName, lineNumber, TestTerminatorWithoutExceptions()); + UtestShell::getCurrent()->fail("", fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } // LCOV_EXCL_LINE -void CHECK_C_LOCATION(int condition, const char* conditionString, const char* fileName, int lineNumber) +void CHECK_C_LOCATION(int condition, const char* conditionString, const char* text, const char* fileName, size_t lineNumber) { - UtestShell::getCurrent()->assertTrue(condition != 0, "CHECK_C", conditionString, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); + UtestShell::getCurrent()->assertTrue(condition != 0, "CHECK_C", conditionString, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } enum { NO_COUNTDOWN = -1, OUT_OF_MEMORRY = 0 }; @@ -104,15 +138,20 @@ int cpputest_malloc_get_count() return malloc_count; } +static TestMemoryAllocator* originalAllocator = NULLPTR; + void cpputest_malloc_set_out_of_memory() { + if (originalAllocator == NULLPTR) + originalAllocator = getCurrentMallocAllocator(); setCurrentMallocAllocator(NullUnknownAllocator::defaultAllocator()); } void cpputest_malloc_set_not_out_of_memory() { malloc_out_of_memory_counter = NO_COUNTDOWN; - setCurrentMallocAllocatorToDefault(); + setCurrentMallocAllocator(originalAllocator); + originalAllocator = NULLPTR; } void cpputest_malloc_set_out_of_memory_countdown(int count) @@ -127,6 +166,16 @@ void* cpputest_malloc(size_t size) return cpputest_malloc_location(size, "", 0); } +char* cpputest_strdup(const char* str) +{ + return cpputest_strdup_location(str, "", 0); +} + +char* cpputest_strndup(const char* str, size_t n) +{ + return cpputest_strndup_location(str, n, "", 0); +} + void* cpputest_calloc(size_t num, size_t size) { return cpputest_calloc_location(num, size, "", 0); @@ -156,14 +205,44 @@ static void countdown() cpputest_malloc_set_out_of_memory(); } -void* cpputest_malloc_location(size_t size, const char* file, int line) +void* cpputest_malloc_location(size_t size, const char* file, size_t line) { countdown(); malloc_count++; return cpputest_malloc_location_with_leak_detection(size, file, line); } -void* cpputest_calloc_location(size_t num, size_t size, const char* file, int line) +static size_t test_harness_c_strlen(const char * str) +{ + size_t n = 0; + while (*str++) n++; + return n; +} + +static char* strdup_alloc(const char * str, size_t size, const char* file, size_t line) +{ + char* result = (char*) cpputest_malloc_location(size, file, line); + PlatformSpecificMemCpy(result, str, size); + result[size-1] = '\0'; + return result; +} + +char* cpputest_strdup_location(const char * str, const char* file, size_t line) +{ + size_t length = 1 + test_harness_c_strlen(str); + return strdup_alloc(str, length, file, line); +} + +char* cpputest_strndup_location(const char * str, size_t n, const char* file, size_t line) +{ + size_t length = test_harness_c_strlen(str); + length = length < n ? length : n; + length = length + 1; + return strdup_alloc(str, length, file, line); +} + + +void* cpputest_calloc_location(size_t num, size_t size, const char* file, size_t line) { void* mem = cpputest_malloc_location(num * size, file, line); if (mem) @@ -171,12 +250,12 @@ void* cpputest_calloc_location(size_t num, size_t size, const char* file, int li return mem; } -void* cpputest_realloc_location(void* memory, size_t size, const char* file, int line) +void* cpputest_realloc_location(void* memory, size_t size, const char* file, size_t line) { return cpputest_realloc_location_with_leak_detection(memory, size, file, line); } -void cpputest_free_location(void* buffer, const char* file, int line) +void cpputest_free_location(void* buffer, const char* file, size_t line) { cpputest_free_location_with_leak_detection(buffer, file, line); } diff --git a/src/CppUTest/TestMemoryAllocator.cpp b/src/CppUTest/TestMemoryAllocator.cpp index 28f77adc0..71e3a7ca6 100644 --- a/src/CppUTest/TestMemoryAllocator.cpp +++ b/src/CppUTest/TestMemoryAllocator.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -33,14 +33,14 @@ static char* checkedMalloc(size_t size) { char* mem = (char*) PlatformSpecificMalloc(size); - if (mem == 0) + if (mem == NULLPTR) FAIL("malloc returned null pointer"); return mem; } -static TestMemoryAllocator* currentNewAllocator = 0; -static TestMemoryAllocator* currentNewArrayAllocator = 0; -static TestMemoryAllocator* currentMallocAllocator = 0; +static TestMemoryAllocator* currentNewAllocator = NULLPTR; +static TestMemoryAllocator* currentNewArrayAllocator = NULLPTR; +static TestMemoryAllocator* currentMallocAllocator = NULLPTR; void setCurrentNewAllocator(TestMemoryAllocator* allocator) { @@ -49,7 +49,7 @@ void setCurrentNewAllocator(TestMemoryAllocator* allocator) TestMemoryAllocator* getCurrentNewAllocator() { - if (currentNewAllocator == 0) setCurrentNewAllocatorToDefault(); + if (currentNewAllocator == NULLPTR) setCurrentNewAllocatorToDefault(); return currentNewAllocator; } @@ -71,7 +71,7 @@ void setCurrentNewArrayAllocator(TestMemoryAllocator* allocator) TestMemoryAllocator* getCurrentNewArrayAllocator() { - if (currentNewArrayAllocator == 0) setCurrentNewArrayAllocatorToDefault(); + if (currentNewArrayAllocator == NULLPTR) setCurrentNewArrayAllocatorToDefault(); return currentNewArrayAllocator; } @@ -93,7 +93,7 @@ void setCurrentMallocAllocator(TestMemoryAllocator* allocator) TestMemoryAllocator* getCurrentMallocAllocator() { - if (currentMallocAllocator == 0) setCurrentMallocAllocatorToDefault(); + if (currentMallocAllocator == NULLPTR) setCurrentMallocAllocatorToDefault(); return currentMallocAllocator; } @@ -110,6 +110,25 @@ TestMemoryAllocator* defaultMallocAllocator() ///////////////////////////////////////////// +GlobalMemoryAllocatorStash::GlobalMemoryAllocatorStash() + : originalMallocAllocator(NULLPTR), originalNewAllocator(NULLPTR), originalNewArrayAllocator(NULLPTR) +{ +} + +void GlobalMemoryAllocatorStash::save() +{ + originalMallocAllocator = getCurrentMallocAllocator(); + originalNewAllocator = getCurrentNewAllocator(); + originalNewArrayAllocator = getCurrentNewArrayAllocator(); +} + +void GlobalMemoryAllocatorStash::restore() +{ + if (originalMallocAllocator) setCurrentMallocAllocator(originalMallocAllocator); + if (originalNewAllocator) setCurrentNewAllocator(originalNewAllocator); + if (originalNewArrayAllocator) setCurrentNewArrayAllocator(originalNewArrayAllocator); +} + TestMemoryAllocator::TestMemoryAllocator(const char* name_str, const char* alloc_name_str, const char* free_name_str) : name_(name_str), alloc_name_(alloc_name_str), free_name_(free_name_str), hasBeenDestroyed_(false) { @@ -137,43 +156,92 @@ char* TestMemoryAllocator::allocMemoryLeakNode(size_t size) void TestMemoryAllocator::freeMemoryLeakNode(char* memory) { - free_memory(memory, "MemoryLeakNode", 1); + free_memory(memory, 0, "MemoryLeakNode", 1); } -char* TestMemoryAllocator::alloc_memory(size_t size, const char*, int) +char* TestMemoryAllocator::alloc_memory(size_t size, const char*, size_t) { return checkedMalloc(size); } -void TestMemoryAllocator::free_memory(char* memory, const char*, int) +void TestMemoryAllocator::free_memory(char* memory, size_t, const char*, size_t) { PlatformSpecificFree(memory); } -const char* TestMemoryAllocator::name() + +const char* TestMemoryAllocator::name() const { return name_; } -const char* TestMemoryAllocator::alloc_name() +const char* TestMemoryAllocator::alloc_name() const { return alloc_name_; } -const char* TestMemoryAllocator::free_name() +const char* TestMemoryAllocator::free_name() const { return free_name_; } +TestMemoryAllocator* TestMemoryAllocator::actualAllocator() +{ + return this; +} + +MemoryLeakAllocator::MemoryLeakAllocator(TestMemoryAllocator* originalAllocator) + : originalAllocator_(originalAllocator) +{ +} + +MemoryLeakAllocator::~MemoryLeakAllocator() +{ +} + +char* MemoryLeakAllocator::alloc_memory(size_t size, const char* file, size_t line) +{ + return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(originalAllocator_, size, file, line); +} + +void MemoryLeakAllocator::free_memory(char* memory, size_t, const char* file, size_t line) +{ + MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(originalAllocator_, memory, file, line); +} + +const char* MemoryLeakAllocator::name() const +{ + return "MemoryLeakAllocator"; +} + +const char* MemoryLeakAllocator::alloc_name() const +{ + return originalAllocator_->alloc_name(); +} + +const char* MemoryLeakAllocator::free_name() const +{ + return originalAllocator_->free_name(); +} + +TestMemoryAllocator* MemoryLeakAllocator::actualAllocator() +{ + return originalAllocator_->actualAllocator(); +} + CrashOnAllocationAllocator::CrashOnAllocationAllocator() : allocationToCrashOn_(0) { } +CrashOnAllocationAllocator::~CrashOnAllocationAllocator() +{ +} + void CrashOnAllocationAllocator::setNumberToCrashOn(unsigned allocationToCrashOn) { allocationToCrashOn_ = allocationToCrashOn; } -char* CrashOnAllocationAllocator::alloc_memory(size_t size, const char* file, int line) +char* CrashOnAllocationAllocator::alloc_memory(size_t size, const char* file, size_t line) { if (MemoryLeakWarningPlugin::getGlobalDetector()->getCurrentAllocationNumber() == allocationToCrashOn_) UT_CRASH(); @@ -182,12 +250,16 @@ char* CrashOnAllocationAllocator::alloc_memory(size_t size, const char* file, in } -char* NullUnknownAllocator::alloc_memory(size_t /*size*/, const char*, int) +NullUnknownAllocator::~NullUnknownAllocator() { - return 0; } -void NullUnknownAllocator::free_memory(char* /*memory*/, const char*, int) +char* NullUnknownAllocator::alloc_memory(size_t /*size*/, const char*, size_t) +{ + return NULLPTR; +} + +void NullUnknownAllocator::free_memory(char* /*memory*/, size_t, const char*, size_t) { } @@ -209,7 +281,7 @@ class LocationToFailAllocNode int allocNumberToFail_; int actualAllocNumber_; const char* file_; - int line_; + size_t line_; LocationToFailAllocNode* next_; void failAtAllocNumber(int number, LocationToFailAllocNode* next) @@ -218,7 +290,7 @@ class LocationToFailAllocNode allocNumberToFail_ = number; } - void failNthAllocAt(int allocationNumber, const char* file, int line, LocationToFailAllocNode* next) + void failNthAllocAt(int allocationNumber, const char* file, size_t line, LocationToFailAllocNode* next) { init(next); allocNumberToFail_ = allocationNumber; @@ -226,7 +298,7 @@ class LocationToFailAllocNode line_ = line; } - bool shouldFail(int allocationNumber, const char* file, int line) + bool shouldFail(int allocationNumber, const char* file, size_t line) { if (file_ && SimpleString::StrCmp(file, file_) == 0 && line == line_) { actualAllocNumber_++; @@ -238,19 +310,23 @@ class LocationToFailAllocNode } private: - void init(LocationToFailAllocNode* next = NULL) + void init(LocationToFailAllocNode* next = NULLPTR) { allocNumberToFail_ = 0; actualAllocNumber_ = 0; - file_ = NULL; + file_ = NULLPTR; line_ = 0; next_ = next; } }; +FailableMemoryAllocator::~FailableMemoryAllocator() +{ +} + FailableMemoryAllocator::FailableMemoryAllocator(const char* name_str, const char* alloc_name_str, const char* free_name_str) -: TestMemoryAllocator(name_str, alloc_name_str, free_name_str), head_(NULL), currentAllocNumber_(0) +: TestMemoryAllocator(name_str, alloc_name_str, free_name_str), head_(NULLPTR), currentAllocNumber_(0) { } @@ -261,26 +337,26 @@ void FailableMemoryAllocator::failAllocNumber(int number) head_ = newNode; } -void FailableMemoryAllocator::failNthAllocAt(int allocationNumber, const char* file, int line) +void FailableMemoryAllocator::failNthAllocAt(int allocationNumber, const char* file, size_t line) { LocationToFailAllocNode* newNode = (LocationToFailAllocNode*) (void*) allocMemoryLeakNode(sizeof(LocationToFailAllocNode)); newNode->failNthAllocAt(allocationNumber, file, line, head_); head_ = newNode; } -char* FailableMemoryAllocator::alloc_memory(size_t size, const char* file, int line) +char* FailableMemoryAllocator::alloc_memory(size_t size, const char* file, size_t line) { currentAllocNumber_++; LocationToFailAllocNode* current = head_; - LocationToFailAllocNode* previous = NULL; + LocationToFailAllocNode* previous = NULLPTR; while (current) { if (current->shouldFail(currentAllocNumber_, file, line)) { if (previous) previous->next_ = current->next_; else head_ = current->next_; - free_memory((char*) current, __FILE__, __LINE__); - return NULL; + free_memory((char*) current, size, __FILE__, __LINE__); + return NULLPTR; } previous = current; current = current->next_; @@ -295,17 +371,16 @@ char* FailableMemoryAllocator::allocMemoryLeakNode(size_t size) void FailableMemoryAllocator::checkAllFailedAllocsWereDone() { - if (head_) { - UtestShell* currentTest = UtestShell::getCurrent(); - SimpleString failText; - if (head_->file_) - failText = StringFromFormat("Expected failing alloc at %s:%d was never done", head_->file_, head_->line_); - else - failText = StringFromFormat("Expected allocation number %d was never done", head_->allocNumberToFail_); + if (head_) { + UtestShell* currentTest = UtestShell::getCurrent(); + SimpleString failText; + if (head_->file_) + failText = StringFromFormat("Expected failing alloc at %s:%d was never done", head_->file_, (int) head_->line_); + else + failText = StringFromFormat("Expected allocation number %d was never done", (int) head_->allocNumberToFail_); - currentTest->failWith(FailFailure(currentTest, currentTest->getName().asCharString(), - currentTest->getLineNumber(), failText), TestTerminatorWithoutExceptions()); - } + currentTest->failWith(FailFailure(currentTest, currentTest->getName().asCharString(), currentTest->getLineNumber(), failText)); + } } void FailableMemoryAllocator::clearFailedAllocs() @@ -313,9 +388,405 @@ void FailableMemoryAllocator::clearFailedAllocs() LocationToFailAllocNode* current = head_; while (current) { head_ = current->next_; - free_memory((char*) current, __FILE__, __LINE__); + free_memory((char*) current, 0, __FILE__, __LINE__); current = head_; } currentAllocNumber_ = 0; } +struct MemoryAccountantAllocationNode +{ + size_t size_; + size_t allocations_; + size_t deallocations_; + size_t maxAllocations_; + size_t currentAllocations_; + MemoryAccountantAllocationNode* next_; +}; + +MemoryAccountantAllocationNode* MemoryAccountant::createNewAccountantAllocationNode(size_t size, MemoryAccountantAllocationNode* next) const +{ + MemoryAccountantAllocationNode* node = (MemoryAccountantAllocationNode*) (void*) allocator_->alloc_memory(sizeof(MemoryAccountantAllocationNode), __FILE__, __LINE__); + node->size_ = size; + node->allocations_ = 0; + node->deallocations_ = 0; + node->maxAllocations_ = 0; + node->currentAllocations_ = 0; + node->next_ = next; + return node; +} + +void MemoryAccountant::destroyAccountantAllocationNode(MemoryAccountantAllocationNode* node) const +{ + allocator_->free_memory((char*) node, sizeof(*node), __FILE__, __LINE__); +} + +MemoryAccountant::MemoryAccountant() + : head_(NULLPTR), allocator_(defaultMallocAllocator()), useCacheSizes_(false) +{ +} + +MemoryAccountant::~MemoryAccountant() +{ + clear(); +} + +void MemoryAccountant::createCacheSizeNodes(size_t sizes[], size_t length) +{ + for (size_t i = 0; i < length; i++) + findOrCreateNodeOfSize(sizes[i]); + + if (head_ == NULLPTR) + head_ = createNewAccountantAllocationNode(0, NULLPTR); + else { + for (MemoryAccountantAllocationNode* lastNode = head_; lastNode; lastNode = lastNode->next_) { + if (lastNode->next_ == NULLPTR) { + lastNode->next_ = createNewAccountantAllocationNode(0, NULLPTR); + break; + } + } + } +} + + +void MemoryAccountant::useCacheSizes(size_t sizes[], size_t length) +{ + if (head_) + FAIL("MemoryAccountant: Cannot set cache sizes as allocations already occured!"); + + createCacheSizeNodes(sizes, length); + useCacheSizes_ = true; +} + +void MemoryAccountant::setAllocator(TestMemoryAllocator* allocator) +{ + allocator_ = allocator; +} + +void MemoryAccountant::clear() +{ + MemoryAccountantAllocationNode* node = head_; + MemoryAccountantAllocationNode* to_be_deleted = NULLPTR; + while (node) { + to_be_deleted = node; + node = node->next_; + destroyAccountantAllocationNode(to_be_deleted); + } + head_ = NULLPTR; +} + +MemoryAccountantAllocationNode* MemoryAccountant::findNodeOfSize(size_t size) const +{ + if (useCacheSizes_) { + for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) { + if (((size > node->size_) && (node->next_ == NULLPTR)) + || ((size <= node->size_) && + !((node->next_->size_ != 0) && (node->next_->size_ <= size)))) + return node; + } + } + else + for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) + if (node->size_ == size) + return node; + return NULLPTR; +} + +MemoryAccountantAllocationNode* MemoryAccountant::findOrCreateNodeOfSize(size_t size) +{ + if (useCacheSizes_) + return findNodeOfSize(size); + + if (head_ && head_->size_ > size) + head_ = createNewAccountantAllocationNode(size, head_); + + for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) { + if (node->size_ == size) + return node; + if (node->next_ == NULLPTR || node->next_->size_ > size) + node->next_ = createNewAccountantAllocationNode(size, node->next_); + } + head_ = createNewAccountantAllocationNode(size, head_); + return head_; +} + +void MemoryAccountant::alloc(size_t size) +{ + MemoryAccountantAllocationNode* node = findOrCreateNodeOfSize(size); + node->allocations_++; + node->currentAllocations_++; + node->maxAllocations_ = (node->currentAllocations_ > node->maxAllocations_) ? node->currentAllocations_ : node->maxAllocations_; +} + +void MemoryAccountant::dealloc(size_t size) +{ + MemoryAccountantAllocationNode* node = findOrCreateNodeOfSize(size); + node->deallocations_++; + if (node->currentAllocations_) + node->currentAllocations_--; +} + +size_t MemoryAccountant::totalAllocationsOfSize(size_t size) const +{ + MemoryAccountantAllocationNode* node = findNodeOfSize(size); + if (node) + return node->allocations_; + return 0; +} + +size_t MemoryAccountant::totalDeallocationsOfSize(size_t size) const +{ + MemoryAccountantAllocationNode* node = findNodeOfSize(size); + if (node) + return node->deallocations_; + return 0; +} + +size_t MemoryAccountant::maximumAllocationAtATimeOfSize(size_t size) const +{ + MemoryAccountantAllocationNode* node = findNodeOfSize(size); + if (node) + return node->maxAllocations_; + return 0; +} + +size_t MemoryAccountant::totalAllocations() const +{ + size_t theTotalAllocations = 0; + + for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) + theTotalAllocations += node->allocations_; + + return theTotalAllocations; +} + +size_t MemoryAccountant::totalDeallocations() const +{ + size_t theTotalDeallocations = 0; + + for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) + theTotalDeallocations += node->deallocations_; + + return theTotalDeallocations; +} + +SimpleString MemoryAccountant::reportNoAllocations() const +{ + return SimpleString("CppUTest Memory Accountant has not noticed any allocations or deallocations. Sorry\n"); +} + +SimpleString MemoryAccountant::reportTitle() const +{ + if (useCacheSizes_) + return "CppUTest Memory Accountant report (with cache sizes):\n"; + return "CppUTest Memory Accountant report:\n"; +} + +SimpleString MemoryAccountant::reportHeader() const +{ + if (useCacheSizes_) + return "Cache size # allocations # deallocations max # allocations at one time\n"; + return "Allocation size # allocations # deallocations max # allocations at one time\n"; +} + +#define MEMORY_ACCOUNTANT_ROW_FORMAT "%s %5d %5d %5d\n" + +SimpleString MemoryAccountant::reportFooter() const +{ + return SimpleString(" Thank you for your business\n"); +} + +SimpleString MemoryAccountant::stringSize(size_t size) const +{ + return (size == 0) ? StringFrom("other") : StringFromFormat("%5d", (int) size); +} + +SimpleString MemoryAccountant::report() const +{ + if (head_ == NULLPTR) + return reportNoAllocations(); + + SimpleString accountantReport = reportTitle() + reportHeader(); + + for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) + accountantReport += StringFromFormat(MEMORY_ACCOUNTANT_ROW_FORMAT, stringSize(node->size_).asCharString(), (int) node->allocations_, (int) node->deallocations_, (int) node->maxAllocations_); + + return accountantReport + reportFooter(); +} + +AccountingTestMemoryAllocator::AccountingTestMemoryAllocator(MemoryAccountant& accountant, TestMemoryAllocator* origAllocator) + : accountant_(accountant), originalAllocator_(origAllocator), head_(NULLPTR) +{ +} + +AccountingTestMemoryAllocator::~AccountingTestMemoryAllocator() +{ +} + +struct AccountingTestMemoryAllocatorMemoryNode +{ + char* memory_; + size_t size_; + AccountingTestMemoryAllocatorMemoryNode* next_; +}; + +void AccountingTestMemoryAllocator::addMemoryToMemoryTrackingToKeepTrackOfSize(char* memory, size_t size) +{ + AccountingTestMemoryAllocatorMemoryNode* node = (AccountingTestMemoryAllocatorMemoryNode*) (void*) originalAllocator_->alloc_memory(sizeof(AccountingTestMemoryAllocatorMemoryNode), __FILE__, __LINE__); + node->memory_ = memory; + node->size_ = size; + node->next_ = head_; + head_ = node; +} + +size_t AccountingTestMemoryAllocator::removeNextNodeAndReturnSize(AccountingTestMemoryAllocatorMemoryNode* node) +{ + AccountingTestMemoryAllocatorMemoryNode* foundNode = node->next_; + node->next_ = node->next_->next_; + + size_t size = foundNode->size_; + originalAllocator_->free_memory((char*) foundNode, size, __FILE__, __LINE__); + return size; +} + +size_t AccountingTestMemoryAllocator::removeHeadAndReturnSize() +{ + AccountingTestMemoryAllocatorMemoryNode* foundNode = head_; + head_ = head_->next_; + + size_t size = foundNode->size_; + originalAllocator_->free_memory((char*) foundNode, size, __FILE__, __LINE__); + return size; +} + +size_t AccountingTestMemoryAllocator::removeMemoryFromTrackingAndReturnAllocatedSize(char* memory) +{ + if (head_ && head_->memory_ == memory) + return removeHeadAndReturnSize(); + + for (AccountingTestMemoryAllocatorMemoryNode* node = head_; node; node = node->next_) { + if (node->next_ && node->next_->memory_ == memory) + return removeNextNodeAndReturnSize(node); + } + + return 0; +} + +char* AccountingTestMemoryAllocator::alloc_memory(size_t size, const char* file, size_t line) +{ + accountant_.alloc(size); + char* memory = originalAllocator_->alloc_memory(size, file, line); + addMemoryToMemoryTrackingToKeepTrackOfSize(memory, size); + return memory; +} + +void AccountingTestMemoryAllocator::free_memory(char* memory, size_t, const char* file, size_t line) +{ + size_t size = removeMemoryFromTrackingAndReturnAllocatedSize(memory); + accountant_.dealloc(size); + originalAllocator_->free_memory(memory, size, file, line); +} + +TestMemoryAllocator* AccountingTestMemoryAllocator::actualAllocator() +{ + return originalAllocator_->actualAllocator(); +} + +TestMemoryAllocator* AccountingTestMemoryAllocator::originalAllocator() +{ + return originalAllocator_; +} + +const char* AccountingTestMemoryAllocator::alloc_name() const +{ + return originalAllocator_->alloc_name(); +} + +const char* AccountingTestMemoryAllocator::free_name() const +{ + return originalAllocator_->free_name(); +} + +GlobalMemoryAccountant::GlobalMemoryAccountant() + : mallocAllocator_(NULLPTR), newAllocator_(NULLPTR), newArrayAllocator_(NULLPTR) +{ +} + +GlobalMemoryAccountant::~GlobalMemoryAccountant() +{ + restoreMemoryAllocators(); + delete mallocAllocator_; + delete newAllocator_; + delete newArrayAllocator_; +} + +void GlobalMemoryAccountant::useCacheSizes(size_t sizes[], size_t length) +{ + accountant_.useCacheSizes(sizes, length); +} + +void GlobalMemoryAccountant::start() +{ + if (mallocAllocator_ != NULLPTR) + FAIL("Global allocator start called twice!"); + + mallocAllocator_ = new AccountingTestMemoryAllocator(accountant_, getCurrentMallocAllocator()); + newAllocator_ = new AccountingTestMemoryAllocator(accountant_, getCurrentNewAllocator()); + newArrayAllocator_ = new AccountingTestMemoryAllocator(accountant_, getCurrentNewArrayAllocator()); + + accountant_.setAllocator(getCurrentMallocAllocator()); + + setCurrentMallocAllocator(mallocAllocator_); + setCurrentNewAllocator(newAllocator_); + setCurrentNewArrayAllocator(newArrayAllocator_); +} + +void GlobalMemoryAccountant::restoreMemoryAllocators() +{ + if (getCurrentMallocAllocator() == mallocAllocator_) + setCurrentMallocAllocator(mallocAllocator_->originalAllocator()); + + if (getCurrentNewAllocator() == newAllocator_) + setCurrentNewAllocator(newAllocator_->originalAllocator()); + + if (getCurrentNewArrayAllocator() == newArrayAllocator_) + setCurrentNewArrayAllocator(newArrayAllocator_->originalAllocator()); +} + +void GlobalMemoryAccountant::stop() +{ + if (mallocAllocator_ == NULLPTR) + FAIL("GlobalMemoryAccount: Stop called without starting"); + + if (getCurrentMallocAllocator() != mallocAllocator_) + FAIL("GlobalMemoryAccountant: Malloc memory allocator has been changed while accounting for memory"); + + if (getCurrentNewAllocator() != newAllocator_) + FAIL("GlobalMemoryAccountant: New memory allocator has been changed while accounting for memory"); + + if (getCurrentNewArrayAllocator() != newArrayAllocator_) + FAIL("GlobalMemoryAccountant: New Array memory allocator has been changed while accounting for memory"); + + restoreMemoryAllocators(); +} + +SimpleString GlobalMemoryAccountant::report() +{ + return accountant_.report(); +} + +TestMemoryAllocator* GlobalMemoryAccountant::getMallocAllocator() +{ + return mallocAllocator_; +} + +TestMemoryAllocator* GlobalMemoryAccountant::getNewAllocator() +{ + return newAllocator_; +} + +TestMemoryAllocator* GlobalMemoryAccountant::getNewArrayAllocator() +{ + return newArrayAllocator_; +} + diff --git a/src/CppUTest/TestOutput.cpp b/src/CppUTest/TestOutput.cpp index 113884ea7..cb4ced54e 100644 --- a/src/CppUTest/TestOutput.cpp +++ b/src/CppUTest/TestOutput.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -24,7 +24,6 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "CppUTest/TestHarness.h" #include "CppUTest/TestOutput.h" #include "CppUTest/PlatformSpecificFunctions.h" @@ -45,7 +44,7 @@ TestOutput::WorkingEnvironment TestOutput::getWorkingEnvironment() TestOutput::TestOutput() : - dotCount_(0), verbose_(false), color_(false), progressIndication_(".") + dotCount_(0), verbose_(level_quiet), color_(false), progressIndication_(".") { } @@ -53,9 +52,9 @@ TestOutput::~TestOutput() { } -void TestOutput::verbose() +void TestOutput::verbose(VerbosityLevel level) { - verbose_ = true; + verbose_ = level; } void TestOutput::color() @@ -73,6 +72,11 @@ void TestOutput::print(long n) print(StringFrom(n).asCharString()); } +void TestOutput::print(size_t n) +{ + print(StringFrom(n).asCharString()); +} + void TestOutput::printDouble(double d) { print(StringFrom(d).asCharString()); @@ -92,7 +96,7 @@ TestOutput& operator<<(TestOutput& p, long int i) void TestOutput::printCurrentTestStarted(const UtestShell& test) { - if (verbose_) print(test.getFormattedName().asCharString()); + if (verbose_ > level_quiet) print(test.getFormattedName().asCharString()); if (test.willRun()) { setProgressIndicator("."); @@ -104,7 +108,7 @@ void TestOutput::printCurrentTestStarted(const UtestShell& test) void TestOutput::printCurrentTestEnded(const TestResult& res) { - if (verbose_) { + if (verbose_ > level_quiet) { print(" - "); print(res.getCurrentTestTotalExecutionTime()); print(" ms\n"); @@ -140,13 +144,20 @@ void TestOutput::printCurrentGroupEnded(const TestResult& /*res*/) void TestOutput::printTestsEnded(const TestResult& result) { print("\n"); - if (result.getFailureCount() > 0) { + const bool isFailure = result.isFailure(); + const size_t failureCount = result.getFailureCount(); + if (isFailure) { if (color_) { print("\033[31;1m"); } print("Errors ("); - print(result.getFailureCount()); - print(" failures, "); + if (failureCount > 0) { + print(failureCount); + print(" failures, "); + } + else { + print("ran nothing, "); + } } else { if (color_) { @@ -169,10 +180,16 @@ void TestOutput::printTestsEnded(const TestResult& result) if (color_) { print("\033[m"); } + if (isFailure && failureCount == 0) { + print("\nNote: test run failed because no tests were run or ignored. Assuming something went wrong. " + "This often happens because of linking errors or typos in test filter."); + } print("\n\n"); + + dotCount_ = 0; } -void TestOutput::printTestRun(int number, int total) +void TestOutput::printTestRun(size_t number, size_t total) { if (total > 1) { print("Test run "); @@ -220,7 +237,7 @@ void TestOutput::printFailureMessage(SimpleString reason) print("\n\n"); } -void TestOutput::printErrorInFileOnLineFormattedForWorkingEnvironment(SimpleString file, int lineNumber) +void TestOutput::printErrorInFileOnLineFormattedForWorkingEnvironment(SimpleString file, size_t lineNumber) { if (TestOutput::getWorkingEnvironment() == TestOutput::visualStudio) printVisualStudioErrorInFileOnLine(file, lineNumber); @@ -228,7 +245,7 @@ void TestOutput::printErrorInFileOnLineFormattedForWorkingEnvironment(SimpleStri printEclipseErrorInFileOnLine(file, lineNumber); } -void TestOutput::printEclipseErrorInFileOnLine(SimpleString file, int lineNumber) +void TestOutput::printEclipseErrorInFileOnLine(SimpleString file, size_t lineNumber) { print("\n"); print(file.asCharString()); @@ -238,7 +255,7 @@ void TestOutput::printEclipseErrorInFileOnLine(SimpleString file, int lineNumber print(" error:"); } -void TestOutput::printVisualStudioErrorInFileOnLine(SimpleString file, int lineNumber) +void TestOutput::printVisualStudioErrorInFileOnLine(SimpleString file, size_t lineNumber) { print("\n"); print(file.asCharString()); @@ -248,12 +265,16 @@ void TestOutput::printVisualStudioErrorInFileOnLine(SimpleString file, int lineN print(" error:"); } +void TestOutput::printVeryVerbose(const char* str) +{ + if(verbose_ == level_veryVerbose) + printBuffer(str); +} + + void ConsoleTestOutput::printBuffer(const char* s) { - while (*s) { - PlatformSpecificPutchar(*s); - s++; - } + PlatformSpecificFPuts(s, PlatformSpecificStdOut); flush(); } @@ -267,7 +288,7 @@ StringBufferTestOutput::~StringBufferTestOutput() } CompositeTestOutput::CompositeTestOutput() - : outputOne_(NULL), outputTwo_(NULL) + : outputOne_(NULLPTR), outputTwo_(NULLPTR) { } @@ -325,10 +346,10 @@ void CompositeTestOutput::printCurrentGroupEnded(const TestResult& res) if (outputTwo_) outputTwo_->printCurrentGroupEnded(res); } -void CompositeTestOutput::verbose() +void CompositeTestOutput::verbose(VerbosityLevel level) { - if (outputOne_) outputOne_->verbose(); - if (outputTwo_) outputTwo_->verbose(); + if (outputOne_) outputOne_->verbose(level); + if (outputTwo_) outputTwo_->verbose(level); } void CompositeTestOutput::color() @@ -355,6 +376,12 @@ void CompositeTestOutput::print(long number) if (outputTwo_) outputTwo_->print(number); } +void CompositeTestOutput::print(size_t number) +{ + if (outputOne_) outputOne_->print(number); + if (outputTwo_) outputTwo_->print(number); +} + void CompositeTestOutput::printDouble(double number) { if (outputOne_) outputOne_->printDouble(number); @@ -373,6 +400,12 @@ void CompositeTestOutput::setProgressIndicator(const char* indicator) if (outputTwo_) outputTwo_->setProgressIndicator(indicator); } +void CompositeTestOutput::printVeryVerbose(const char* str) +{ + if (outputOne_) outputOne_->printVeryVerbose(str); + if (outputTwo_) outputTwo_->printVeryVerbose(str); +} + void CompositeTestOutput::flush() { if (outputOne_) outputOne_->flush(); diff --git a/src/CppUTest/TestPlugin.cpp b/src/CppUTest/TestPlugin.cpp index 9f83fee28..29aa38bcf 100644 --- a/src/CppUTest/TestPlugin.cpp +++ b/src/CppUTest/TestPlugin.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -62,10 +62,10 @@ void TestPlugin::runAllPostTestAction(UtestShell& test, TestResult& result) bool TestPlugin::parseAllArguments(int ac, char** av, int index) { - return parseAllArguments(ac, const_cast (av), index); + return parseAllArguments(ac, const_cast (av), index); } -bool TestPlugin::parseAllArguments(int ac, const char** av, int index) +bool TestPlugin::parseAllArguments(int ac, const char *const *av, int index) { if (parseArguments(ac, av, index)) return true; if (next_) return next_->parseAllArguments(ac, av, index); @@ -90,7 +90,7 @@ TestPlugin* TestPlugin::getNext() } TestPlugin* TestPlugin::removePluginByName(const SimpleString& name) { - TestPlugin* removed = 0; + TestPlugin* removed = NULLPTR; if (next_ && next_->getName() == name) { removed = next_; next_ = next_->next_; @@ -150,7 +150,7 @@ void SetPointerPlugin::postTestAction(UtestShell& /*test*/, TestResult& /*result //////// NullPlugin NullTestPlugin::NullTestPlugin() : - TestPlugin(0) + TestPlugin(NULLPTR) { } diff --git a/src/CppUTest/TestRegistry.cpp b/src/CppUTest/TestRegistry.cpp old mode 100755 new mode 100644 index 26c049859..542ab51a8 --- a/src/CppUTest/TestRegistry.cpp +++ b/src/CppUTest/TestRegistry.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -27,10 +27,10 @@ #include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" +#include "CppUTest/PlatformSpecificFunctions.h" TestRegistry::TestRegistry() : - tests_(NULL), nameFilters_(NULL), groupFilters_(NULL), firstPlugin_(NullTestPlugin::instance()), runInSeperateProcess_(false), currentRepetition_(0), runIgnored_(false) - + tests_(NULLPTR), nameFilters_(NULLPTR), groupFilters_(NULLPTR), firstPlugin_(NullTestPlugin::instance()), runInSeperateProcess_(false), currentRepetition_(0), runIgnored_(false) { } @@ -48,7 +48,7 @@ void TestRegistry::runAllTests(TestResult& result) bool groupStart = true; result.testsStarted(); - for (UtestShell *test = tests_; test != NULL; test = test->getNext()) { + for (UtestShell *test = tests_; test != NULLPTR; test = test->getNext()) { if (runInSeperateProcess_) test->setRunInSeperateProcess(); if (runIgnored_) test->setRunIgnored(); @@ -77,7 +77,7 @@ void TestRegistry::listTestGroupNames(TestResult& result) { SimpleString groupList; - for (UtestShell *test = tests_; test != NULL; test = test->getNext()) { + for (UtestShell *test = tests_; test != NULLPTR; test = test->getNext()) { SimpleString gname; gname += "#"; gname += test->getGroup(); @@ -100,7 +100,7 @@ void TestRegistry::listTestGroupAndCaseNames(TestResult& result) { SimpleString groupAndNameList; - for (UtestShell *test = tests_; test != NULL; test = test->getNext()) { + for (UtestShell *test = tests_; test != NULLPTR; test = test->getNext()) { if (testShouldRun(test, result)) { SimpleString groupAndName; groupAndName += "#"; @@ -123,22 +123,42 @@ void TestRegistry::listTestGroupAndCaseNames(TestResult& result) result.print(groupAndNameList.asCharString()); } +void TestRegistry::listTestLocations(TestResult& result) +{ + SimpleString testLocations; + + for (UtestShell *test = tests_; test != NULLPTR; test = test->getNext()) { + SimpleString testLocation; + testLocation += test->getGroup(); + testLocation += "."; + testLocation += test->getName(); + testLocation += "."; + testLocation += test->getFile(); + testLocation += "."; + testLocation += StringFromFormat("%d\n",(int) test->getLineNumber()); + + testLocations += testLocation; + } + + result.print(testLocations.asCharString()); +} + bool TestRegistry::endOfGroup(UtestShell* test) { return (!test || !test->getNext() || test->getGroup() != test->getNext()->getGroup()); } -int TestRegistry::countTests() +size_t TestRegistry::countTests() { return tests_ ? tests_->countTests() : 0; } -TestRegistry* TestRegistry::currentRegistry_ = 0; +TestRegistry* TestRegistry::currentRegistry_ = NULLPTR; TestRegistry* TestRegistry::getCurrentRegistry() { static TestRegistry registry; - return (currentRegistry_ == 0) ? ®istry : currentRegistry_; + return (currentRegistry_ == NULLPTR) ? ®istry : currentRegistry_; } void TestRegistry::setCurrentRegistry(TestRegistry* registry) @@ -148,7 +168,7 @@ void TestRegistry::setCurrentRegistry(TestRegistry* registry) void TestRegistry::unDoLastAddTest() { - tests_ = tests_ ? tests_->getNext() : NULL; + tests_ = tests_ ? tests_->getNext() : NULLPTR; } @@ -227,6 +247,20 @@ UtestShell* TestRegistry::getFirstTest() return tests_; } +void TestRegistry::shuffleTests(size_t seed) +{ + UtestShellPointerArray array(getFirstTest()); + array.shuffle(seed); + tests_ = array.getFirstTest(); +} + +void TestRegistry::reverseTests() +{ + UtestShellPointerArray array(getFirstTest()); + array.reverse(); + tests_ = array.getFirstTest(); +} + UtestShell* TestRegistry::getTestWithNext(UtestShell* test) { UtestShell* current = tests_; @@ -243,7 +277,7 @@ UtestShell* TestRegistry::findTestWithName(const SimpleString& name) return current; current = current->getNext(); } - return NULL; + return NULLPTR; } UtestShell* TestRegistry::findTestWithGroup(const SimpleString& group) @@ -254,6 +288,6 @@ UtestShell* TestRegistry::findTestWithGroup(const SimpleString& group) return current; current = current->getNext(); } - return NULL; + return NULLPTR; } diff --git a/src/CppUTest/TestResult.cpp b/src/CppUTest/TestResult.cpp index 90c215d69..37ff57f84 100644 --- a/src/CppUTest/TestResult.cpp +++ b/src/CppUTest/TestResult.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -44,19 +44,19 @@ TestResult::~TestResult() void TestResult::currentGroupStarted(UtestShell* test) { output_.printCurrentGroupStarted(*test); - currentGroupTimeStarted_ = GetPlatformSpecificTimeInMillis(); + currentGroupTimeStarted_ = (size_t) GetPlatformSpecificTimeInMillis(); } void TestResult::currentGroupEnded(UtestShell* /*test*/) { - currentGroupTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentGroupTimeStarted_; + currentGroupTotalExecutionTime_ = (size_t) GetPlatformSpecificTimeInMillis() - currentGroupTimeStarted_; output_.printCurrentGroupEnded(*this); } void TestResult::currentTestStarted(UtestShell* test) { output_.printCurrentTestStarted(*test); - currentTestTimeStarted_ = GetPlatformSpecificTimeInMillis(); + currentTestTimeStarted_ = (size_t) GetPlatformSpecificTimeInMillis(); } void TestResult::print(const char* text) @@ -64,9 +64,14 @@ void TestResult::print(const char* text) output_.print(text); } +void TestResult::printVeryVerbose(const char* text) +{ + output_.printVeryVerbose(text); +} + void TestResult::currentTestEnded(UtestShell* /*test*/) { - currentTestTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentTestTimeStarted_; + currentTestTotalExecutionTime_ = (size_t) GetPlatformSpecificTimeInMillis() - currentTestTimeStarted_; output_.printCurrentTestEnded(*this); } @@ -104,33 +109,33 @@ void TestResult::countIgnored() void TestResult::testsStarted() { - timeStarted_ = GetPlatformSpecificTimeInMillis(); + timeStarted_ = (size_t) GetPlatformSpecificTimeInMillis(); output_.printTestsStarted(); } void TestResult::testsEnded() { - long timeEnded = GetPlatformSpecificTimeInMillis(); + size_t timeEnded = (size_t) GetPlatformSpecificTimeInMillis(); totalExecutionTime_ = timeEnded - timeStarted_; output_.printTestsEnded(*this); } -long TestResult::getTotalExecutionTime() const +size_t TestResult::getTotalExecutionTime() const { return totalExecutionTime_; } -void TestResult::setTotalExecutionTime(long exTime) +void TestResult::setTotalExecutionTime(size_t exTime) { totalExecutionTime_ = exTime; } -long TestResult::getCurrentTestTotalExecutionTime() const +size_t TestResult::getCurrentTestTotalExecutionTime() const { return currentTestTotalExecutionTime_; } -long TestResult::getCurrentGroupTotalExecutionTime() const +size_t TestResult::getCurrentGroupTotalExecutionTime() const { return currentGroupTotalExecutionTime_; } diff --git a/src/CppUTest/TestTestingFixture.cpp b/src/CppUTest/TestTestingFixture.cpp index 9e7d9b938..a5e73d33e 100644 --- a/src/CppUTest/TestTestingFixture.cpp +++ b/src/CppUTest/TestTestingFixture.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,19 +30,165 @@ bool TestTestingFixture::lineOfCodeExecutedAfterCheck = false; +TestTestingFixture::TestTestingFixture() +{ + output_ = new StringBufferTestOutput(); + result_ = new TestResult(*output_); + genTest_ = new ExecFunctionTestShell(); + registry_ = new TestRegistry(); + ownsExecFunction_ = false; + + registry_->setCurrentRegistry(registry_); + registry_->addTest(genTest_); + + lineOfCodeExecutedAfterCheck = false; +} + +void TestTestingFixture::flushOutputAndResetResult() +{ + output_->flush(); + delete result_; + result_ = new TestResult(*output_); +} + +TestTestingFixture::~TestTestingFixture() +{ + registry_->setCurrentRegistry(NULLPTR); + clearExecFunction(); + delete registry_; + delete result_; + delete output_; + delete genTest_; +} + +void TestTestingFixture::clearExecFunction() +{ + if (genTest_->testFunction_ && ownsExecFunction_) + delete genTest_->testFunction_; +} + +void TestTestingFixture::addTest(UtestShell * test) +{ + registry_->addTest(test); +} + +void TestTestingFixture::setTestFunction(void(*testFunction)()) +{ + clearExecFunction(); + + genTest_->testFunction_ = new ExecFunctionWithoutParameters(testFunction); + ownsExecFunction_ = true; +} + +void TestTestingFixture::setTestFunction(ExecFunction* testFunction) +{ + clearExecFunction(); + + genTest_->testFunction_ = testFunction; + + ownsExecFunction_ = false; +} + +void TestTestingFixture::setSetup(void(*setupFunction)()) +{ + genTest_->setup_ = setupFunction; +} + +void TestTestingFixture::setTeardown(void(*teardownFunction)()) +{ + genTest_->teardown_ = teardownFunction; +} + +void TestTestingFixture::installPlugin(TestPlugin* plugin) +{ + registry_->installPlugin(plugin); +} + +void TestTestingFixture::setRunTestsInSeperateProcess() +{ + registry_->setRunTestsInSeperateProcess(); +} + +void TestTestingFixture::setOutputVerbose() +{ + output_->verbose(TestOutput::level_verbose); +} + +void TestTestingFixture::runTestWithMethod(void(*method)()) +{ + setTestFunction(method); + runAllTests(); +} + +void TestTestingFixture::runAllTests() +{ + registry_->runAllTests(*result_); +} + +size_t TestTestingFixture::getFailureCount() +{ + return result_->getFailureCount(); +} + +size_t TestTestingFixture::getCheckCount() +{ + return result_->getCheckCount(); +} + +size_t TestTestingFixture::getTestCount() +{ + return result_->getTestCount(); +} + +size_t TestTestingFixture::getIgnoreCount() +{ + return result_->getIgnoredCount(); +} + +TestRegistry* TestTestingFixture::getRegistry() +{ + return registry_; +} + +bool TestTestingFixture::hasTestFailed() +{ + return genTest_->hasFailed(); +} + +void TestTestingFixture::assertPrintContains(const SimpleString& contains) +{ + STRCMP_CONTAINS(contains.asCharString(), getOutput().asCharString()); +} + +void TestTestingFixture::assertPrintContainsNot(const SimpleString& contains) +{ + CHECK(! getOutput().contains(contains)); +} + + +const SimpleString& TestTestingFixture::getOutput() +{ + return output_->getOutput(); +} + +size_t TestTestingFixture::getRunCount() +{ + return result_->getRunCount(); +} + void TestTestingFixture::lineExecutedAfterCheck() { - lineOfCodeExecutedAfterCheck = true; + lineOfCodeExecutedAfterCheck = true; } -void TestTestingFixture::checkTestFailsWithProperTestLocation(const char* text, const char* file, int line) +void TestTestingFixture::checkTestFailsWithProperTestLocation(const char* text, const char* file, size_t line) { - if (getFailureCount() != 1) - FAIL_LOCATION(StringFromFormat("Expected one test failure, but got %d amount of test failures", getFailureCount()).asCharString(), file, line); + if (getFailureCount() != 1) + FAIL_LOCATION(StringFromFormat("Expected one test failure, but got %d amount of test failures", (int) getFailureCount()).asCharString(), file, line); - STRCMP_CONTAINS_LOCATION(text, output_->getOutput().asCharString(), "", file, line); + STRCMP_CONTAINS_LOCATION(text, output_->getOutput().asCharString(), "", file, line); - if (lineOfCodeExecutedAfterCheck) - FAIL_LOCATION("The test should jump/throw on failure and not execute the next line. However, the next line was executed.", file, line) + if (lineOfCodeExecutedAfterCheck) + FAIL_LOCATION("The test should jump/throw on failure and not execute the next line. However, the next line was executed.", file, line); } diff --git a/src/CppUTest/Utest.cpp b/src/CppUTest/Utest.cpp old mode 100755 new mode 100644 index 14a025182..d74a87c79 --- a/src/CppUTest/Utest.cpp +++ b/src/CppUTest/Utest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,6 +30,10 @@ #include "CppUTest/PlatformSpecificFunctions.h" #include "CppUTest/TestOutput.h" +#if defined(__GNUC__) && __GNUC__ >= 11 +# define NEEDS_DISABLE_NULL_WARNING +#endif /* GCC >= 11 */ + bool doubles_equal(double d1, double d2, double threshold) { if (PlatformSpecificIsNan(d1) || PlatformSpecificIsNan(d2) || PlatformSpecificIsNan(threshold)) @@ -55,7 +59,7 @@ class OutsideTestRunnerUTest: public UtestShell { return defaultTestResult; } - virtual ~OutsideTestRunnerUTest() + virtual ~OutsideTestRunnerUTest() CPPUTEST_DESTRUCTOR_OVERRIDE { } private: @@ -131,17 +135,29 @@ extern "C" { /******************************** */ +static const NormalTestTerminator normalTestTerminator = NormalTestTerminator(); +static const CrashingTestTerminator crashingTestTerminator = CrashingTestTerminator(); +static const TestTerminatorWithoutExceptions normalTestTerminatorWithoutExceptions = TestTerminatorWithoutExceptions(); +static const CrashingTestTerminatorWithoutExceptions crashingTestTerminatorWithoutExceptions = CrashingTestTerminatorWithoutExceptions(); + +const TestTerminator *UtestShell::currentTestTerminator_ = &normalTestTerminator; +const TestTerminator *UtestShell::currentTestTerminatorWithoutExceptions_ = &normalTestTerminatorWithoutExceptions; + +bool UtestShell::rethrowExceptions_ = false; + +/******************************** */ + UtestShell::UtestShell() : - group_("UndefinedTestGroup"), name_("UndefinedTest"), file_("UndefinedFile"), lineNumber_(0), next_(NULL), isRunAsSeperateProcess_(false), hasFailed_(false) + group_("UndefinedTestGroup"), name_("UndefinedTest"), file_("UndefinedFile"), lineNumber_(0), next_(NULLPTR), isRunAsSeperateProcess_(false), hasFailed_(false) { } -UtestShell::UtestShell(const char* groupName, const char* testName, const char* fileName, int lineNumber) : - group_(groupName), name_(testName), file_(fileName), lineNumber_(lineNumber), next_(NULL), isRunAsSeperateProcess_(false), hasFailed_(false) +UtestShell::UtestShell(const char* groupName, const char* testName, const char* fileName, size_t lineNumber) : + group_(groupName), name_(testName), file_(fileName), lineNumber_(lineNumber), next_(NULLPTR), isRunAsSeperateProcess_(false), hasFailed_(false) { } -UtestShell::UtestShell(const char* groupName, const char* testName, const char* fileName, int lineNumber, UtestShell* nextTest) : +UtestShell::UtestShell(const char* groupName, const char* testName, const char* fileName, size_t lineNumber, UtestShell* nextTest) : group_(groupName), name_(testName), file_(fileName), lineNumber_(lineNumber), next_(nextTest), isRunAsSeperateProcess_(false), hasFailed_(false) { } @@ -150,14 +166,7 @@ UtestShell::~UtestShell() { } -// LCOV_EXCL_START - actually covered but not in .gcno due to race condition -static void defaultCrashMethod() -{ - UtestShell* ptr = (UtestShell*) 0x0; ptr->countTests(); -} -// LCOV_EXCL_STOP - -static void (*pleaseCrashMeRightNow) () = defaultCrashMethod; +static void (*pleaseCrashMeRightNow) () = PlatformSpecificAbort; void UtestShell::setCrashMethod(void (*crashme)()) { @@ -166,7 +175,7 @@ void UtestShell::setCrashMethod(void (*crashme)()) void UtestShell::resetCrashMethod() { - pleaseCrashMeRightNow = defaultCrashMethod; + pleaseCrashMeRightNow = PlatformSpecificAbort; } void UtestShell::crash() @@ -177,6 +186,7 @@ void UtestShell::crash() void UtestShell::runOneTest(TestPlugin* plugin, TestResult& result) { hasFailed_ = false; + result.countRun(); HelperTestRunInfo runInfo(this, plugin, &result); if (isRunInSeperateProcess()) PlatformSpecificSetJmp(helperDoRunOneTestSeperateProcess, &runInfo); @@ -196,24 +206,49 @@ void UtestShell::destroyTest(Utest* test) void UtestShell::runOneTestInCurrentProcess(TestPlugin* plugin, TestResult& result) { + result.printVeryVerbose("\n-- before runAllPreTestAction: "); plugin->runAllPreTestAction(*this, result); + result.printVeryVerbose("\n-- after runAllPreTestAction: "); //save test context, so that test class can be tested UtestShell* savedTest = UtestShell::getCurrent(); TestResult* savedResult = UtestShell::getTestResult(); - result.countRun(); UtestShell::setTestResult(&result); UtestShell::setCurrentTest(this); - Utest* testToRun = createTest(); - testToRun->run(); - destroyTest(testToRun); + Utest* testToRun = NULLPTR; - UtestShell::setCurrentTest(savedTest); - UtestShell::setTestResult(savedResult); +#if CPPUTEST_HAVE_EXCEPTIONS + try + { +#endif + result.printVeryVerbose("\n---- before createTest: "); + testToRun = createTest(); + result.printVeryVerbose("\n---- after createTest: "); + result.printVeryVerbose("\n------ before runTest: "); + testToRun->run(); + result.printVeryVerbose("\n------ after runTest: "); + + UtestShell::setCurrentTest(savedTest); + UtestShell::setTestResult(savedResult); +#if CPPUTEST_HAVE_EXCEPTIONS + } + catch(...) + { + destroyTest(testToRun); + throw; + } +#endif + + result.printVeryVerbose("\n---- before destroyTest: "); + destroyTest(testToRun); + result.printVeryVerbose("\n---- after destroyTest: "); + + result.printVeryVerbose("\n-- before runAllPostTestAction: "); plugin->runAllPostTestAction(*this, result); + result.printVeryVerbose("\n-- after runAllPostTestAction: "); } UtestShell *UtestShell::getNext() const @@ -227,7 +262,7 @@ UtestShell* UtestShell::addTest(UtestShell *test) return this; } -int UtestShell::countTests() +size_t UtestShell::countTests() { return next_ ? next_->countTests() + 1 : 1; } @@ -295,7 +330,7 @@ void UtestShell::setFileName(const char* fileName) file_ = fileName; } -void UtestShell::setLineNumber(int lineNumber) +void UtestShell::setLineNumber(size_t lineNumber) { lineNumber_ = lineNumber; } @@ -315,16 +350,16 @@ const SimpleString UtestShell::getFile() const return SimpleString(file_); } -int UtestShell::getLineNumber() const +size_t UtestShell::getLineNumber() const { return lineNumber_; } bool UtestShell::match(const char* target, const TestFilter* filters) const { - if(filters == NULL) return true; + if(filters == NULLPTR) return true; - for(; filters != NULL; filters = filters->getNext()) + for(; filters != NULLPTR; filters = filters->getNext()) if(filters->match(target)) return true; return false; @@ -337,102 +372,107 @@ bool UtestShell::shouldRun(const TestFilter* groupFilters, const TestFilter* nam void UtestShell::failWith(const TestFailure& failure) { - failWith(failure, NormalTestTerminator()); + failWith(failure, getCurrentTestTerminator()); } // LCOV_EXCL_LINE void UtestShell::failWith(const TestFailure& failure, const TestTerminator& terminator) { - hasFailed_ = true; - getTestResult()->addFailure(failure); + addFailure(failure); terminator.exitCurrentTest(); } // LCOV_EXCL_LINE +void UtestShell::addFailure(const TestFailure& failure) +{ + hasFailed_ = true; + getTestResult()->addFailure(failure); +} + void UtestShell::exitTest(const TestTerminator& terminator) { terminator.exitCurrentTest(); } // LCOV_EXCL_LINE -void UtestShell::assertTrue(bool condition, const char *checkString, const char *conditionString, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertTrue(bool condition, const char *checkString, const char *conditionString, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (!condition) failWith(CheckFailure(this, fileName, lineNumber, checkString, conditionString, text), testTerminator); } -void UtestShell::fail(const char *text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::fail(const char *text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); failWith(FailFailure(this, fileName, lineNumber, text), testTerminator); } // LCOV_EXCL_LINE -void UtestShell::assertCstrEqual(const char* expected, const char* actual, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertCstrEqual(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); - if (actual == 0 && expected == 0) return; - if (actual == 0 || expected == 0) + if (actual == NULLPTR && expected == NULLPTR) return; + if (actual == NULLPTR || expected == NULLPTR) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); if (SimpleString::StrCmp(expected, actual) != 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); } -void UtestShell::assertCstrNEqual(const char* expected, const char* actual, size_t length, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertCstrNEqual(const char* expected, const char* actual, size_t length, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); - if (actual == 0 && expected == 0) return; - if (actual == 0 || expected == 0) + if (actual == NULLPTR && expected == NULLPTR) return; + if (actual == NULLPTR || expected == NULLPTR) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); if (SimpleString::StrNCmp(expected, actual, length) != 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); } -void UtestShell::assertCstrNoCaseEqual(const char* expected, const char* actual, const char* text, const char* fileName, int lineNumber) +void UtestShell::assertCstrNoCaseEqual(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber) { getTestResult()->countCheck(); - if (actual == 0 && expected == 0) return; - if (actual == 0 || expected == 0) + if (actual == NULLPTR && expected == NULLPTR) return; + if (actual == NULLPTR || expected == NULLPTR) failWith(StringEqualNoCaseFailure(this, fileName, lineNumber, expected, actual, text)); if (!SimpleString(expected).equalsNoCase(actual)) failWith(StringEqualNoCaseFailure(this, fileName, lineNumber, expected, actual, text)); } -void UtestShell::assertCstrContains(const char* expected, const char* actual, const char* text, const char* fileName, int lineNumber) +void UtestShell::assertCstrContains(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber) { getTestResult()->countCheck(); - if (actual == 0 && expected == 0) return; - if(actual == 0 || expected == 0) + if (actual == NULLPTR && expected == NULLPTR) return; + if (actual == NULLPTR || expected == NULLPTR) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); if (!SimpleString(actual).contains(expected)) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); } -void UtestShell::assertCstrNoCaseContains(const char* expected, const char* actual, const char* text, const char* fileName, int lineNumber) +void UtestShell::assertCstrNoCaseContains(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber) { getTestResult()->countCheck(); - if (actual == 0 && expected == 0) return; - if(actual == 0 || expected == 0) + if (actual == NULLPTR && expected == NULLPTR) return; + if (actual == NULLPTR || expected == NULLPTR) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); if (!SimpleString(actual).containsNoCase(expected)) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); } -void UtestShell::assertLongsEqual(long expected, long actual, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertLongsEqual(long expected, long actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(LongsEqualFailure (this, fileName, lineNumber, expected, actual, text), testTerminator); } -void UtestShell::assertUnsignedLongsEqual(unsigned long expected, unsigned long actual, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertUnsignedLongsEqual(unsigned long expected, unsigned long actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(UnsignedLongsEqualFailure (this, fileName, lineNumber, expected, actual, text), testTerminator); } -void UtestShell::assertLongLongsEqual(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertLongLongsEqual(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); -#ifdef CPPUTEST_USE_LONG_LONG +#if CPPUTEST_USE_LONG_LONG if (expected != actual) failWith(LongLongsEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); #else @@ -442,10 +482,10 @@ void UtestShell::assertLongLongsEqual(cpputest_longlong expected, cpputest_longl #endif } -void UtestShell::assertUnsignedLongLongsEqual(cpputest_ulonglong expected, cpputest_ulonglong actual, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertUnsignedLongLongsEqual(cpputest_ulonglong expected, cpputest_ulonglong actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); -#ifdef CPPUTEST_USE_LONG_LONG +#if CPPUTEST_USE_LONG_LONG if (expected != actual) failWith(UnsignedLongLongsEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); #else @@ -455,60 +495,67 @@ void UtestShell::assertUnsignedLongLongsEqual(cpputest_ulonglong expected, cpput #endif } -void UtestShell::assertSignedBytesEqual(signed char expected, signed char actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertSignedBytesEqual(signed char expected, signed char actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(SignedBytesEqualFailure (this, fileName, lineNumber, expected, actual, text), testTerminator); } -void UtestShell::assertPointersEqual(const void* expected, const void* actual, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertPointersEqual(const void* expected, const void* actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(EqualsFailure(this, fileName, lineNumber, StringFrom(expected), StringFrom(actual), text), testTerminator); } -void UtestShell::assertFunctionPointersEqual(void (*expected)(), void (*actual)(), const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertFunctionPointersEqual(void (*expected)(), void (*actual)(), const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(EqualsFailure(this, fileName, lineNumber, StringFrom(expected), StringFrom(actual), text), testTerminator); } -void UtestShell::assertDoublesEqual(double expected, double actual, double threshold, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertDoublesEqual(double expected, double actual, double threshold, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (!doubles_equal(expected, actual, threshold)) failWith(DoublesEqualFailure(this, fileName, lineNumber, expected, actual, threshold, text), testTerminator); } -void UtestShell::assertBinaryEqual(const void *expected, const void *actual, size_t length, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertBinaryEqual(const void *expected, const void *actual, size_t length, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); - if (actual == 0 && expected == 0) return; - if (actual == 0 || expected == 0) + if (length == 0) return; + if (actual == NULLPTR && expected == NULLPTR) return; + if (actual == NULLPTR || expected == NULLPTR) failWith(BinaryEqualFailure(this, fileName, lineNumber, (const unsigned char *) expected, (const unsigned char *) actual, length, text), testTerminator); if (SimpleString::MemCmp(expected, actual, length) != 0) failWith(BinaryEqualFailure(this, fileName, lineNumber, (const unsigned char *) expected, (const unsigned char *) actual, length, text), testTerminator); } -void UtestShell::assertBitsEqual(unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator) +void UtestShell::assertBitsEqual(unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if ((expected & mask) != (actual & mask)) failWith(BitsEqualFailure(this, fileName, lineNumber, expected, actual, mask, byteCount, text), testTerminator); } -void UtestShell::assertEquals(bool failed, const char* expected, const char* actual, const char* text, const char* file, int line, const TestTerminator& testTerminator) +void UtestShell::assertEquals(bool failed, const char* expected, const char* actual, const char* text, const char* file, size_t line, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (failed) failWith(CheckEqualFailure(this, file, line, expected, actual, text), testTerminator); } +void UtestShell::assertCompare(bool comparison, const char *checkString, const char *comparisonString, const char *text, const char *fileName, size_t lineNumber, const TestTerminator &testTerminator) +{ + getTestResult()->countCheck(); + if (!comparison) + failWith(ComparisonFailure(this, fileName, lineNumber, checkString, comparisonString, text), testTerminator); +} -void UtestShell::print(const char *text, const char* fileName, int lineNumber) +void UtestShell::print(const char *text, const char* fileName, size_t lineNumber) { SimpleString stringToPrint = "\n"; stringToPrint += fileName; @@ -519,13 +566,18 @@ void UtestShell::print(const char *text, const char* fileName, int lineNumber) getTestResult()->print(stringToPrint.asCharString()); } -void UtestShell::print(const SimpleString& text, const char* fileName, int lineNumber) +void UtestShell::print(const SimpleString& text, const char* fileName, size_t lineNumber) { print(text.asCharString(), fileName, lineNumber); } -TestResult* UtestShell::testResult_ = NULL; -UtestShell* UtestShell::currentTest_ = NULL; +void UtestShell::printVeryVerbose(const char* text) +{ + getTestResult()->printVeryVerbose(text); +} + +TestResult* UtestShell::testResult_ = NULLPTR; +UtestShell* UtestShell::currentTest_ = NULLPTR; void UtestShell::setTestResult(TestResult* result) { @@ -539,18 +591,49 @@ void UtestShell::setCurrentTest(UtestShell* test) TestResult* UtestShell::getTestResult() { - if (testResult_ == NULL) + if (testResult_ == NULLPTR) return &OutsideTestRunnerUTest::instance().getTestResult(); return testResult_; } UtestShell* UtestShell::getCurrent() { - if (currentTest_ == NULL) + if (currentTest_ == NULLPTR) return &OutsideTestRunnerUTest::instance(); return currentTest_; } +const TestTerminator &UtestShell::getCurrentTestTerminator() +{ + return *currentTestTerminator_; +} + +const TestTerminator &UtestShell::getCurrentTestTerminatorWithoutExceptions() +{ + return *currentTestTerminatorWithoutExceptions_; +} + +void UtestShell::setCrashOnFail() +{ + currentTestTerminator_ = &crashingTestTerminator; + currentTestTerminatorWithoutExceptions_ = &crashingTestTerminatorWithoutExceptions; +} + +void UtestShell::restoreDefaultTestTerminator() +{ + currentTestTerminator_ = &normalTestTerminator; + currentTestTerminatorWithoutExceptions_ = &normalTestTerminatorWithoutExceptions; +} + +void UtestShell::setRethrowExceptions(bool rethrowExceptions) +{ + rethrowExceptions_ = rethrowExceptions; +} + +bool UtestShell::isRethrowingExceptions() +{ + return rethrowExceptions_; +} ExecFunctionTestShell::~ExecFunctionTestShell() { @@ -566,28 +649,77 @@ Utest::~Utest() { } -#if CPPUTEST_USE_STD_CPP_LIB +#if CPPUTEST_HAVE_EXCEPTIONS void Utest::run() { + UtestShell* current = UtestShell::getCurrent(); + int jumpResult = 0; try { - if (PlatformSpecificSetJmp(helperDoTestSetup, this)) { + current->printVeryVerbose("\n-------- before setup: "); + jumpResult = PlatformSpecificSetJmp(helperDoTestSetup, this); + current->printVeryVerbose("\n-------- after setup: "); + + if (jumpResult) { + current->printVeryVerbose("\n---------- before body: "); PlatformSpecificSetJmp(helperDoTestBody, this); + current->printVeryVerbose("\n---------- after body: "); } } catch (CppUTestFailedException&) { PlatformSpecificRestoreJumpBuffer(); } +#if CPPUTEST_USE_STD_CPP_LIB + catch (const std::exception &e) + { + current->addFailure(UnexpectedExceptionFailure(current, e)); + PlatformSpecificRestoreJumpBuffer(); + if (current->isRethrowingExceptions()) + { + throw; + } + } +#endif + catch (...) + { + current->addFailure(UnexpectedExceptionFailure(current)); + PlatformSpecificRestoreJumpBuffer(); + if (current->isRethrowingExceptions()) + { + throw; + } + } try { + current->printVeryVerbose("\n-------- before teardown: "); PlatformSpecificSetJmp(helperDoTestTeardown, this); + current->printVeryVerbose("\n-------- after teardown: "); } catch (CppUTestFailedException&) { PlatformSpecificRestoreJumpBuffer(); } - +#if CPPUTEST_USE_STD_CPP_LIB + catch (const std::exception &e) + { + current->addFailure(UnexpectedExceptionFailure(current, e)); + PlatformSpecificRestoreJumpBuffer(); + if (current->isRethrowingExceptions()) + { + throw; + } + } +#endif + catch (...) + { + current->addFailure(UnexpectedExceptionFailure(current)); + PlatformSpecificRestoreJumpBuffer(); + if (current->isRethrowingExceptions()) + { + throw; + } + } } #else @@ -622,7 +754,7 @@ TestTerminator::~TestTerminator() void NormalTestTerminator::exitCurrentTest() const { - #if CPPUTEST_USE_STD_CPP_LIB + #if CPPUTEST_HAVE_EXCEPTIONS throw CppUTestFailedException(); #else TestTerminatorWithoutExceptions().exitCurrentTest(); @@ -642,6 +774,51 @@ TestTerminatorWithoutExceptions::~TestTerminatorWithoutExceptions() { } +void CrashingTestTerminator::exitCurrentTest() const +{ + UtestShell::crash(); + NormalTestTerminator::exitCurrentTest(); +} + +CrashingTestTerminator::~CrashingTestTerminator() +{ +} + +void CrashingTestTerminatorWithoutExceptions::exitCurrentTest() const +{ + UtestShell::crash(); + TestTerminatorWithoutExceptions::exitCurrentTest(); +} + +CrashingTestTerminatorWithoutExceptions::~CrashingTestTerminatorWithoutExceptions() +{ +} + +//////////////////// ExecFunction +// +ExecFunction::ExecFunction() +{ +} + +ExecFunction::~ExecFunction() +{ +} + +ExecFunctionWithoutParameters::ExecFunctionWithoutParameters(void(*testFunction)()) + : testFunction_(testFunction) +{ +} + +ExecFunctionWithoutParameters::~ExecFunctionWithoutParameters() +{ +} + +void ExecFunctionWithoutParameters::exec() +{ + if (testFunction_) + testFunction_(); +} + //////////////////// ExecFunctionTest ExecFunctionTest::ExecFunctionTest(ExecFunctionTestShell* shell) @@ -651,7 +828,7 @@ ExecFunctionTest::ExecFunctionTest(ExecFunctionTestShell* shell) void ExecFunctionTest::testBody() { - if (shell_->testFunction_) shell_->testFunction_(); + if (shell_->testFunction_) shell_->testFunction_->exec(); } void ExecFunctionTest::setup() @@ -669,7 +846,7 @@ IgnoredUtestShell::IgnoredUtestShell(): runIgnored_(false) { } -IgnoredUtestShell::IgnoredUtestShell(const char* groupName, const char* testName, const char* fileName, int lineNumber) : +IgnoredUtestShell::IgnoredUtestShell(const char* groupName, const char* testName, const char* fileName, size_t lineNumber) : UtestShell(groupName, testName, fileName, lineNumber), runIgnored_(false) { } @@ -708,10 +885,89 @@ void IgnoredUtestShell::setRunIgnored() runIgnored_ = true; } +//////////////////// UtestShellPointerArray + +UtestShellPointerArray::UtestShellPointerArray(UtestShell* firstTest) + : arrayOfTests_(NULLPTR), count_(0) +{ + count_ = (firstTest) ? firstTest->countTests() : 0; + if (count_ == 0) return; + + arrayOfTests_ = new UtestShell*[count_]; + + UtestShell*currentTest = firstTest; + for (size_t i = 0; i < count_; i++) + { + arrayOfTests_[i] = currentTest; + currentTest = currentTest->getNext(); + } +} + +UtestShellPointerArray::~UtestShellPointerArray() +{ + delete [] arrayOfTests_; +} + +void UtestShellPointerArray::swap(size_t index1, size_t index2) +{ + UtestShell* e2 = arrayOfTests_[index2]; + UtestShell* e1 = arrayOfTests_[index1]; + arrayOfTests_[index1] = e2; + arrayOfTests_[index2] = e1; +} + +void UtestShellPointerArray::shuffle(size_t seed) +{ + if (count_ == 0) return; + + PlatformSpecificSrand((unsigned int) seed); + + for (size_t i = count_ - 1; i >= 1; --i) + { + if (count_ == 0) return; + + const size_t j = ((size_t)PlatformSpecificRand()) % (i + 1); // distribution biased by modulo, but good enough for shuffling + swap(i, j); + } + relinkTestsInOrder(); +} + +void UtestShellPointerArray::reverse() +{ + if (count_ == 0) return; + + size_t halfCount = count_ / 2; + for (size_t i = 0; i < halfCount; i++) + { + size_t j = count_ - i - 1; + swap(i, j); + } + relinkTestsInOrder(); +} + +void UtestShellPointerArray::relinkTestsInOrder() +{ + UtestShell *tests = NULLPTR; + for (size_t i = 0; i < count_; i++) + tests = arrayOfTests_[count_ - i - 1]->addTest(tests); +} + +UtestShell* UtestShellPointerArray::getFirstTest() const +{ + return get(0); +} + +UtestShell* UtestShellPointerArray::get(size_t index) const +{ + if (index >= count_) return NULLPTR; + return arrayOfTests_[index]; +} + + ////////////// TestInstaller //////////// -TestInstaller::TestInstaller(UtestShell& shell, const char* groupName, const char* testName, const char* fileName, int lineNumber) +TestInstaller::TestInstaller(UtestShell& shell, const char* groupName, const char* testName, const char* fileName, size_t lineNumber) { shell.setGroupName(groupName); shell.setTestName(testName); diff --git a/src/CppUTestExt/CMakeLists.txt b/src/CppUTestExt/CMakeLists.txt index 749be7a9e..ec0f27586 100644 --- a/src/CppUTestExt/CMakeLists.txt +++ b/src/CppUTestExt/CMakeLists.txt @@ -1,48 +1,62 @@ -set(CppUTestExt_src - CodeMemoryReportFormatter.cpp - IEEE754ExceptionsPlugin.cpp - MemoryReporterPlugin.cpp - MockFailure.cpp - MockSupportPlugin.cpp - MockActualCall.cpp - MockSupport_c.cpp - MemoryReportAllocator.cpp - MockExpectedCall.cpp - MockNamedValue.cpp - OrderedTest.cpp - MemoryReportFormatter.cpp - MockExpectedCallsList.cpp - MockSupport.cpp +add_library(CppUTestExt STATIC + CodeMemoryReportFormatter.cpp + GTest.cpp + IEEE754ExceptionsPlugin.cpp + MemoryReporterPlugin.cpp + MockFailure.cpp + MockSupportPlugin.cpp + MockActualCall.cpp + MockSupport_c.cpp + MemoryReportAllocator.cpp + MockExpectedCall.cpp + MockNamedValue.cpp + OrderedTest.cpp + MemoryReportFormatter.cpp + MockExpectedCallsList.cpp + MockSupport.cpp + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/CodeMemoryReportFormatter.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/IEEE754ExceptionsPlugin.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MemoryReportAllocator.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MockExpectedCall.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MockCheckedExpectedCall.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MockExpectedCallsList.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MockSupportPlugin.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MemoryReportFormatter.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MockFailure.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MockSupport.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MockSupport_c.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/GMock.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/GTest.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/GTestSupport.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MemoryReporterPlugin.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/OrderedTest.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/GTestConvertor.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MockActualCall.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MockCheckedActualCall.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MockNamedValue.h + ${PROJECT_SOURCE_DIR}/include/CppUTestExt/MockSupport.h ) -set(CppUTestExt_headers - ${CppUTestRootDirectory}/include/CppUTestExt/CodeMemoryReportFormatter.h - ${CppUTestRootDirectory}/include/CppUTestExt/IEEE754ExceptionsPlugin.h - ${CppUTestRootDirectory}/include/CppUTestExt/MemoryReportAllocator.h - ${CppUTestRootDirectory}/include/CppUTestExt/MockExpectedCall.h - ${CppUTestRootDirectory}/include/CppUTestExt/MockCheckedExpectedCall.h - ${CppUTestRootDirectory}/include/CppUTestExt/MockExpectedCallsList.h - ${CppUTestRootDirectory}/include/CppUTestExt/MockSupportPlugin.h - ${CppUTestRootDirectory}/include/CppUTestExt/MemoryReportFormatter.h - ${CppUTestRootDirectory}/include/CppUTestExt/MockFailure.h - ${CppUTestRootDirectory}/include/CppUTestExt/MockSupport.h - ${CppUTestRootDirectory}/include/CppUTestExt/MockSupport_c.h - ${CppUTestRootDirectory}/include/CppUTestExt/GMock.h - ${CppUTestRootDirectory}/include/CppUTestExt/GTest.h - ${CppUTestRootDirectory}/include/CppUTestExt/MemoryReporterPlugin.h - ${CppUTestRootDirectory}/include/CppUTestExt/OrderedTest.h - ${CppUTestRootDirectory}/include/CppUTestExt/GTestConvertor.h - ${CppUTestRootDirectory}/include/CppUTestExt/MockActualCall.h - ${CppUTestRootDirectory}/include/CppUTestExt/MockCheckedActualCall.h - ${CppUTestRootDirectory}/include/CppUTestExt/MockNamedValue.h - ${CppUTestRootDirectory}/include/CppUTestExt/MockSupport.h +target_link_libraries(CppUTestExt PUBLIC CppUTest) + +#[[Arrange for the include directory to be added to the include paths of any CMake target depending on CppUTestExt.]] +target_include_directories(CppUTestExt + PUBLIC + $ + $ ) -add_library(CppUTestExt STATIC ${CppUTestExt_src} ${CppUTestExt_headers}) -target_link_libraries(CppUTestExt ${CPPUNIT_EXTERNAL_LIBRARIES}) -install(FILES ${CppUTestExt_headers} DESTINATION include/CppUTestExt) -install(TARGETS CppUTestExt - EXPORT CppUTestTargets - RUNTIME DESTINATION bin - LIBRARY DESTINATION lib - ARCHIVE DESTINATION lib) +add_library(CppUTest::CppUTestExt ALIAS CppUTestExt) + +if(PROJECT_IS_TOP_LEVEL) + install( + TARGETS CppUTestExt + EXPORT CppUTestTargets + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + ) + install( + DIRECTORY "${PROJECT_SOURCE_DIR}/include/CppUTestExt" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" + ) +endif() diff --git a/src/CppUTestExt/CodeMemoryReportFormatter.cpp b/src/CppUTestExt/CodeMemoryReportFormatter.cpp index ff210374c..57c1e4f96 100644 --- a/src/CppUTestExt/CodeMemoryReportFormatter.cpp +++ b/src/CppUTestExt/CodeMemoryReportFormatter.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,7 +34,7 @@ #define MAX_VARIABLE_NAME_LINE_PART 10 #define MAX_VARIABLE_NAME_FILE_PART 53 #define MAX_VARIABLE_NAME_SEPERATOR_PART 1 -#define MAX_VARIABLE_NAME_LENGTH MAX_VARIABLE_NAME_FILE_PART + MAX_VARIABLE_NAME_SEPERATOR_PART + MAX_VARIABLE_NAME_LINE_PART +#define MAX_VARIABLE_NAME_LENGTH (MAX_VARIABLE_NAME_FILE_PART + MAX_VARIABLE_NAME_SEPERATOR_PART + MAX_VARIABLE_NAME_LINE_PART) struct CodeReportingAllocationNode { @@ -44,7 +44,7 @@ struct CodeReportingAllocationNode }; CodeMemoryReportFormatter::CodeMemoryReportFormatter(TestMemoryAllocator* internalAllocator) - : codeReportingList_(NULL), internalAllocator_(internalAllocator) + : codeReportingList_(NULLPTR), internalAllocator_(internalAllocator) { } @@ -58,7 +58,7 @@ void CodeMemoryReportFormatter::clearReporting() while (codeReportingList_) { CodeReportingAllocationNode* oldNode = codeReportingList_; codeReportingList_ = codeReportingList_->next_; - internalAllocator_->free_memory((char*) oldNode, __FILE__, __LINE__); + internalAllocator_->free_memory((char*) oldNode, 0, __FILE__, __LINE__); } } @@ -90,13 +90,13 @@ static SimpleString extractFileNameFromPath(const char* file) return fileNameOnly; } -SimpleString CodeMemoryReportFormatter::createVariableNameFromFileLineInfo(const char *file, int line) +SimpleString CodeMemoryReportFormatter::createVariableNameFromFileLineInfo(const char *file, size_t line) { SimpleString fileNameOnly = extractFileNameFromPath(file); fileNameOnly.replace(".", "_"); for (int i = 1; i < 100; i++) { - SimpleString variableName = StringFromFormat("%s_%d_%d", fileNameOnly.asCharString(), line, i); + SimpleString variableName = StringFromFormat("%s_%d_%d", fileNameOnly.asCharString(), (int) line, i); if (!variableExists(variableName)) return variableName; } @@ -127,19 +127,19 @@ SimpleString CodeMemoryReportFormatter::getAllocationString(TestMemoryAllocator* return StringFromFormat("void* %s = malloc(%lu);", variableName.asCharString(), (unsigned long) size); } -SimpleString CodeMemoryReportFormatter::getDeallocationString(TestMemoryAllocator* allocator, const SimpleString& variableName, const char* file, int line) +SimpleString CodeMemoryReportFormatter::getDeallocationString(TestMemoryAllocator* allocator, const SimpleString& variableName, const char* file, size_t line) { if (isNewAllocator(allocator)) - return StringFromFormat("delete [] %s; /* using %s at %s:%d */", variableName.asCharString(), allocator->free_name(), file, line); + return StringFromFormat("delete [] %s; /* using %s at %s:%d */", variableName.asCharString(), allocator->free_name(), file, (int) line); else - return StringFromFormat("free(%s); /* at %s:%d */", variableName.asCharString(), file, line); + return StringFromFormat("free(%s); /* at %s:%d */", variableName.asCharString(), file, (int) line); } void CodeMemoryReportFormatter::report_test_start(TestResult* result, UtestShell& test) { clearReporting(); result->print(StringFromFormat("*/\nTEST(%s_memoryReport, %s)\n{ /* at %s:%d */\n", - test.getGroup().asCharString(), test.getName().asCharString(), test.getFile().asCharString(), test.getLineNumber()).asCharString()); + test.getGroup().asCharString(), test.getName().asCharString(), test.getFile().asCharString(), (int) test.getLineNumber()).asCharString()); } void CodeMemoryReportFormatter::report_test_end(TestResult* result, UtestShell&) @@ -153,19 +153,19 @@ void CodeMemoryReportFormatter::report_testgroup_start(TestResult* result, Utest test.getGroup().asCharString()).asCharString()); } -void CodeMemoryReportFormatter::report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, int line) +void CodeMemoryReportFormatter::report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, size_t line) { SimpleString variableName = createVariableNameFromFileLineInfo(file, line); result->print(StringFromFormat("\t%s\n", getAllocationString(allocator, variableName, size).asCharString()).asCharString()); addNodeToList(variableName.asCharString(), memory, codeReportingList_); } -void CodeMemoryReportFormatter::report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, int line) +void CodeMemoryReportFormatter::report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, size_t line) { SimpleString variableName; CodeReportingAllocationNode* node = findNode(memory); - if (memory == NULL) variableName = "NULL"; + if (memory == NULLPTR) variableName = "NULL"; else variableName = node->variableName_; result->print(StringFromFormat("\t%s\n", getDeallocationString(allocator, variableName, file, line).asCharString()).asCharString()); diff --git a/src/CppUTestExt/GTest.cpp b/src/CppUTestExt/GTest.cpp new file mode 100644 index 000000000..919866c39 --- /dev/null +++ b/src/CppUTestExt/GTest.cpp @@ -0,0 +1,9 @@ + +#include "CppUTest/TestHarness.h" +#include "CppUTestExt/GTestSupport.h" + +void CppuTestGTestIgnoreLeaksInTest() +{ + IGNORE_ALL_LEAKS_IN_TEST(); +} + diff --git a/src/CppUTestExt/IEEE754ExceptionsPlugin.cpp b/src/CppUTestExt/IEEE754ExceptionsPlugin.cpp index 9f0ec9b38..5b84a4862 100644 --- a/src/CppUTestExt/IEEE754ExceptionsPlugin.cpp +++ b/src/CppUTestExt/IEEE754ExceptionsPlugin.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -28,7 +28,7 @@ #include "CppUTest/TestHarness.h" #include "CppUTestExt/IEEE754ExceptionsPlugin.h" -#ifdef CPPUTEST_HAVE_FENV +#if CPPUTEST_HAVE_FENV extern "C" { #include @@ -100,4 +100,54 @@ void IEEE754ExceptionsPlugin::ieee754Check(UtestShell& test, TestResult& result, } } +#else + + +bool IEEE754ExceptionsPlugin::inexactDisabled_ = true; + +IEEE754ExceptionsPlugin::IEEE754ExceptionsPlugin(const SimpleString& name) + : TestPlugin(name) +{ +} + +void IEEE754ExceptionsPlugin::preTestAction(UtestShell&, TestResult&) +{ +} + +void IEEE754ExceptionsPlugin::postTestAction(UtestShell&, TestResult&) +{ +} + +void IEEE754ExceptionsPlugin::disableInexact() +{ +} + +void IEEE754ExceptionsPlugin::enableInexact() +{ +} + +bool IEEE754ExceptionsPlugin::checkIeee754OverflowExceptionFlag() +{ + return false; +} + +bool IEEE754ExceptionsPlugin::checkIeee754UnderflowExceptionFlag() +{ + return false; +} + +bool IEEE754ExceptionsPlugin::checkIeee754InexactExceptionFlag() +{ + return false; +} + +bool IEEE754ExceptionsPlugin::checkIeee754DivByZeroExceptionFlag() +{ + return false; +} + +void IEEE754ExceptionsPlugin::ieee754Check(UtestShell&, TestResult&, int, const char*) +{ +} + #endif diff --git a/src/CppUTestExt/MemoryReportAllocator.cpp b/src/CppUTestExt/MemoryReportAllocator.cpp index 30c27c1cf..f51b932ab 100644 --- a/src/CppUTestExt/MemoryReportAllocator.cpp +++ b/src/CppUTestExt/MemoryReportAllocator.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -29,7 +29,7 @@ #include "CppUTestExt/MemoryReportAllocator.h" #include "CppUTestExt/MemoryReportFormatter.h" -MemoryReportAllocator::MemoryReportAllocator() : result_(NULL), realAllocator_(NULL), formatter_(NULL) +MemoryReportAllocator::MemoryReportAllocator() : result_(NULLPTR), realAllocator_(NULLPTR), formatter_(NULLPTR) { } @@ -37,17 +37,17 @@ MemoryReportAllocator::~MemoryReportAllocator() { } -const char* MemoryReportAllocator::name() +const char* MemoryReportAllocator::name() const { - return realAllocator_->name(); + return "MemoryReporterAllocator"; } -const char* MemoryReportAllocator::alloc_name() +const char* MemoryReportAllocator::alloc_name() const { return realAllocator_->alloc_name(); } -const char* MemoryReportAllocator::free_name() +const char* MemoryReportAllocator::free_name() const { return realAllocator_->free_name(); } @@ -62,6 +62,11 @@ TestMemoryAllocator* MemoryReportAllocator::getRealAllocator() return realAllocator_; } +TestMemoryAllocator* MemoryReportAllocator::actualAllocator() +{ + return realAllocator_->actualAllocator(); +} + void MemoryReportAllocator::setTestResult(TestResult* result) { result_ = result; @@ -72,7 +77,7 @@ void MemoryReportAllocator::setFormatter(MemoryReportFormatter* formatter) formatter_ = formatter; } -char* MemoryReportAllocator::alloc_memory(size_t size, const char* file, int line) +char* MemoryReportAllocator::alloc_memory(size_t size, const char* file, size_t line) { char* memory = realAllocator_->alloc_memory(size, file, line); if (result_ && formatter_) @@ -80,9 +85,9 @@ char* MemoryReportAllocator::alloc_memory(size_t size, const char* file, int lin return memory; } -void MemoryReportAllocator::free_memory(char* memory, const char* file, int line) +void MemoryReportAllocator::free_memory(char* memory, size_t size, const char* file, size_t line) { - realAllocator_->free_memory(memory, file, line); + realAllocator_->free_memory(memory, size, file, line); if (result_ && formatter_) formatter_->report_free_memory(result_, this, memory, file, line); } diff --git a/src/CppUTestExt/MemoryReportFormatter.cpp b/src/CppUTestExt/MemoryReportFormatter.cpp index ec912e76a..13833e5d6 100644 --- a/src/CppUTestExt/MemoryReportFormatter.cpp +++ b/src/CppUTestExt/MemoryReportFormatter.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -47,14 +47,14 @@ void NormalMemoryReportFormatter::report_test_end(TestResult* result, UtestShell result->print(StringFromFormat("ENDTEST(%s, %s)\n", test.getGroup().asCharString(), test.getName().asCharString()).asCharString()); } -void NormalMemoryReportFormatter::report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, int line) +void NormalMemoryReportFormatter::report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, size_t line) { - result->print(StringFromFormat("\tAllocation using %s of size: %lu pointer: %p at %s:%d\n", allocator->alloc_name(), (unsigned long) size, (void*) memory, file, line).asCharString()); + result->print(StringFromFormat("\tAllocation using %s of size: %lu pointer: %p at %s:%d\n", allocator->alloc_name(), (unsigned long) size, (void*) memory, file, (int) line).asCharString()); } -void NormalMemoryReportFormatter::report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, int line) +void NormalMemoryReportFormatter::report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, size_t line) { - result->print(StringFromFormat("\tDeallocation using %s of pointer: %p at %s:%d\n", allocator->free_name(), (void*) memory, file, line).asCharString()); + result->print(StringFromFormat("\tDeallocation using %s of pointer: %p at %s:%d\n", allocator->free_name(), (void*) memory, file, (int) line).asCharString()); } void NormalMemoryReportFormatter::report_testgroup_start(TestResult* result, UtestShell& test) diff --git a/src/CppUTestExt/MemoryReporterPlugin.cpp b/src/CppUTestExt/MemoryReporterPlugin.cpp index e4206e004..8b81f5dc8 100644 --- a/src/CppUTestExt/MemoryReporterPlugin.cpp +++ b/src/CppUTestExt/MemoryReporterPlugin.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -31,7 +31,7 @@ #include "CppUTestExt/CodeMemoryReportFormatter.h" MemoryReporterPlugin::MemoryReporterPlugin() - : TestPlugin("MemoryReporterPlugin"), formatter_(NULL) + : TestPlugin("MemoryReporterPlugin"), formatter_(NULLPTR) { } @@ -41,7 +41,7 @@ MemoryReporterPlugin::~MemoryReporterPlugin() destroyMemoryFormatter(formatter_); } -bool MemoryReporterPlugin::parseArguments(int /* ac */, const char** av, int index) +bool MemoryReporterPlugin::parseArguments(int /* ac */, const char *const *av, int index) { SimpleString argument (av[index]); if (argument.contains("-pmemoryreport=")) { @@ -62,7 +62,7 @@ MemoryReportFormatter* MemoryReporterPlugin::createMemoryFormatter(const SimpleS else if (type == "code") { return new CodeMemoryReportFormatter(defaultMallocAllocator()); } - return NULL; + return NULLPTR; } void MemoryReporterPlugin::destroyMemoryFormatter(MemoryReportFormatter* formatter) @@ -95,6 +95,20 @@ void MemoryReporterPlugin::removeGlobalMemoryReportAllocators() setCurrentMallocAllocator(mallocAllocator.getRealAllocator()); } +MemoryReportAllocator* MemoryReporterPlugin::getMallocAllocator() +{ + return &mallocAllocator; +} + +MemoryReportAllocator* MemoryReporterPlugin::getNewAllocator() +{ + return &newAllocator; +} + +MemoryReportAllocator* MemoryReporterPlugin::getNewArrayAllocator() +{ + return &newArrayAllocator; +} void MemoryReporterPlugin::initializeAllocator(MemoryReportAllocator* allocator, TestResult & result) { @@ -104,7 +118,7 @@ void MemoryReporterPlugin::initializeAllocator(MemoryReportAllocator* allocator, void MemoryReporterPlugin::preTestAction(UtestShell& test, TestResult& result) { - if (formatter_ == NULL) return; + if (formatter_ == NULLPTR) return; initializeAllocator(&mallocAllocator, result); initializeAllocator(&newAllocator, result); @@ -122,11 +136,11 @@ void MemoryReporterPlugin::preTestAction(UtestShell& test, TestResult& result) void MemoryReporterPlugin::postTestAction(UtestShell& test, TestResult& result) { - if (formatter_ == NULL) return; + if (formatter_ == NULLPTR) return; removeGlobalMemoryReportAllocators(); formatter_->report_test_end(&result, test); - if (test.getNext() == NULL || test.getNext()->getGroup() != currentTestGroup_) + if (test.getNext() == NULLPTR || test.getNext()->getGroup() != currentTestGroup_) formatter_->report_testgroup_end(&result, test); } diff --git a/src/CppUTestExt/MockActualCall.cpp b/src/CppUTestExt/MockActualCall.cpp index 0cfef9a2c..319e20a60 100644 --- a/src/CppUTestExt/MockActualCall.cpp +++ b/src/CppUTestExt/MockActualCall.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -49,10 +49,11 @@ SimpleString MockCheckedActualCall::getName() const return functionName_; } -MockCheckedActualCall::MockCheckedActualCall(int callOrder, MockFailureReporter* reporter, const MockExpectedCallsList& allExpectations) - : callOrder_(callOrder), reporter_(reporter), state_(CALL_SUCCEED), fulfilledExpectation_(NULL), allExpectations_(allExpectations), outputParameterExpectations_(NULL) +MockCheckedActualCall::MockCheckedActualCall(unsigned int callOrder, MockFailureReporter* reporter, const MockExpectedCallsList& allExpectations) + : callOrder_(callOrder), reporter_(reporter), state_(CALL_SUCCEED), expectationsChecked_(false), matchingExpectation_(NULLPTR), + allExpectations_(allExpectations), outputParameterExpectations_(NULLPTR) { - unfulfilledExpectations_.addUnfulfilledExpectations(allExpectations); + potentiallyMatchingExpectations_.addPotentiallyMatchingExpectations(allExpectations); } MockCheckedActualCall::~MockCheckedActualCall() @@ -78,7 +79,7 @@ void MockCheckedActualCall::failTest(const MockFailure& failure) } } -void MockCheckedActualCall::finalizeOutputParameters(MockCheckedExpectedCall* expectedCall) +void MockCheckedActualCall::copyOutputParameters(MockCheckedExpectedCall* expectedCall) { for (MockOutputParametersListNode* p = outputParameterExpectations_; p; p = p->next_) { @@ -86,7 +87,7 @@ void MockCheckedActualCall::finalizeOutputParameters(MockCheckedExpectedCall* ex MockNamedValueCopier* copier = outputParameter.getCopier(); if (copier) { - copier->copy(p->ptr_, outputParameter.getObjectPointer()); + copier->copy(p->ptr_, outputParameter.getConstObjectPointer()); } else if ((outputParameter.getType() == "const void*") && (p->type_ == "void*")) { @@ -103,15 +104,19 @@ void MockCheckedActualCall::finalizeOutputParameters(MockCheckedExpectedCall* ex } } -void MockCheckedActualCall::finalizeCallWhenFulfilled() +void MockCheckedActualCall::completeCallWhenMatchIsFound() { - if (unfulfilledExpectations_.hasFulfilledExpectationsWithoutIgnoredParameters()) { - finalizeOutputParameters(unfulfilledExpectations_.getOneFulfilledExpectationWithIgnoredParameters()); - } + // Expectations that don't ignore parameters have higher fulfillment preference than those that ignore parameters - if (unfulfilledExpectations_.hasFulfilledExpectations()) { - fulfilledExpectation_ = unfulfilledExpectations_.removeOneFulfilledExpectation(); + matchingExpectation_ = potentiallyMatchingExpectations_.removeFirstFinalizedMatchingExpectation(); + if (matchingExpectation_) { + copyOutputParameters(matchingExpectation_); callHasSucceeded(); + } else { + MockCheckedExpectedCall* matchingExpectationWithIgnoredParameters = potentiallyMatchingExpectations_.getFirstMatchingExpectation(); + if (matchingExpectationWithIgnoredParameters) { + copyOutputParameters(matchingExpectationWithIgnoredParameters); + } } } @@ -120,37 +125,34 @@ void MockCheckedActualCall::callHasSucceeded() setState(CALL_SUCCEED); } -void MockCheckedActualCall::callIsInProgress() +void MockCheckedActualCall::discardCurrentlyMatchingExpectations() { - setState(CALL_IN_PROGRESS); - if (fulfilledExpectation_) + if (matchingExpectation_) { - fulfilledExpectation_->resetExpectation(); - fulfilledExpectation_ = NULL; + matchingExpectation_->resetActualCallMatchingState(); + matchingExpectation_ = NULLPTR; } - unfulfilledExpectations_.onlyKeepUnfulfilledExpectations(); + potentiallyMatchingExpectations_.onlyKeepUnmatchingExpectations(); } MockActualCall& MockCheckedActualCall::withName(const SimpleString& name) { setName(name); - callIsInProgress(); + setState(CALL_IN_PROGRESS); - unfulfilledExpectations_.onlyKeepExpectationsRelatedTo(name); - if (unfulfilledExpectations_.isEmpty()) { + potentiallyMatchingExpectations_.onlyKeepExpectationsRelatedTo(name); + if (potentiallyMatchingExpectations_.isEmpty()) { MockUnexpectedCallHappenedFailure failure(getTest(), name, allExpectations_); failTest(failure); return *this; } - unfulfilledExpectations_.callWasMade(callOrder_); - - finalizeCallWhenFulfilled(); + completeCallWhenMatchIsFound(); return *this; } -MockActualCall& MockCheckedActualCall::withCallOrder(int) +MockActualCall& MockCheckedActualCall::withCallOrder(unsigned int) { return *this; } @@ -162,18 +164,19 @@ void MockCheckedActualCall::checkInputParameter(const MockNamedValue& actualPara return; } - callIsInProgress(); + setState(CALL_IN_PROGRESS); + discardCurrentlyMatchingExpectations(); - unfulfilledExpectations_.onlyKeepExpectationsWithInputParameter(actualParameter); + potentiallyMatchingExpectations_.onlyKeepExpectationsWithInputParameter(actualParameter); - if (unfulfilledExpectations_.isEmpty()) { + if (potentiallyMatchingExpectations_.isEmpty()) { MockUnexpectedInputParameterFailure failure(getTest(), getName(), actualParameter, allExpectations_); failTest(failure); return; } - unfulfilledExpectations_.parameterWasPassed(actualParameter.getName()); - finalizeCallWhenFulfilled(); + potentiallyMatchingExpectations_.parameterWasPassed(actualParameter.getName()); + completeCallWhenMatchIsFound(); } void MockCheckedActualCall::checkOutputParameter(const MockNamedValue& outputParameter) @@ -183,18 +186,19 @@ void MockCheckedActualCall::checkOutputParameter(const MockNamedValue& outputPar return; } - callIsInProgress(); + setState(CALL_IN_PROGRESS); + discardCurrentlyMatchingExpectations(); - unfulfilledExpectations_.onlyKeepExpectationsWithOutputParameter(outputParameter); + potentiallyMatchingExpectations_.onlyKeepExpectationsWithOutputParameter(outputParameter); - if (unfulfilledExpectations_.isEmpty()) { + if (potentiallyMatchingExpectations_.isEmpty()) { MockUnexpectedOutputParameterFailure failure(getTest(), getName(), outputParameter, allExpectations_); failTest(failure); return; } - unfulfilledExpectations_.outputParameterWasPassed(outputParameter.getName()); - finalizeCallWhenFulfilled(); + potentiallyMatchingExpectations_.outputParameterWasPassed(outputParameter.getName()); + completeCallWhenMatchIsFound(); } MockActualCall& MockCheckedActualCall::withBoolParameter(const SimpleString& name, bool value) @@ -237,6 +241,40 @@ MockActualCall& MockCheckedActualCall::withLongIntParameter(const SimpleString& return *this; } +#if CPPUTEST_USE_LONG_LONG + +MockActualCall& MockCheckedActualCall::withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value) +{ + MockNamedValue actualParameter(name); + actualParameter.setValue(value); + checkInputParameter(actualParameter); + return *this; +} + +MockActualCall& MockCheckedActualCall::withLongLongIntParameter(const SimpleString& name, cpputest_longlong value) +{ + MockNamedValue actualParameter(name); + actualParameter.setValue(value); + checkInputParameter(actualParameter); + return *this; +} + +#else + +MockActualCall& MockCheckedActualCall::withUnsignedLongLongIntParameter(const SimpleString&, cpputest_ulonglong) +{ + FAIL("Unsigned Long Long type is not supported"); + return *this; +} + +MockActualCall& MockCheckedActualCall::withLongLongIntParameter(const SimpleString&, cpputest_longlong) +{ + FAIL("Long Long type is not supported"); + return *this; +} + +#endif + MockActualCall& MockCheckedActualCall::withDoubleParameter(const SimpleString& name, double value) { MockNamedValue actualParameter(name); @@ -288,9 +326,9 @@ MockActualCall& MockCheckedActualCall::withMemoryBufferParameter(const SimpleStr MockActualCall& MockCheckedActualCall::withParameterOfType(const SimpleString& type, const SimpleString& name, const void* value) { MockNamedValue actualParameter(name); - actualParameter.setObjectPointer(type, value); + actualParameter.setConstObjectPointer(type, value); - if (actualParameter.getComparator() == NULL) { + if (actualParameter.getComparator() == NULLPTR) { MockNoWayToCompareCustomTypeFailure failure(getTest(), type); failTest(failure); return *this; @@ -315,7 +353,7 @@ MockActualCall& MockCheckedActualCall::withOutputParameterOfType(const SimpleStr addOutputParameter(name, type, output); MockNamedValue outputParameter(name); - outputParameter.setObjectPointer(type, output); + outputParameter.setConstObjectPointer(type, output); checkOutputParameter(outputParameter); return *this; @@ -333,24 +371,34 @@ bool MockCheckedActualCall::hasFailed() const void MockCheckedActualCall::checkExpectations() { - if (state_ != CALL_IN_PROGRESS) - { - unfulfilledExpectations_.resetExpectations(); + if(expectationsChecked_) { + return; + } + + expectationsChecked_ = true; + + if (state_ != CALL_IN_PROGRESS) { + if(state_ == CALL_SUCCEED) { + matchingExpectation_->callWasMade(callOrder_); + } + potentiallyMatchingExpectations_.resetActualCallMatchingState(); return; } - if (! unfulfilledExpectations_.hasUnfulfilledExpectations()) - FAIL("Actual call is in progress. Checking expectations. But no unfulfilled expectations. Cannot happen.") // LCOV_EXCL_LINE + if (potentiallyMatchingExpectations_.hasFinalizedMatchingExpectations()) + FAIL("Actual call is in progress, but there are finalized matching expectations when checking expectations. This cannot happen."); // LCOV_EXCL_LINE - fulfilledExpectation_ = unfulfilledExpectations_.removeOneFulfilledExpectationWithIgnoredParameters(); - if (fulfilledExpectation_) { + matchingExpectation_ = potentiallyMatchingExpectations_.removeFirstMatchingExpectation(); + if (matchingExpectation_) { + matchingExpectation_->finalizeActualCallMatch(); callHasSucceeded(); - unfulfilledExpectations_.resetExpectations(); + matchingExpectation_->callWasMade(callOrder_); + potentiallyMatchingExpectations_.resetActualCallMatchingState(); return; } - if (unfulfilledExpectations_.hasUnfulfilledExpectationsBecauseOfMissingParameters()) { - MockExpectedParameterDidntHappenFailure failure(getTest(), getName(), allExpectations_); + if (potentiallyMatchingExpectations_.hasUnmatchingExpectationsBecauseOfMissingParameters()) { + MockExpectedParameterDidntHappenFailure failure(getTest(), getName(), allExpectations_, potentiallyMatchingExpectations_); failTest(failure); } else { @@ -367,8 +415,8 @@ void MockCheckedActualCall::setState(ActualCallState state) MockNamedValue MockCheckedActualCall::returnValue() { checkExpectations(); - if (fulfilledExpectation_) - return fulfilledExpectation_->returnValue(); + if (matchingExpectation_) + return matchingExpectation_->returnValue(); return MockNamedValue("no return value"); } @@ -424,6 +472,64 @@ long int MockCheckedActualCall::returnLongIntValueOrDefault(long int default_val return returnLongIntValue(); } +#if CPPUTEST_USE_LONG_LONG + +cpputest_ulonglong MockCheckedActualCall::returnUnsignedLongLongIntValue() +{ + return returnValue().getUnsignedLongLongIntValue(); +} + +cpputest_ulonglong MockCheckedActualCall::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong default_value) +{ + if (!hasReturnValue()) { + return default_value; + } + return returnUnsignedLongLongIntValue(); +} + +cpputest_longlong MockCheckedActualCall::returnLongLongIntValue() +{ + return returnValue().getLongLongIntValue(); +} + +cpputest_longlong MockCheckedActualCall::returnLongLongIntValueOrDefault(cpputest_longlong default_value) +{ + if (!hasReturnValue()) { + return default_value; + } + return returnLongLongIntValue(); +} + +#else + +cpputest_ulonglong MockCheckedActualCall::returnUnsignedLongLongIntValue() +{ + FAIL("Unsigned Long Long type is not supported"); + cpputest_ulonglong ret = {}; + return ret; +} + +cpputest_ulonglong MockCheckedActualCall::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong default_value) +{ + FAIL("Unsigned Long Long type is not supported"); + return default_value; +} + +cpputest_longlong MockCheckedActualCall::returnLongLongIntValue() +{ + FAIL("Long Long type is not supported"); + cpputest_longlong ret = {}; + return ret; +} + +cpputest_longlong MockCheckedActualCall::returnLongLongIntValueOrDefault(cpputest_longlong default_value) +{ + FAIL("Long Long type is not supported"); + return default_value; +} + +#endif + double MockCheckedActualCall::returnDoubleValue() { return returnValue().getDoubleValue(); @@ -509,19 +615,27 @@ bool MockCheckedActualCall::hasReturnValue() MockActualCall& MockCheckedActualCall::onObject(const void* objectPtr) { - callIsInProgress(); + if(hasFailed()) { + return *this; + } - unfulfilledExpectations_.onlyKeepExpectationsOnObject(objectPtr); + // Currently matching expectations are not discarded because the passed object + // is ignored if not specifically set in the expectation - if (unfulfilledExpectations_.isEmpty()) { + potentiallyMatchingExpectations_.onlyKeepExpectationsOnObject(objectPtr); + + if ((!matchingExpectation_) && potentiallyMatchingExpectations_.isEmpty()) { MockUnexpectedObjectFailure failure(getTest(), getName(), objectPtr, allExpectations_); failTest(failure); return *this; } - unfulfilledExpectations_.wasPassedToObject(); + potentiallyMatchingExpectations_.wasPassedToObject(); + + if (!matchingExpectation_) { + completeCallWhenMatchIsFound(); + } - finalizeCallWhenFulfilled(); return *this; } @@ -529,7 +643,7 @@ void MockCheckedActualCall::addOutputParameter(const SimpleString& name, const S { MockOutputParametersListNode* newNode = new MockOutputParametersListNode(name, type, ptr); - if (outputParameterExpectations_ == NULL) + if (outputParameterExpectations_ == NULLPTR) outputParameterExpectations_ = newNode; else { MockOutputParametersListNode* lastNode = outputParameterExpectations_; @@ -541,7 +655,7 @@ void MockCheckedActualCall::addOutputParameter(const SimpleString& name, const S void MockCheckedActualCall::cleanUpOutputParameterList() { MockOutputParametersListNode* current = outputParameterExpectations_; - MockOutputParametersListNode* toBeDeleted = NULL; + MockOutputParametersListNode* toBeDeleted = NULLPTR; while (current) { toBeDeleted = current; @@ -566,7 +680,7 @@ MockActualCall& MockActualCallTrace::withName(const SimpleString& name) return *this; } -MockActualCall& MockActualCallTrace::withCallOrder(int callOrder) +MockActualCall& MockActualCallTrace::withCallOrder(unsigned int callOrder) { traceBuffer_ += " withCallOrder:"; traceBuffer_ += StringFrom(callOrder); @@ -590,31 +704,63 @@ MockActualCall& MockActualCallTrace::withBoolParameter(const SimpleString& name, MockActualCall& MockActualCallTrace::withUnsignedIntParameter(const SimpleString& name, unsigned int value) { addParameterName(name); - traceBuffer_ += StringFrom(value); + traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value); return *this; } MockActualCall& MockActualCallTrace::withIntParameter(const SimpleString& name, int value) { addParameterName(name); - traceBuffer_ += StringFrom(value); + traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value); return *this; } MockActualCall& MockActualCallTrace::withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) { addParameterName(name); - traceBuffer_ += StringFrom(value); + traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value); return *this; } MockActualCall& MockActualCallTrace::withLongIntParameter(const SimpleString& name, long int value) { addParameterName(name); - traceBuffer_ += StringFrom(value); + traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value); return *this; } +#if CPPUTEST_USE_LONG_LONG + +MockActualCall& MockActualCallTrace::withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value) +{ + addParameterName(name); + traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value); + return *this; +} + +MockActualCall& MockActualCallTrace::withLongLongIntParameter(const SimpleString& name, cpputest_longlong value) +{ + addParameterName(name); + traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value); + return *this; +} + +#else + +MockActualCall& MockActualCallTrace::withUnsignedLongLongIntParameter(const SimpleString&, cpputest_ulonglong) +{ + FAIL("Unsigned Long Long type is not supported"); + return *this; +} + +MockActualCall& MockActualCallTrace::withLongLongIntParameter(const SimpleString&, cpputest_longlong) +{ + FAIL("Long Long type is not supported"); + return *this; +} + +#endif + MockActualCall& MockActualCallTrace::withDoubleParameter(const SimpleString& name, double value) { addParameterName(name); @@ -709,9 +855,63 @@ unsigned long int MockActualCallTrace::returnUnsignedLongIntValueOrDefault(unsig long int MockActualCallTrace::returnLongIntValueOrDefault(long int) { - return returnLongIntValue(); + return 0; } +#if CPPUTEST_USE_LONG_LONG + +cpputest_longlong MockActualCallTrace::returnLongLongIntValue() +{ + return 0; +} + +cpputest_ulonglong MockActualCallTrace::returnUnsignedLongLongIntValue() +{ + return 0; +} + +cpputest_ulonglong MockActualCallTrace::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong) +{ + return 0; +} + +cpputest_longlong MockActualCallTrace::returnLongLongIntValueOrDefault(cpputest_longlong) +{ + return 0; +} + +#else + +cpputest_longlong MockActualCallTrace::returnLongLongIntValue() +{ + FAIL("Long Long type is not supported"); + cpputest_longlong ret = {}; + return ret; +} + +cpputest_ulonglong MockActualCallTrace::returnUnsignedLongLongIntValue() +{ + FAIL("Unsigned Long Long type is not supported"); + cpputest_ulonglong ret = {}; + return ret; +} + +cpputest_ulonglong MockActualCallTrace::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong) +{ + FAIL("Unsigned Long Long type is not supported"); + cpputest_ulonglong ret = {}; + return ret; +} + +cpputest_longlong MockActualCallTrace::returnLongLongIntValueOrDefault(cpputest_longlong) +{ + FAIL("Long Long type is not supported"); + cpputest_longlong ret = {}; + return ret; +} + +#endif + bool MockActualCallTrace::returnBoolValue() { return false; @@ -744,17 +944,17 @@ unsigned int MockActualCallTrace::returnUnsignedIntValue() void * MockActualCallTrace::returnPointerValue() { - return NULL; + return NULLPTR; } const void * MockActualCallTrace::returnConstPointerValue() { - return NULL; + return NULLPTR; } void (*MockActualCallTrace::returnFunctionPointerValue())() { - return NULL; + return NULLPTR; } const void * MockActualCallTrace::returnConstPointerValueOrDefault(const void *) @@ -809,10 +1009,19 @@ const char* MockActualCallTrace::getTraceOutput() return traceBuffer_.asCharString(); } +MockActualCallTrace* MockActualCallTrace::instance_ = NULLPTR; + MockActualCallTrace& MockActualCallTrace::instance() { - static MockActualCallTrace call; - return call; + if (instance_ == NULLPTR) + instance_ = new MockActualCallTrace; + return *instance_; +} + +void MockActualCallTrace::clearInstance() +{ + delete instance_; + instance_ = NULLPTR; } MockIgnoredActualCall& MockIgnoredActualCall::instance() diff --git a/src/CppUTestExt/MockExpectedCall.cpp b/src/CppUTestExt/MockExpectedCall.cpp index e9f3c96d0..2e11e7385 100644 --- a/src/CppUTestExt/MockExpectedCall.cpp +++ b/src/CppUTestExt/MockExpectedCall.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -52,7 +52,20 @@ SimpleString MockCheckedExpectedCall::getName() const } MockCheckedExpectedCall::MockCheckedExpectedCall() - : ignoreOtherParameters_(false), parametersWereIgnored_(false), callOrder_(0), expectedCallOrder_(NO_EXPECTED_CALL_ORDER), outOfOrder_(true), returnValue_(""), objectPtr_(NULL), wasPassedToObject_(true) + : ignoreOtherParameters_(false), isActualCallMatchFinalized_(false), + initialExpectedCallOrder_(NO_EXPECTED_CALL_ORDER), finalExpectedCallOrder_(NO_EXPECTED_CALL_ORDER), + outOfOrder_(false), returnValue_(""), objectPtr_(NULLPTR), isSpecificObjectExpected_(false), wasPassedToObject_(true), + actualCalls_(0), expectedCalls_(1) +{ + inputParameters_ = new MockNamedValueList(); + outputParameters_ = new MockNamedValueList(); +} + +MockCheckedExpectedCall::MockCheckedExpectedCall(unsigned int numCalls) + : ignoreOtherParameters_(false), isActualCallMatchFinalized_(false), + initialExpectedCallOrder_(NO_EXPECTED_CALL_ORDER), finalExpectedCallOrder_(NO_EXPECTED_CALL_ORDER), + outOfOrder_(false), returnValue_(""), objectPtr_(NULLPTR), isSpecificObjectExpected_(false), wasPassedToObject_(true), + actualCalls_(0), expectedCalls_(numCalls) { inputParameters_ = new MockNamedValueList(); outputParameters_ = new MockNamedValueList(); @@ -69,7 +82,6 @@ MockCheckedExpectedCall::~MockCheckedExpectedCall() MockExpectedCall& MockCheckedExpectedCall::withName(const SimpleString& name) { setName(name); - callOrder_ = NOT_CALLED_YET; return *this; } @@ -113,6 +125,40 @@ MockExpectedCall& MockCheckedExpectedCall::withUnsignedLongIntParameter(const Si return *this; } +#if CPPUTEST_USE_LONG_LONG + +MockExpectedCall& MockCheckedExpectedCall::withLongLongIntParameter(const SimpleString& name, cpputest_longlong value) +{ + MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); + inputParameters_->add(newParameter); + newParameter->setValue(value); + return *this; +} + +MockExpectedCall& MockCheckedExpectedCall::withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value) +{ + MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); + inputParameters_->add(newParameter); + newParameter->setValue(value); + return *this; +} + +#else + +MockExpectedCall& MockCheckedExpectedCall::withLongLongIntParameter(const SimpleString&, cpputest_longlong) +{ + FAIL("Long Long type is not supported"); + return *this; +} + +MockExpectedCall& MockCheckedExpectedCall::withUnsignedLongLongIntParameter(const SimpleString&, cpputest_ulonglong) +{ + FAIL("Unsigned Long Long type is not supported"); + return *this; +} + +#endif + MockExpectedCall& MockCheckedExpectedCall::withDoubleParameter(const SimpleString& name, double value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); @@ -121,6 +167,14 @@ MockExpectedCall& MockCheckedExpectedCall::withDoubleParameter(const SimpleStrin return *this; } +MockExpectedCall& MockCheckedExpectedCall::withDoubleParameter(const SimpleString& name, double value, double tolerance) +{ + MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); + inputParameters_->add(newParameter); + newParameter->setValue(value, tolerance); + return *this; +} + MockExpectedCall& MockCheckedExpectedCall::withStringParameter(const SimpleString& name, const char* value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); @@ -165,7 +219,7 @@ MockExpectedCall& MockCheckedExpectedCall::withParameterOfType(const SimpleStrin { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); inputParameters_->add(newParameter); - newParameter->setObjectPointer(type, value); + newParameter->setConstObjectPointer(type, value); return *this; } @@ -182,26 +236,31 @@ MockExpectedCall& MockCheckedExpectedCall::withOutputParameterOfTypeReturning(co { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); outputParameters_->add(newParameter); - newParameter->setObjectPointer(type, value); + newParameter->setConstObjectPointer(type, value); return *this; } +MockExpectedCall& MockCheckedExpectedCall::withUnmodifiedOutputParameter(const SimpleString& name) +{ + return withOutputParameterReturning(name, NULLPTR, 0); +} + SimpleString MockCheckedExpectedCall::getInputParameterType(const SimpleString& name) { MockNamedValue * p = inputParameters_->getValueByName(name); - return (p) ? p->getType() : ""; + return (p) ? p->getType() : StringFrom(""); } bool MockCheckedExpectedCall::hasInputParameterWithName(const SimpleString& name) { MockNamedValue * p = inputParameters_->getValueByName(name); - return p != NULL; + return p != NULLPTR; } bool MockCheckedExpectedCall::hasOutputParameterWithName(const SimpleString& name) { MockNamedValue * p = outputParameters_->getValueByName(name); - return p != NULL; + return p != NULLPTR; } MockNamedValue MockCheckedExpectedCall::getInputParameter(const SimpleString& name) @@ -216,25 +275,18 @@ MockNamedValue MockCheckedExpectedCall::getOutputParameter(const SimpleString& n return (p) ? *p : MockNamedValue(""); } -bool MockCheckedExpectedCall::areParametersFulfilled() +bool MockCheckedExpectedCall::areParametersMatchingActualCall() { MockNamedValueListNode* p; for (p = inputParameters_->begin(); p; p = p->next()) - if (! item(p)->isFulfilled()) + if (! item(p)->isMatchingActualCall()) return false; for (p = outputParameters_->begin(); p; p = p->next()) - if (! item(p)->isFulfilled()) + if (! item(p)->isMatchingActualCall()) return false; return true; } -bool MockCheckedExpectedCall::areIgnoredParametersFulfilled() -{ - if (ignoreOtherParameters_) - return parametersWereIgnored_; - return true; -} - MockExpectedCall& MockCheckedExpectedCall::ignoreOtherParameters() { ignoreOtherParameters_ = true; @@ -243,29 +295,39 @@ MockExpectedCall& MockCheckedExpectedCall::ignoreOtherParameters() bool MockCheckedExpectedCall::isFulfilled() { - return isFulfilledWithoutIgnoredParameters() && areIgnoredParametersFulfilled(); + return (actualCalls_ == expectedCalls_); } -bool MockCheckedExpectedCall::isFulfilledWithoutIgnoredParameters() +bool MockCheckedExpectedCall::canMatchActualCalls() { - return callOrder_ != NOT_CALLED_YET && areParametersFulfilled() && wasPassedToObject_; + return (actualCalls_ < expectedCalls_); } +bool MockCheckedExpectedCall::isMatchingActualCallAndFinalized() +{ + return isMatchingActualCall() && (!ignoreOtherParameters_ || isActualCallMatchFinalized_); +} + +bool MockCheckedExpectedCall::isMatchingActualCall() +{ + return areParametersMatchingActualCall() && wasPassedToObject_; +} -void MockCheckedExpectedCall::callWasMade(int callOrder) +void MockCheckedExpectedCall::callWasMade(unsigned int callOrder) { - callOrder_ = callOrder; - if (expectedCallOrder_ == NO_EXPECTED_CALL_ORDER) - outOfOrder_ = false; - else if (callOrder_ == expectedCallOrder_) - outOfOrder_ = false; - else + actualCalls_++; + + if ( (initialExpectedCallOrder_ != NO_EXPECTED_CALL_ORDER) && + ((callOrder < initialExpectedCallOrder_) || (callOrder > finalExpectedCallOrder_)) ) { outOfOrder_ = true; + } + + resetActualCallMatchingState(); } -void MockCheckedExpectedCall::parametersWereIgnored() +void MockCheckedExpectedCall::finalizeActualCallMatch() { - parametersWereIgnored_ = true; + isActualCallMatchFinalized_ = true; } @@ -274,23 +336,24 @@ void MockCheckedExpectedCall::wasPassedToObject() wasPassedToObject_ = true; } -void MockCheckedExpectedCall::resetExpectation() +void MockCheckedExpectedCall::resetActualCallMatchingState() { - callOrder_ = NOT_CALLED_YET; - wasPassedToObject_ = (objectPtr_ == NULL); + wasPassedToObject_ = !isSpecificObjectExpected_; + isActualCallMatchFinalized_ = false; + MockNamedValueListNode* p; for (p = inputParameters_->begin(); p; p = p->next()) - item(p)->setFulfilled(false); + item(p)->setMatchesActualCall(false); for (p = outputParameters_->begin(); p; p = p->next()) - item(p)->setFulfilled(false); + item(p)->setMatchesActualCall(false); } void MockCheckedExpectedCall::inputParameterWasPassed(const SimpleString& name) { for (MockNamedValueListNode* p = inputParameters_->begin(); p; p = p->next()) { if (p->getName() == name) - item(p)->setFulfilled(true); + item(p)->setMatchesActualCall(true); } } @@ -298,14 +361,14 @@ void MockCheckedExpectedCall::outputParameterWasPassed(const SimpleString& name) { for (MockNamedValueListNode* p = outputParameters_->begin(); p; p = p->next()) { if (p->getName() == name) - item(p)->setFulfilled(true); + item(p)->setMatchesActualCall(true); } } SimpleString MockCheckedExpectedCall::getInputParameterValueString(const SimpleString& name) { MockNamedValue * p = inputParameters_->getValueByName(name); - return (p) ? StringFrom(*p) : "failed"; + return (p) ? StringFrom(*p) : StringFrom("failed"); } bool MockCheckedExpectedCall::hasInputParameter(const MockNamedValue& parameter) @@ -323,39 +386,46 @@ bool MockCheckedExpectedCall::hasOutputParameter(const MockNamedValue& parameter SimpleString MockCheckedExpectedCall::callToString() { SimpleString str; - if (objectPtr_) + if (isSpecificObjectExpected_) str = StringFromFormat("(object address: %p)::", objectPtr_); str += getName(); str += " -> "; - if (expectedCallOrder_ != NO_EXPECTED_CALL_ORDER) { - str += StringFromFormat("expected call order: <%d> -> ", expectedCallOrder_); + if (initialExpectedCallOrder_ != NO_EXPECTED_CALL_ORDER) { + if (initialExpectedCallOrder_ == finalExpectedCallOrder_) { + str += StringFromFormat("expected call order: <%u> -> ", initialExpectedCallOrder_); + } else { + str += StringFromFormat("expected calls order: <%u..%u> -> ", initialExpectedCallOrder_, finalExpectedCallOrder_); + } } - if (inputParameters_->begin() == NULL && outputParameters_->begin() == NULL) { + if (inputParameters_->begin() == NULLPTR && outputParameters_->begin() == NULLPTR) { str += (ignoreOtherParameters_) ? "all parameters ignored" : "no parameters"; - return str; - } + } else { + MockNamedValueListNode* p; - MockNamedValueListNode* p; + for (p = inputParameters_->begin(); p; p = p->next()) { + str += StringFromFormat("%s %s: <%s>", p->getType().asCharString(), p->getName().asCharString(), getInputParameterValueString(p->getName()).asCharString()); + if (p->next()) str += ", "; + } - for (p = inputParameters_->begin(); p; p = p->next()) { - str += StringFromFormat("%s %s: <%s>", p->getType().asCharString(), p->getName().asCharString(), getInputParameterValueString(p->getName()).asCharString()); - if (p->next()) str += ", "; - } + if (inputParameters_->begin() && outputParameters_->begin()) + { + str += ", "; + } - if (inputParameters_->begin() && outputParameters_->begin()) - { - str += ", "; - } + for (p = outputParameters_->begin(); p; p = p->next()) { + str += StringFromFormat("%s %s: ", p->getType().asCharString(), p->getName().asCharString()); + if (p->next()) str += ", "; + } - for (p = outputParameters_->begin(); p; p = p->next()) { - str += StringFromFormat("%s %s: ", p->getType().asCharString(), p->getName().asCharString()); - if (p->next()) str += ", "; + if (ignoreOtherParameters_) + str += ", other parameters are ignored"; } - if (ignoreOtherParameters_) - str += ", other parameters are ignored"; + str += StringFromFormat(" (expected %u call%s, called %u time%s)", + expectedCalls_, (expectedCalls_ == 1) ? "" : "s", actualCalls_, (actualCalls_ == 1) ? "" : "s" ); + return str; } @@ -365,13 +435,13 @@ SimpleString MockCheckedExpectedCall::missingParametersToString() MockNamedValueListNode* p; for (p = inputParameters_->begin(); p; p = p->next()) { - if (! item(p)->isFulfilled()) { + if (! item(p)->isMatchingActualCall()) { if (str != "") str += ", "; str += StringFromFormat("%s %s", p->getType().asCharString(), p->getName().asCharString()); } } for (p = outputParameters_->begin(); p; p = p->next()) { - if (! item(p)->isFulfilled()) { + if (! item(p)->isMatchingActualCall()) { if (str != "") str += ", "; str += StringFromFormat("%s %s", p->getType().asCharString(), p->getName().asCharString()); } @@ -386,7 +456,7 @@ bool MockCheckedExpectedCall::relatesTo(const SimpleString& functionName) bool MockCheckedExpectedCall::relatesToObject(const void* objectPtr) const { - return objectPtr_ == objectPtr; + return (!isSpecificObjectExpected_) || (objectPtr_ == objectPtr); } MockCheckedExpectedCall::MockExpectedFunctionParameter* MockCheckedExpectedCall::item(MockNamedValueListNode* node) @@ -395,18 +465,18 @@ MockCheckedExpectedCall::MockExpectedFunctionParameter* MockCheckedExpectedCall: } MockCheckedExpectedCall::MockExpectedFunctionParameter::MockExpectedFunctionParameter(const SimpleString& name) - : MockNamedValue(name), fulfilled_(false) + : MockNamedValue(name), matchesActualCall_(false) { } -void MockCheckedExpectedCall::MockExpectedFunctionParameter::setFulfilled(bool b) +void MockCheckedExpectedCall::MockExpectedFunctionParameter::setMatchesActualCall(bool b) { - fulfilled_ = b; + matchesActualCall_ = b; } -bool MockCheckedExpectedCall::MockExpectedFunctionParameter::isFulfilled() const +bool MockCheckedExpectedCall::MockExpectedFunctionParameter::isMatchingActualCall() const { - return fulfilled_; + return matchesActualCall_; } MockExpectedCall& MockCheckedExpectedCall::andReturnValue(bool value) @@ -444,294 +514,101 @@ MockExpectedCall& MockCheckedExpectedCall::andReturnValue(unsigned long int valu return *this; } -MockExpectedCall& MockCheckedExpectedCall::andReturnValue(const char* value) -{ - returnValue_.setName("returnValue"); - returnValue_.setValue(value); - return *this; -} +#if CPPUTEST_USE_LONG_LONG -MockExpectedCall& MockCheckedExpectedCall::andReturnValue(double value) +MockExpectedCall& MockCheckedExpectedCall::andReturnValue(cpputest_longlong value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } -MockExpectedCall& MockCheckedExpectedCall::andReturnValue(void* value) +MockExpectedCall& MockCheckedExpectedCall::andReturnValue(cpputest_ulonglong value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } -MockExpectedCall& MockCheckedExpectedCall::andReturnValue(const void* value) -{ - returnValue_.setName("returnValue"); - returnValue_.setValue(value); - return *this; -} +#else -MockExpectedCall& MockCheckedExpectedCall::andReturnValue(void (*value)()) +MockExpectedCall& MockCheckedExpectedCall::andReturnValue(cpputest_longlong) { - returnValue_.setName("returnValue"); - returnValue_.setValue(value); + FAIL("Long Long type is not supported"); return *this; } -MockExpectedCall& MockCheckedExpectedCall::onObject(void* objectPtr) +MockExpectedCall& MockCheckedExpectedCall::andReturnValue(cpputest_ulonglong) { - wasPassedToObject_ = false; - objectPtr_ = objectPtr; - return *this; -} - -MockNamedValue MockCheckedExpectedCall::returnValue() -{ - return returnValue_; -} - -int MockCheckedExpectedCall::getCallOrder() const -{ - return callOrder_; -} - -MockExpectedCall& MockCheckedExpectedCall::withCallOrder(int callOrder) -{ - expectedCallOrder_ = callOrder; + FAIL("Unsigned Long Long type is not supported"); return *this; } -bool MockCheckedExpectedCall::isOutOfOrder() const -{ - return outOfOrder_; -} - -struct MockExpectedCallCompositeNode -{ - MockExpectedCallCompositeNode(MockExpectedCall& functionCall, MockExpectedCallCompositeNode* next) : next_(next), call_(functionCall){} - - MockExpectedCallCompositeNode* next_; - MockExpectedCall& call_; -}; - -MockExpectedCallComposite::MockExpectedCallComposite() : head_(NULL) -{ -} - -MockExpectedCallComposite::~MockExpectedCallComposite() -{ +#endif -} - -void MockExpectedCallComposite::add(MockExpectedCall& call) -{ - head_ = new MockExpectedCallCompositeNode(call, head_); -} - -void MockExpectedCallComposite::clear() -{ - while (head_) { - MockExpectedCallCompositeNode* next = head_->next_; - delete head_; - head_ = next; - } -} - -MockExpectedCall& MockExpectedCallComposite::withName(const SimpleString& name) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withName(name); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withCallOrder(int) -{ - FAIL("withCallOrder not supported for CompositeCalls"); - return *this; // LCOV_EXCL_LINE -} - -MockExpectedCall& MockExpectedCallComposite::withBoolParameter(const SimpleString& name, bool value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameter(name, value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withUnsignedIntParameter(const SimpleString& name, unsigned int value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameter(name, value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withIntParameter(const SimpleString& name, int value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameter(name, value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withLongIntParameter(const SimpleString& name, long int value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameter(name, value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameter(name, value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withDoubleParameter(const SimpleString& name, double value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameter(name, value); - return *this; - -} - -MockExpectedCall& MockExpectedCallComposite::withStringParameter(const SimpleString& name, const char* value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameter(name, value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withPointerParameter(const SimpleString& name, void* value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameter(name, value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withConstPointerParameter(const SimpleString& name, const void* value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameter(name, value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withFunctionPointerParameter(const SimpleString& name, void (*value)()) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameter(name, value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameter(name, value, size); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withParameterOfType(typeName, name, value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withOutputParameterReturning(const SimpleString& name, const void* value, size_t size) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withOutputParameterReturning(name, value, size); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::withOutputParameterOfTypeReturning(const SimpleString& typeName, const SimpleString& name, const void* value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.withOutputParameterOfTypeReturning(typeName, name, value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::ignoreOtherParameters() -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.ignoreOtherParameters(); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::andReturnValue(bool value) -{ - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.andReturnValue(value); - return *this; -} - -MockExpectedCall& MockExpectedCallComposite::andReturnValue(unsigned int value) +MockExpectedCall& MockCheckedExpectedCall::andReturnValue(const char* value) { - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.andReturnValue(value); + returnValue_.setName("returnValue"); + returnValue_.setValue(value); return *this; } -MockExpectedCall& MockExpectedCallComposite::andReturnValue(int value) +MockExpectedCall& MockCheckedExpectedCall::andReturnValue(double value) { - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.andReturnValue(value); + returnValue_.setName("returnValue"); + returnValue_.setValue(value); return *this; } -MockExpectedCall& MockExpectedCallComposite::andReturnValue(long int value) +MockExpectedCall& MockCheckedExpectedCall::andReturnValue(void* value) { - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.andReturnValue(value); + returnValue_.setName("returnValue"); + returnValue_.setValue(value); return *this; } -MockExpectedCall& MockExpectedCallComposite::andReturnValue(unsigned long int value) +MockExpectedCall& MockCheckedExpectedCall::andReturnValue(const void* value) { - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.andReturnValue(value); + returnValue_.setName("returnValue"); + returnValue_.setValue(value); return *this; } -MockExpectedCall& MockExpectedCallComposite::andReturnValue(double value) +MockExpectedCall& MockCheckedExpectedCall::andReturnValue(void (*value)()) { - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.andReturnValue(value); + returnValue_.setName("returnValue"); + returnValue_.setValue(value); return *this; } -MockExpectedCall& MockExpectedCallComposite::andReturnValue(const char* value) +MockExpectedCall& MockCheckedExpectedCall::onObject(void* objectPtr) { - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.andReturnValue(value); + isSpecificObjectExpected_ = true; + wasPassedToObject_ = false; + objectPtr_ = objectPtr; return *this; } -MockExpectedCall& MockExpectedCallComposite::andReturnValue(void* value) +MockNamedValue MockCheckedExpectedCall::returnValue() { - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.andReturnValue(value); - return *this; + return returnValue_; } -MockExpectedCall& MockExpectedCallComposite::andReturnValue(const void* value) +MockExpectedCall& MockCheckedExpectedCall::withCallOrder(unsigned int initialCallOrder, unsigned int finalCallOrder) { - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.andReturnValue(value); + initialExpectedCallOrder_ = initialCallOrder; + finalExpectedCallOrder_ = finalCallOrder; return *this; } -MockExpectedCall& MockExpectedCallComposite::andReturnValue(void (*value)()) +bool MockCheckedExpectedCall::isOutOfOrder() const { - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.andReturnValue(value); - return *this; + return outOfOrder_; } -MockExpectedCall& MockExpectedCallComposite::onObject(void* object) +unsigned int MockCheckedExpectedCall::getActualCallsFulfilled() const { - for (MockExpectedCallCompositeNode* node = head_; node != NULL; node = node->next_) - node->call_.onObject(object); - return *this; + return actualCalls_; } MockExpectedCall& MockIgnoredExpectedCall::instance() diff --git a/src/CppUTestExt/MockExpectedCallsList.cpp b/src/CppUTestExt/MockExpectedCallsList.cpp index 06d0643ce..dd2970d7d 100644 --- a/src/CppUTestExt/MockExpectedCallsList.cpp +++ b/src/CppUTestExt/MockExpectedCallsList.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -29,7 +29,7 @@ #include "CppUTestExt/MockExpectedCallsList.h" #include "CppUTestExt/MockCheckedExpectedCall.h" -MockExpectedCallsList::MockExpectedCallsList() : head_(NULL) +MockExpectedCallsList::MockExpectedCallsList() : head_(NULLPTR) { } @@ -50,9 +50,9 @@ bool MockExpectedCallsList::hasCallsOutOfOrder() const return false; } -int MockExpectedCallsList::size() const +unsigned int MockExpectedCallsList::size() const { - int count = 0; + unsigned int count = 0; for (MockExpectedCallsListNode* p = head_; p; p = p->next_) count++; return count; @@ -60,43 +60,46 @@ int MockExpectedCallsList::size() const bool MockExpectedCallsList::isEmpty() const { - return size() == 0; + return head_ == NULLPTR; } - -int MockExpectedCallsList::amountOfExpectationsFor(const SimpleString& name) const +unsigned int MockExpectedCallsList::amountOfActualCallsFulfilledFor(const SimpleString& name) const { - int count = 0; - for (MockExpectedCallsListNode* p = head_; p; p = p->next_) - if (p->expectedCall_->relatesTo(name)) count++; + unsigned int count = 0; + for (MockExpectedCallsListNode* p = head_; p; p = p->next_) { + if (p->expectedCall_->relatesTo(name)) { + count += p->expectedCall_->getActualCallsFulfilled(); + } + } return count; - } -int MockExpectedCallsList::amountOfUnfulfilledExpectations() const +unsigned int MockExpectedCallsList::amountOfUnfulfilledExpectations() const { - int count = 0; + unsigned int count = 0; for (MockExpectedCallsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->isFulfilled()) count++; return count; } -bool MockExpectedCallsList::hasFulfilledExpectations() const -{ - return (size() - amountOfUnfulfilledExpectations()) != 0; -} - -bool MockExpectedCallsList::hasFulfilledExpectationsWithoutIgnoredParameters() const +bool MockExpectedCallsList::hasFinalizedMatchingExpectations() const { - for (MockExpectedCallsListNode* p = head_; p; p = p->next_) - if (p->expectedCall_->isFulfilledWithoutIgnoredParameters()) + for (MockExpectedCallsListNode* p = head_; p; p = p->next_) { + if (p->expectedCall_->isMatchingActualCallAndFinalized()) { return true; + } + } return false; } bool MockExpectedCallsList::hasUnfulfilledExpectations() const { - return amountOfUnfulfilledExpectations() != 0; + for (MockExpectedCallsListNode* p = head_; p; p = p->next_) { + if (!p->expectedCall_->isFulfilled()) { + return true; + } + } + return false; } bool MockExpectedCallsList::hasExpectationWithName(const SimpleString& name) const @@ -111,7 +114,7 @@ void MockExpectedCallsList::addExpectedCall(MockCheckedExpectedCall* call) { MockExpectedCallsListNode* newCall = new MockExpectedCallsListNode(call); - if (head_ == NULL) + if (head_ == NULLPTR) head_ = newCall; else { MockExpectedCallsListNode* lastCall = head_; @@ -120,10 +123,10 @@ void MockExpectedCallsList::addExpectedCall(MockCheckedExpectedCall* call) } } -void MockExpectedCallsList::addUnfulfilledExpectations(const MockExpectedCallsList& list) +void MockExpectedCallsList::addPotentiallyMatchingExpectations(const MockExpectedCallsList& list) { for (MockExpectedCallsListNode* p = list.head_; p; p = p->next_) - if (! p->expectedCall_->isFulfilled()) + if (p->expectedCall_->canMatchActualCalls()) addExpectedCall(p->expectedCall_); } @@ -144,7 +147,7 @@ void MockExpectedCallsList::onlyKeepExpectationsRelatedTo(const SimpleString& na { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->relatesTo(name)) - p->expectedCall_ = NULL; + p->expectedCall_ = NULLPTR; pruneEmptyNodeFromList(); } @@ -153,17 +156,17 @@ void MockExpectedCallsList::onlyKeepOutOfOrderExpectations() { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) if (!p->expectedCall_->isOutOfOrder()) - p->expectedCall_ = NULL; + p->expectedCall_ = NULLPTR; pruneEmptyNodeFromList(); } -void MockExpectedCallsList::onlyKeepUnfulfilledExpectations() +void MockExpectedCallsList::onlyKeepUnmatchingExpectations() { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) - if (p->expectedCall_->isFulfilled()) + if (p->expectedCall_->isMatchingActualCallAndFinalized()) { - p->expectedCall_->resetExpectation(); - p->expectedCall_ = NULL; + p->expectedCall_->resetActualCallMatchingState(); + p->expectedCall_ = NULLPTR; } pruneEmptyNodeFromList(); @@ -173,7 +176,7 @@ void MockExpectedCallsList::onlyKeepExpectationsWithInputParameterName(const Sim { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->hasInputParameterWithName(name)) - p->expectedCall_ = NULL; + p->expectedCall_ = NULLPTR; pruneEmptyNodeFromList(); } @@ -181,7 +184,7 @@ void MockExpectedCallsList::onlyKeepExpectationsWithOutputParameterName(const Si { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->hasOutputParameterWithName(name)) - p->expectedCall_ = NULL; + p->expectedCall_ = NULLPTR; pruneEmptyNodeFromList(); } @@ -189,7 +192,7 @@ void MockExpectedCallsList::onlyKeepExpectationsWithInputParameter(const MockNam { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->hasInputParameter(parameter)) - p->expectedCall_ = NULL; + p->expectedCall_ = NULLPTR; pruneEmptyNodeFromList(); } @@ -197,7 +200,7 @@ void MockExpectedCallsList::onlyKeepExpectationsWithOutputParameter(const MockNa { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->hasOutputParameter(parameter)) - p->expectedCall_ = NULL; + p->expectedCall_ = NULLPTR; pruneEmptyNodeFromList(); } @@ -205,57 +208,56 @@ void MockExpectedCallsList::onlyKeepExpectationsOnObject(const void* objectPtr) { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->relatesToObject(objectPtr)) - p->expectedCall_ = NULL; + p->expectedCall_ = NULLPTR; pruneEmptyNodeFromList(); } -MockCheckedExpectedCall* MockExpectedCallsList::removeOneFulfilledExpectation() +MockCheckedExpectedCall* MockExpectedCallsList::removeFirstFinalizedMatchingExpectation() { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) { - if (p->expectedCall_->isFulfilled()) { - MockCheckedExpectedCall* fulfilledCall = p->expectedCall_; - p->expectedCall_ = NULL; + if (p->expectedCall_->isMatchingActualCallAndFinalized()) { + MockCheckedExpectedCall* matchingCall = p->expectedCall_; + p->expectedCall_ = NULLPTR; pruneEmptyNodeFromList(); - return fulfilledCall; + return matchingCall; } } - return NULL; + return NULLPTR; } -MockCheckedExpectedCall* MockExpectedCallsList::getOneFulfilledExpectationWithIgnoredParameters() +MockCheckedExpectedCall* MockExpectedCallsList::getFirstMatchingExpectation() { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) { - if (p->expectedCall_->isFulfilledWithoutIgnoredParameters()) { + if (p->expectedCall_->isMatchingActualCall()) { return p->expectedCall_; } } - return NULL; + return NULLPTR; } -MockCheckedExpectedCall* MockExpectedCallsList::removeOneFulfilledExpectationWithIgnoredParameters() +MockCheckedExpectedCall* MockExpectedCallsList::removeFirstMatchingExpectation() { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) { - if (p->expectedCall_->isFulfilledWithoutIgnoredParameters()) { - MockCheckedExpectedCall* fulfilledCall = p->expectedCall_; - p->expectedCall_->parametersWereIgnored(); - p->expectedCall_ = NULL; + if (p->expectedCall_->isMatchingActualCall()) { + MockCheckedExpectedCall* matchingCall = p->expectedCall_; + p->expectedCall_ = NULLPTR; pruneEmptyNodeFromList(); - return fulfilledCall; + return matchingCall; } } - return NULL; + return NULLPTR; } void MockExpectedCallsList::pruneEmptyNodeFromList() { MockExpectedCallsListNode* current = head_; - MockExpectedCallsListNode* previous = NULL; - MockExpectedCallsListNode* toBeDeleted = NULL; + MockExpectedCallsListNode* previous = NULLPTR; + MockExpectedCallsListNode* toBeDeleted = NULLPTR; while (current) { - if (current->expectedCall_ == NULL) { + if (current->expectedCall_ == NULLPTR) { toBeDeleted = current; - if (previous == NULL) + if (previous == NULLPTR) head_ = current = current->next_; else current = previous->next_ = current->next_; @@ -278,16 +280,10 @@ void MockExpectedCallsList::deleteAllExpectationsAndClearList() } } -void MockExpectedCallsList::resetExpectations() -{ - for (MockExpectedCallsListNode* p = head_; p; p = p->next_) - p->expectedCall_->resetExpectation(); -} - -void MockExpectedCallsList::callWasMade(int callOrder) +void MockExpectedCallsList::resetActualCallMatchingState() { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) - p->expectedCall_->callWasMade(callOrder); + p->expectedCall_->resetActualCallMatchingState(); } void MockExpectedCallsList::wasPassedToObject() @@ -309,14 +305,6 @@ void MockExpectedCallsList::outputParameterWasPassed(const SimpleString& paramet p->expectedCall_->outputParameterWasPassed(parameterName); } -MockExpectedCallsList::MockExpectedCallsListNode* MockExpectedCallsList::findNodeWithCallOrderOf(int callOrder) const -{ - for (MockExpectedCallsListNode* p = head_; p; p = p->next_) - if (p->expectedCall_->getCallOrder() == callOrder && p->expectedCall_->isFulfilled()) - return p; - return NULL; -} - static SimpleString stringOrNoneTextWhenEmpty(const SimpleString& inputString, const SimpleString& linePrefix) { SimpleString str = inputString; @@ -349,28 +337,30 @@ SimpleString MockExpectedCallsList::fulfilledCallsToString(const SimpleString& l { SimpleString str; - MockExpectedCallsListNode* nextNodeInOrder; - for (int callOrder = 1; (nextNodeInOrder = findNodeWithCallOrderOf(callOrder)); callOrder++) - if (nextNodeInOrder) - str = appendStringOnANewLine(str, linePrefix, nextNodeInOrder->expectedCall_->callToString()); + for (MockExpectedCallsListNode* p = head_; p; p = p->next_) + if (p->expectedCall_->isFulfilled()) + str = appendStringOnANewLine(str, linePrefix, p->expectedCall_->callToString()); return stringOrNoneTextWhenEmpty(str, linePrefix); } -SimpleString MockExpectedCallsList::missingParametersToString() const +SimpleString MockExpectedCallsList::callsWithMissingParametersToString(const SimpleString& linePrefix, + const SimpleString& missingParametersPrefix) const { SimpleString str; for (MockExpectedCallsListNode* p = head_; p; p = p->next_) - if (! p->expectedCall_->isFulfilled()) - str = appendStringOnANewLine(str, "", p->expectedCall_->missingParametersToString()); + { + str = appendStringOnANewLine(str, linePrefix, p->expectedCall_->callToString()); + str = appendStringOnANewLine(str, linePrefix + missingParametersPrefix, p->expectedCall_->missingParametersToString()); + } - return stringOrNoneTextWhenEmpty(str, ""); + return stringOrNoneTextWhenEmpty(str, linePrefix); } -bool MockExpectedCallsList::hasUnfulfilledExpectationsBecauseOfMissingParameters() const +bool MockExpectedCallsList::hasUnmatchingExpectationsBecauseOfMissingParameters() const { for (MockExpectedCallsListNode* p = head_; p; p = p->next_) - if (! p->expectedCall_->areParametersFulfilled()) + if (! p->expectedCall_->areParametersMatchingActualCall()) return true; return false; } diff --git a/src/CppUTestExt/MockFailure.cpp b/src/CppUTestExt/MockFailure.cpp index bb93ea503..1c0a40f4f 100644 --- a/src/CppUTestExt/MockFailure.cpp +++ b/src/CppUTestExt/MockFailure.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -31,22 +31,22 @@ #include "CppUTestExt/MockExpectedCallsList.h" #include "CppUTestExt/MockNamedValue.h" -class MockFailureReporterTestTerminator : public NormalTestTerminator +class MockFailureReporterTestTerminator : public TestTerminator { public: MockFailureReporterTestTerminator(bool crashOnFailure) : crashOnFailure_(crashOnFailure) { } - virtual void exitCurrentTest() const + virtual void exitCurrentTest() const CPPUTEST_OVERRIDE { if (crashOnFailure_) UT_CRASH(); - NormalTestTerminator::exitCurrentTest(); + UtestShell::getCurrentTestTerminator().exitCurrentTest(); } // LCOV_EXCL_LINE - virtual ~MockFailureReporterTestTerminator() + virtual ~MockFailureReporterTestTerminator() CPPUTEST_DESTRUCTOR_OVERRIDE { } private: @@ -71,9 +71,9 @@ MockFailure::MockFailure(UtestShell* test) : TestFailure(test, "Test failed with void MockFailure::addExpectationsAndCallHistory(const MockExpectedCallsList& expectations) { - message_ += "\tEXPECTED calls that did NOT happen:\n"; + message_ += "\tEXPECTED calls that WERE NOT fulfilled:\n"; message_ += expectations.unfulfilledCallsToString("\t\t"); - message_ += "\n\tACTUAL calls that did happen (in call order):\n"; + message_ += "\n\tEXPECTED calls that WERE fulfilled:\n"; message_ += expectations.fulfilledCallsToString("\t\t"); } @@ -82,13 +82,13 @@ void MockFailure::addExpectationsAndCallHistoryRelatedTo(const SimpleString& nam MockExpectedCallsList expectationsForFunction; expectationsForFunction.addExpectationsRelatedTo(name, expectations); - message_ += "\tEXPECTED calls that DID NOT happen related to function: "; + message_ += "\tEXPECTED calls that WERE NOT fulfilled related to function: "; message_ += name; message_ += "\n"; message_ += expectationsForFunction.unfulfilledCallsToString("\t\t"); - message_ += "\n\tACTUAL calls that DID happen related to function: "; + message_ += "\n\tEXPECTED calls that WERE fulfilled related to function: "; message_ += name; message_ += "\n"; @@ -97,14 +97,15 @@ void MockFailure::addExpectationsAndCallHistoryRelatedTo(const SimpleString& nam MockExpectedCallsDidntHappenFailure::MockExpectedCallsDidntHappenFailure(UtestShell* test, const MockExpectedCallsList& expectations) : MockFailure(test) { - message_ = "Mock Failure: Expected call did not happen.\n"; + message_ = "Mock Failure: Expected call WAS NOT fulfilled.\n"; addExpectationsAndCallHistory(expectations); } MockUnexpectedCallHappenedFailure::MockUnexpectedCallHappenedFailure(UtestShell* test, const SimpleString& name, const MockExpectedCallsList& expectations) : MockFailure(test) { - if (expectations.amountOfExpectationsFor(name)) { - SimpleString ordinalNumber = StringFromOrdinalNumber((unsigned)(expectations.amountOfExpectationsFor(name) + 1)); + unsigned int amountOfActualCalls = expectations.amountOfActualCallsFulfilledFor(name); + if (amountOfActualCalls > 0) { + SimpleString ordinalNumber = StringFromOrdinalNumber(amountOfActualCalls + 1); message_ = StringFromFormat("Mock Failure: Unexpected additional (%s) call to function: ", ordinalNumber.asCharString()); } else { message_ = "Mock Failure: Unexpected call to function: "; @@ -198,20 +199,21 @@ MockUnexpectedOutputParameterFailure::MockUnexpectedOutputParameterFailure(Utest message_ += parameter.getName(); } -MockExpectedParameterDidntHappenFailure::MockExpectedParameterDidntHappenFailure(UtestShell* test, const SimpleString& functionName, const MockExpectedCallsList& expectations) : MockFailure(test) +MockExpectedParameterDidntHappenFailure::MockExpectedParameterDidntHappenFailure(UtestShell* test, const SimpleString& functionName, + const MockExpectedCallsList& allExpectations, + const MockExpectedCallsList& matchingExpectations) : MockFailure(test) { - MockExpectedCallsList expectationsForFunction; - expectationsForFunction.addExpectationsRelatedTo(functionName, expectations); - message_ = "Mock Failure: Expected parameter for function \""; message_ += functionName; message_ += "\" did not happen.\n"; - addExpectationsAndCallHistoryRelatedTo(functionName, expectations); + message_ += "\tEXPECTED calls with MISSING parameters related to function: "; + message_ += functionName; + message_ += "\n"; + message_ += matchingExpectations.callsWithMissingParametersToString("\t\t", "\tMISSING parameters: "); + message_ += "\n"; - message_ += "\n\tMISSING parameters that didn't happen:\n"; - message_ += "\t\t"; - message_ += expectationsForFunction.missingParametersToString(); + addExpectationsAndCallHistoryRelatedTo(functionName, allExpectations); } MockNoWayToCompareCustomTypeFailure::MockNoWayToCompareCustomTypeFailure(UtestShell* test, const SimpleString& typeName) : MockFailure(test) diff --git a/src/CppUTestExt/MockNamedValue.cpp b/src/CppUTestExt/MockNamedValue.cpp index 169b9ac29..2d4f1d1a0 100644 --- a/src/CppUTestExt/MockNamedValue.cpp +++ b/src/CppUTestExt/MockNamedValue.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,14 +30,20 @@ #include "CppUTest/PlatformSpecificFunctions.h" -MockNamedValueComparatorsAndCopiersRepository* MockNamedValue::defaultRepository_ = NULL; +MockNamedValueComparatorsAndCopiersRepository* MockNamedValue::defaultRepository_ = NULLPTR; +const double MockNamedValue::defaultDoubleTolerance = 0.005; void MockNamedValue::setDefaultComparatorsAndCopiersRepository(MockNamedValueComparatorsAndCopiersRepository* repository) { defaultRepository_ = repository; } -MockNamedValue::MockNamedValue(const SimpleString& name) : name_(name), type_("int"), size_(0), comparator_(NULL), copier_(NULL) +MockNamedValueComparatorsAndCopiersRepository* MockNamedValue::getDefaultComparatorsAndCopiersRepository() +{ + return defaultRepository_; +} + +MockNamedValue::MockNamedValue(const SimpleString& name) : name_(name), type_("int"), size_(0), comparator_(NULLPTR), copier_(NULLPTR) { value_.intValue_ = 0; } @@ -76,10 +82,44 @@ void MockNamedValue::setValue(unsigned long int value) value_.unsignedLongIntValue_ = value; } +#if CPPUTEST_USE_LONG_LONG + +void MockNamedValue::setValue(cpputest_longlong value) +{ + type_ = "long long int"; + value_.longLongIntValue_ = value; +} + +void MockNamedValue::setValue(cpputest_ulonglong value) +{ + type_ = "unsigned long long int"; + value_.unsignedLongLongIntValue_ = value; +} + +#else + +void MockNamedValue::setValue(cpputest_longlong) +{ + FAIL("Long Long type is not supported"); +} + +void MockNamedValue::setValue(cpputest_ulonglong) +{ + FAIL("Unsigned Long Long type is not supported"); +} + +#endif + void MockNamedValue::setValue(double value) +{ + setValue(value, defaultDoubleTolerance); +} + +void MockNamedValue::setValue(double value, double tolerance) { type_ = "double"; - value_.doubleValue_ = value; + value_.doubleValue_.value = value; + value_.doubleValue_.tolerance = tolerance; } void MockNamedValue::setValue(void* value) @@ -113,7 +153,18 @@ void MockNamedValue::setMemoryBuffer(const unsigned char* value, size_t size) size_ = size; } -void MockNamedValue::setObjectPointer(const SimpleString& type, const void* objectPtr) +void MockNamedValue::setConstObjectPointer(const SimpleString& type, const void* objectPtr) +{ + type_ = type; + value_.constObjectPointerValue_ = objectPtr; + if (defaultRepository_) + { + comparator_ = defaultRepository_->getComparatorForType(type); + copier_ = defaultRepository_->getCopierForType(type); + } +} + +void MockNamedValue::setObjectPointer(const SimpleString& type, void* objectPtr) { type_ = type; value_.objectPointerValue_ = objectPtr; @@ -195,10 +246,72 @@ unsigned long int MockNamedValue::getUnsignedLongIntValue() const } } +#if CPPUTEST_USE_LONG_LONG + +cpputest_longlong MockNamedValue::getLongLongIntValue() const +{ + if(type_ == "int") + return value_.intValue_; + else if(type_ == "unsigned int") + return (long long int)value_.unsignedIntValue_; + else if(type_ == "long int") + return value_.longIntValue_; + else if(type_ == "unsigned long int") + return (long long int)value_.unsignedLongIntValue_; + else + { + STRCMP_EQUAL("long long int", type_.asCharString()); + return value_.longLongIntValue_; + } +} + +cpputest_ulonglong MockNamedValue::getUnsignedLongLongIntValue() const +{ + if(type_ == "unsigned int") + return value_.unsignedIntValue_; + else if(type_ == "int" && value_.intValue_ >= 0) + return (unsigned long long int)value_.intValue_; + else if(type_ == "long int" && value_.longIntValue_ >= 0) + return (unsigned long long int)value_.longIntValue_; + else if(type_ == "unsigned long int") + return value_.unsignedLongIntValue_; + else if(type_ == "long long int" && value_.longLongIntValue_ >= 0) + return (unsigned long long int)value_.longLongIntValue_; + else + { + STRCMP_EQUAL("unsigned long long int", type_.asCharString()); + return value_.unsignedLongLongIntValue_; + } +} + +#else + +cpputest_longlong MockNamedValue::getLongLongIntValue() const +{ + FAIL("Long Long type is not supported"); + cpputest_longlong ret = {}; + return ret; +} + +cpputest_ulonglong MockNamedValue::getUnsignedLongLongIntValue() const +{ + FAIL("Unsigned Long Long type is not supported"); + cpputest_ulonglong ret = {}; + return ret; +} + +#endif + double MockNamedValue::getDoubleValue() const { STRCMP_EQUAL("double", type_.asCharString()); - return value_.doubleValue_; + return value_.doubleValue_.value; +} + +double MockNamedValue::getDoubleTolerance() const +{ + STRCMP_EQUAL("double", type_.asCharString()); + return value_.doubleValue_.tolerance; } const char* MockNamedValue::getStringValue() const @@ -231,7 +344,12 @@ const unsigned char* MockNamedValue::getMemoryBuffer() const return value_.memoryBufferValue_; } -const void* MockNamedValue::getObjectPointer() const +const void* MockNamedValue::getConstObjectPointer() const +{ + return value_.constObjectPointerValue_; +} + +void* MockNamedValue::getObjectPointer() const { return value_.objectPointerValue_; } @@ -258,25 +376,63 @@ bool MockNamedValue::equals(const MockNamedValue& p) const else if((type_ == "int") && (p.type_ == "long int")) return value_.intValue_ == p.value_.longIntValue_; else if((type_ == "unsigned int") && (p.type_ == "int")) - return (long)value_.unsignedIntValue_ == (long)p.value_.intValue_; + return (p.value_.intValue_ >= 0) && (value_.unsignedIntValue_ == (unsigned int)p.value_.intValue_); else if((type_ == "int") && (p.type_ == "unsigned int")) - return (long)value_.intValue_ == (long)p.value_.unsignedIntValue_; + return (value_.intValue_ >= 0) && ((unsigned int)value_.intValue_ == p.value_.unsignedIntValue_); else if((type_ == "unsigned long int") && (p.type_ == "int")) - return value_.unsignedLongIntValue_ == (unsigned long)p.value_.intValue_; + return (p.value_.intValue_ >= 0) && (value_.unsignedLongIntValue_ == (unsigned long)p.value_.intValue_); else if((type_ == "int") && (p.type_ == "unsigned long int")) - return (unsigned long)value_.intValue_ == p.value_.unsignedLongIntValue_; + return (value_.intValue_ >= 0) && ((unsigned long)value_.intValue_ == p.value_.unsignedLongIntValue_); else if((type_ == "unsigned int") && (p.type_ == "long int")) - return (long int)value_.unsignedIntValue_ == p.value_.longIntValue_; + return (p.value_.longIntValue_ >= 0) && (value_.unsignedIntValue_ == (unsigned long)p.value_.longIntValue_); else if((type_ == "long int") && (p.type_ == "unsigned int")) - return value_.longIntValue_ == (long int)p.value_.unsignedIntValue_; + return (value_.longIntValue_ >= 0) && ((unsigned long)value_.longIntValue_ == p.value_.unsignedIntValue_); else if((type_ == "unsigned int") && (p.type_ == "unsigned long int")) return value_.unsignedIntValue_ == p.value_.unsignedLongIntValue_; else if((type_ == "unsigned long int") && (p.type_ == "unsigned int")) return value_.unsignedLongIntValue_ == p.value_.unsignedIntValue_; else if((type_ == "long int") && (p.type_ == "unsigned long int")) - return (value_.longIntValue_ >= 0) && (value_.longIntValue_ == (long) p.value_.unsignedLongIntValue_); + return (value_.longIntValue_ >= 0) && ((unsigned long)value_.longIntValue_ == p.value_.unsignedLongIntValue_); else if((type_ == "unsigned long int") && (p.type_ == "long int")) - return (p.value_.longIntValue_ >= 0) && ((long)value_.unsignedLongIntValue_ == p.value_.longIntValue_); + return (p.value_.longIntValue_ >= 0) && (value_.unsignedLongIntValue_ == (unsigned long) p.value_.longIntValue_); +#if CPPUTEST_USE_LONG_LONG + else if ((type_ == "long long int") && (p.type_ == "int")) + return value_.longLongIntValue_ == p.value_.intValue_; + else if ((type_ == "int") && (p.type_ == "long long int")) + return value_.intValue_ == p.value_.longLongIntValue_; + else if ((type_ == "long long int") && (p.type_ == "long int")) + return value_.longLongIntValue_ == p.value_.longIntValue_; + else if ((type_ == "long int") && (p.type_ == "long long int")) + return value_.longIntValue_ == p.value_.longLongIntValue_; + else if ((type_ == "long long int") && (p.type_ == "unsigned int")) + return (value_.longLongIntValue_ >= 0) && ((unsigned long long)value_.longLongIntValue_ == p.value_.unsignedIntValue_); + else if ((type_ == "unsigned int") && (p.type_ == "long long int")) + return (p.value_.longLongIntValue_ >= 0) && (value_.unsignedIntValue_ == (unsigned long long)p.value_.longLongIntValue_); + else if ((type_ == "long long int") && (p.type_ == "unsigned long int")) + return (value_.longLongIntValue_ >= 0) && ((unsigned long long)value_.longLongIntValue_ == p.value_.unsignedLongIntValue_); + else if ((type_ == "unsigned long int") && (p.type_ == "long long int")) + return (p.value_.longLongIntValue_ >= 0) && (value_.unsignedLongIntValue_ == (unsigned long long)p.value_.longLongIntValue_); + else if ((type_ == "long long int") && (p.type_ == "unsigned long long int")) + return (value_.longLongIntValue_ >= 0) && ((unsigned long long)value_.longLongIntValue_ == p.value_.unsignedLongLongIntValue_); + else if ((type_ == "unsigned long long int") && (p.type_ == "long long int")) + return (p.value_.longLongIntValue_ >= 0) && (value_.unsignedLongLongIntValue_ == (unsigned long long)p.value_.longLongIntValue_); + else if ((type_ == "unsigned long long int") && (p.type_ == "int")) + return (p.value_.intValue_ >= 0) && (value_.unsignedLongLongIntValue_ == (unsigned long long)p.value_.intValue_); + else if ((type_ == "int") && (p.type_ == "unsigned long long int")) + return (value_.intValue_ >= 0) && ((unsigned long long)value_.intValue_ == p.value_.unsignedLongLongIntValue_); + else if ((type_ == "unsigned long long int") && (p.type_ == "unsigned int")) + return value_.unsignedLongLongIntValue_ == p.value_.unsignedIntValue_; + else if ((type_ == "unsigned int") && (p.type_ == "unsigned long long int")) + return value_.unsignedIntValue_ == p.value_.unsignedLongLongIntValue_; + else if ((type_ == "unsigned long long int") && (p.type_ == "long int")) + return (p.value_.longIntValue_ >= 0) && (value_.unsignedLongLongIntValue_ == (unsigned long long)p.value_.longIntValue_); + else if ((type_ == "long int") && (p.type_ == "unsigned long long int")) + return (value_.longIntValue_ >= 0) && ((unsigned long long)value_.longIntValue_ == p.value_.unsignedLongLongIntValue_); + else if ((type_ == "unsigned long long int") && (p.type_ == "unsigned long int")) + return value_.unsignedLongLongIntValue_ == p.value_.unsignedLongIntValue_; + else if ((type_ == "unsigned long int") && (p.type_ == "unsigned long long int")) + return value_.unsignedLongIntValue_ == p.value_.unsignedLongLongIntValue_; +#endif if (type_ != p.type_) return false; @@ -290,6 +446,12 @@ bool MockNamedValue::equals(const MockNamedValue& p) const return value_.longIntValue_ == p.value_.longIntValue_; else if (type_ == "unsigned long int") return value_.unsignedLongIntValue_ == p.value_.unsignedLongIntValue_; +#if CPPUTEST_USE_LONG_LONG + else if (type_ == "long long int") + return value_.longLongIntValue_ == p.value_.longLongIntValue_; + else if (type_ == "unsigned long long int") + return value_.unsignedLongLongIntValue_ == p.value_.unsignedLongLongIntValue_; +#endif else if (type_ == "const char*") return SimpleString(value_.stringValue_) == SimpleString(p.value_.stringValue_); else if (type_ == "void*") @@ -299,7 +461,7 @@ bool MockNamedValue::equals(const MockNamedValue& p) const else if (type_ == "void (*)()") return value_.functionPointerValue_ == p.value_.functionPointerValue_; else if (type_ == "double") - return (doubles_equal(value_.doubleValue_, p.value_.doubleValue_, 0.005)); + return (doubles_equal(value_.doubleValue_.value, p.value_.doubleValue_.value, value_.doubleValue_.tolerance)); else if (type_ == "const unsigned char*") { if (size_ != p.size_) { @@ -309,7 +471,7 @@ bool MockNamedValue::equals(const MockNamedValue& p) const } if (comparator_) - return comparator_->isEqual(value_.objectPointerValue_, p.value_.objectPointerValue_); + return comparator_->isEqual(value_.constObjectPointerValue_, p.value_.constObjectPointerValue_); return false; } @@ -329,13 +491,19 @@ SimpleString MockNamedValue::toString() const if (type_ == "bool") return StringFrom(value_.boolValue_); else if (type_ == "int") - return StringFrom(value_.intValue_); + return StringFrom(value_.intValue_) + " " + BracketsFormattedHexStringFrom(value_.intValue_); else if (type_ == "unsigned int") - return StringFrom(value_.unsignedIntValue_); + return StringFrom(value_.unsignedIntValue_) + " " + BracketsFormattedHexStringFrom(value_.unsignedIntValue_); else if (type_ == "long int") - return StringFrom(value_.longIntValue_); + return StringFrom(value_.longIntValue_) + " " + BracketsFormattedHexStringFrom(value_.longIntValue_); else if (type_ == "unsigned long int") - return StringFrom(value_.unsignedLongIntValue_); + return StringFrom(value_.unsignedLongIntValue_) + " " + BracketsFormattedHexStringFrom(value_.unsignedLongIntValue_); +#if CPPUTEST_USE_LONG_LONG + else if (type_ == "long long int") + return StringFrom(value_.longLongIntValue_) + " " + BracketsFormattedHexStringFrom(value_.longLongIntValue_); + else if (type_ == "unsigned long long int") + return StringFrom(value_.unsignedLongLongIntValue_) + " " + BracketsFormattedHexStringFrom(value_.unsignedLongLongIntValue_); +#endif else if (type_ == "const char*") return value_.stringValue_; else if (type_ == "void*") @@ -345,12 +513,12 @@ SimpleString MockNamedValue::toString() const else if (type_ == "const void*") return StringFrom(value_.constPointerValue_); else if (type_ == "double") - return StringFrom(value_.doubleValue_); + return StringFrom(value_.doubleValue_.value); else if (type_ == "const unsigned char*") return StringFromBinaryWithSizeOrNull(value_.memoryBufferValue_, size_); if (comparator_) - return comparator_->valueToString(value_.objectPointerValue_); + return comparator_->valueToString(value_.constObjectPointerValue_); return StringFromFormat("No comparator found for type: \"%s\"", type_.asCharString()); @@ -377,7 +545,7 @@ void MockNamedValueListNode::destroy() } MockNamedValueListNode::MockNamedValueListNode(MockNamedValue* newValue) - : data_(newValue), next_(NULL) + : data_(newValue), next_(NULLPTR) { } @@ -391,7 +559,7 @@ SimpleString MockNamedValueListNode::getType() const return data_->getType(); } -MockNamedValueList::MockNamedValueList() : head_(NULL) +MockNamedValueList::MockNamedValueList() : head_(NULLPTR) { } @@ -408,7 +576,7 @@ void MockNamedValueList::clear() void MockNamedValueList::add(MockNamedValue* newValue) { MockNamedValueListNode* newNode = new MockNamedValueListNode(newValue); - if (head_ == NULL) + if (head_ == NULLPTR) head_ = newNode; else { MockNamedValueListNode* lastNode = head_; @@ -422,7 +590,7 @@ MockNamedValue* MockNamedValueList::getValueByName(const SimpleString& name) for (MockNamedValueListNode * p = head_; p; p = p->next()) if (p->getName() == name) return p->item(); - return NULL; + return NULLPTR; } MockNamedValueListNode* MockNamedValueList::begin() @@ -433,16 +601,18 @@ MockNamedValueListNode* MockNamedValueList::begin() struct MockNamedValueComparatorsAndCopiersRepositoryNode { MockNamedValueComparatorsAndCopiersRepositoryNode(const SimpleString& name, MockNamedValueComparator* comparator, MockNamedValueComparatorsAndCopiersRepositoryNode* next) - : name_(name), comparator_(comparator), copier_(NULL), next_(next) {} + : name_(name), comparator_(comparator), copier_(NULLPTR), next_(next) {} MockNamedValueComparatorsAndCopiersRepositoryNode(const SimpleString& name, MockNamedValueCopier* copier, MockNamedValueComparatorsAndCopiersRepositoryNode* next) - : name_(name), comparator_(NULL), copier_(copier), next_(next) {} + : name_(name), comparator_(NULLPTR), copier_(copier), next_(next) {} + MockNamedValueComparatorsAndCopiersRepositoryNode(const SimpleString& name, MockNamedValueComparator* comparator, MockNamedValueCopier* copier, MockNamedValueComparatorsAndCopiersRepositoryNode* next) + : name_(name), comparator_(comparator), copier_(copier), next_(next) {} SimpleString name_; MockNamedValueComparator* comparator_; MockNamedValueCopier* copier_; MockNamedValueComparatorsAndCopiersRepositoryNode* next_; }; -MockNamedValueComparatorsAndCopiersRepository::MockNamedValueComparatorsAndCopiersRepository() : head_(NULL) +MockNamedValueComparatorsAndCopiersRepository::MockNamedValueComparatorsAndCopiersRepository() : head_(NULLPTR) { } @@ -475,18 +645,18 @@ MockNamedValueComparator* MockNamedValueComparatorsAndCopiersRepository::getComp { for (MockNamedValueComparatorsAndCopiersRepositoryNode* p = head_; p; p = p->next_) if (p->name_ == name && p->comparator_) return p->comparator_; - return NULL; + return NULLPTR; } MockNamedValueCopier* MockNamedValueComparatorsAndCopiersRepository::getCopierForType(const SimpleString& name) { for (MockNamedValueComparatorsAndCopiersRepositoryNode* p = head_; p; p = p->next_) if (p->name_ == name && p->copier_) return p->copier_; - return NULL; + return NULLPTR; } void MockNamedValueComparatorsAndCopiersRepository::installComparatorsAndCopiers(const MockNamedValueComparatorsAndCopiersRepository& repository) { for (MockNamedValueComparatorsAndCopiersRepositoryNode* p = repository.head_; p; p = p->next_) - head_ = new MockNamedValueComparatorsAndCopiersRepositoryNode(p->name_, p->comparator_, head_); + head_ = new MockNamedValueComparatorsAndCopiersRepositoryNode(p->name_, p->comparator_, p->copier_, head_); } diff --git a/src/CppUTestExt/MockSupport.cpp b/src/CppUTestExt/MockSupport.cpp old mode 100755 new mode 100644 index fb307652e..eced71afb --- a/src/CppUTestExt/MockSupport.cpp +++ b/src/CppUTestExt/MockSupport.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -44,9 +44,18 @@ MockSupport& mock(const SimpleString& mockName, MockFailureReporter* failureRepo } MockSupport::MockSupport(const SimpleString& mockName) - : callOrder_(0), expectedCallOrder_(0), strictOrdering_(false), standardReporter_(&defaultReporter_), ignoreOtherCalls_(false), enabled_(true), lastActualFunctionCall_(NULL), mockName_(mockName), tracing_(false) + : + actualCallOrder_(0), + expectedCallOrder_(0), + strictOrdering_(false), + activeReporter_(NULLPTR), + standardReporter_(&defaultReporter_), + ignoreOtherCalls_(false), + enabled_(true), + lastActualFunctionCall_(NULLPTR), + mockName_(mockName), + tracing_(false) { - setActiveReporter(NULL); } MockSupport::~MockSupport() @@ -60,7 +69,7 @@ void MockSupport::crashOnFailure(bool shouldCrash) void MockSupport::setMockFailureStandardReporter(MockFailureReporter* reporter) { - standardReporter_ = (reporter != NULL) ? reporter : &defaultReporter_; + standardReporter_ = (reporter != NULLPTR) ? reporter : &defaultReporter_; if (lastActualFunctionCall_) lastActualFunctionCall_->setMockFailureReporter(standardReporter_); @@ -113,17 +122,15 @@ void MockSupport::removeAllComparatorsAndCopiers() void MockSupport::clear() { delete lastActualFunctionCall_; - lastActualFunctionCall_ = NULL; + lastActualFunctionCall_ = NULLPTR; tracing_ = false; - MockActualCallTrace::instance().clear(); + MockActualCallTrace::clearInstance(); expectations_.deleteAllExpectationsAndClearList(); - unExpectations_.deleteAllExpectationsAndClearList(); - compositeCalls_.clear(); ignoreOtherCalls_ = false; enabled_ = true; - callOrder_ = 0; + actualCallOrder_ = 0; expectedCallOrder_ = 0; strictOrdering_ = false; @@ -150,74 +157,61 @@ SimpleString MockSupport::appendScopeToName(const SimpleString& functionName) MockExpectedCall& MockSupport::expectOneCall(const SimpleString& functionName) { - if (!enabled_) return MockIgnoredExpectedCall::instance(); - - countCheck(); - - MockCheckedExpectedCall* call = new MockCheckedExpectedCall; - call->withName(appendScopeToName(functionName)); - if (strictOrdering_) - call->withCallOrder(++expectedCallOrder_); - expectations_.addExpectedCall(call); - return *call; + return expectNCalls(1, functionName); } void MockSupport::expectNoCall(const SimpleString& functionName) { - if (!enabled_) return; - - countCheck(); - - MockCheckedExpectedCall* call = new MockCheckedExpectedCall; - call->withName(appendScopeToName(functionName)); - unExpectations_.addExpectedCall(call); + expectNCalls(0, functionName); } -MockExpectedCall& MockSupport::expectNCalls(int amount, const SimpleString& functionName) +MockExpectedCall& MockSupport::expectNCalls(unsigned int amount, const SimpleString& functionName) { - compositeCalls_.clear(); + if (!enabled_) return MockIgnoredExpectedCall::instance(); - for (int i = 0; i < amount; i++) - compositeCalls_.add(expectOneCall(functionName)); - return compositeCalls_; -} + countCheck(); -MockCheckedActualCall* MockSupport::createActualFunctionCall() -{ - lastActualFunctionCall_ = new MockCheckedActualCall(++callOrder_, activeReporter_, expectations_); - return lastActualFunctionCall_; + MockCheckedExpectedCall* call = new MockCheckedExpectedCall(amount); + call->withName(appendScopeToName(functionName)); + if (strictOrdering_) { + call->withCallOrder(expectedCallOrder_ + 1, expectedCallOrder_ + amount); + expectedCallOrder_ += amount; + } + expectations_.addExpectedCall(call); + return *call; } -bool MockSupport::hasntExpectationWithName(const SimpleString& functionName) +MockCheckedActualCall* MockSupport::createActualCall() { - return !expectations_.hasExpectationWithName(functionName) && ignoreOtherCalls_; + lastActualFunctionCall_ = new MockCheckedActualCall(++actualCallOrder_, activeReporter_, expectations_); + return lastActualFunctionCall_; } -bool MockSupport::hasntUnexpectationWithName(const SimpleString& functionName) +bool MockSupport::callIsIgnored(const SimpleString& functionName) { - return !unExpectations_.hasExpectationWithName(functionName); + return ignoreOtherCalls_ && !expectations_.hasExpectationWithName(functionName); } MockActualCall& MockSupport::actualCall(const SimpleString& functionName) { - const SimpleString scopeFuntionName = appendScopeToName(functionName); + const SimpleString scopeFunctionName = appendScopeToName(functionName); if (lastActualFunctionCall_) { lastActualFunctionCall_->checkExpectations(); delete lastActualFunctionCall_; - lastActualFunctionCall_ = NULL; + lastActualFunctionCall_ = NULLPTR; } if (!enabled_) return MockIgnoredActualCall::instance(); - if (tracing_) return MockActualCallTrace::instance().withName(scopeFuntionName); + if (tracing_) return MockActualCallTrace::instance().withName(scopeFunctionName); - if (hasntUnexpectationWithName(scopeFuntionName) && hasntExpectationWithName(scopeFuntionName)) { + if (callIsIgnored(scopeFunctionName)) { return MockIgnoredActualCall::instance(); } - MockCheckedActualCall* call = createActualFunctionCall(); - call->withName(scopeFuntionName); + MockCheckedActualCall* call = createActualCall(); + call->withName(scopeFunctionName); return *call; } @@ -260,6 +254,7 @@ const char* MockSupport::getTraceOutput() bool MockSupport::expectedCallsLeft() { + checkExpectationsOfLastActualCall(); int callsLeft = expectations_.hasUnfulfilledExpectations(); for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) @@ -268,19 +263,19 @@ bool MockSupport::expectedCallsLeft() return callsLeft != 0; } -bool MockSupport::wasLastCallFulfilled() +bool MockSupport::wasLastActualCallFulfilled() { if (lastActualFunctionCall_ && !lastActualFunctionCall_->isFulfilled()) return false; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) - if (getMockSupport(p) && !getMockSupport(p)->wasLastCallFulfilled()) + if (getMockSupport(p) && !getMockSupport(p)->wasLastActualCallFulfilled()) return false; return true; } -void MockSupport::failTestWithUnexpectedCalls() +void MockSupport::failTestWithExpectedCallsNotFulfilled() { MockExpectedCallsList expectationsList; expectationsList.addExpectations(expectations_); @@ -290,7 +285,6 @@ void MockSupport::failTestWithUnexpectedCalls() expectationsList.addExpectations(getMockSupport(p)->expectations_); MockExpectedCallsDidntHappenFailure failure(activeReporter_->getTestToFail(), expectationsList); - clear(); failTest(failure); } @@ -304,12 +298,12 @@ void MockSupport::failTestWithOutOfOrderCalls() expectationsList.addExpectations(getMockSupport(p)->expectations_); MockCallOrderFailure failure(activeReporter_->getTestToFail(), expectationsList); - clear(); failTest(failure); } void MockSupport::failTest(MockFailure& failure) { + clear(); activeReporter_->failTest(failure); } @@ -318,7 +312,7 @@ void MockSupport::countCheck() UtestShell::getCurrent()->countCheck(); } -void MockSupport::checkExpectationsOfLastCall() +void MockSupport::checkExpectationsOfLastActualCall() { if(lastActualFunctionCall_) lastActualFunctionCall_->checkExpectations(); @@ -344,10 +338,10 @@ bool MockSupport::hasCallsOutOfOrder() void MockSupport::checkExpectations() { - checkExpectationsOfLastCall(); + checkExpectationsOfLastActualCall(); - if (wasLastCallFulfilled() && expectedCallsLeft()) - failTestWithUnexpectedCalls(); + if (wasLastActualCallFulfilled() && expectedCallsLeft()) + failTestWithExpectedCallsNotFulfilled(); if (hasCallsOutOfOrder()) failTestWithOutOfOrderCalls(); @@ -356,13 +350,13 @@ void MockSupport::checkExpectations() bool MockSupport::hasData(const SimpleString& name) { - return data_.getValueByName(name) != NULL; + return data_.getValueByName(name) != NULLPTR; } MockNamedValue* MockSupport::retrieveDataFromStore(const SimpleString& name) { MockNamedValue* newData = data_.getValueByName(name); - if (newData == NULL) { + if (newData == NULLPTR) { newData = new MockNamedValue(name); data_.add(newData); } @@ -387,6 +381,18 @@ void MockSupport::setData(const SimpleString& name, int value) newData->setValue(value); } +void MockSupport::setData(const SimpleString& name, long int value) +{ + MockNamedValue* newData = retrieveDataFromStore(name); + newData->setValue(value); +} + +void MockSupport::setData(const SimpleString& name, unsigned long int value) +{ + MockNamedValue* newData = retrieveDataFromStore(name); + newData->setValue(value); +} + void MockSupport::setData(const SimpleString& name, const char* value) { MockNamedValue* newData = retrieveDataFromStore(name); @@ -423,10 +429,16 @@ void MockSupport::setDataObject(const SimpleString& name, const SimpleString& ty newData->setObjectPointer(type, value); } +void MockSupport::setDataConstObject(const SimpleString& name, const SimpleString& type, const void* value) +{ + MockNamedValue* newData = retrieveDataFromStore(name); + newData->setConstObjectPointer(type, value); +} + MockNamedValue MockSupport::getData(const SimpleString& name) { MockNamedValue* value = data_.getValueByName(name); - if (value == NULL) + if (value == NULLPTR) return MockNamedValue(""); return *value; } @@ -465,8 +477,8 @@ MockSupport* MockSupport::getMockSupportScope(const SimpleString& name) MockSupport* MockSupport::getMockSupport(MockNamedValueListNode* node) { if (node->getType() == "MockSupport" && node->getName().contains(MOCK_SUPPORT_SCOPE_PREFIX)) - return (MockSupport*) node->item()->getObjectPointer(); - return NULL; + return (MockSupport*) node->item()->getObjectPointer(); + return NULLPTR; } MockNamedValue MockSupport::returnValue() @@ -556,6 +568,64 @@ unsigned long int MockSupport::unsignedLongIntReturnValue() return returnValue().getUnsignedLongIntValue(); } +#if CPPUTEST_USE_LONG_LONG + +cpputest_longlong MockSupport::longLongIntReturnValue() +{ + return returnValue().getLongLongIntValue(); +} + +cpputest_ulonglong MockSupport::unsignedLongLongIntReturnValue() +{ + return returnValue().getUnsignedLongLongIntValue(); +} + +cpputest_longlong MockSupport::returnLongLongIntValueOrDefault(cpputest_longlong defaultValue) +{ + if (hasReturnValue()) { + return longLongIntReturnValue(); + } + return defaultValue; +} + +cpputest_ulonglong MockSupport::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong defaultValue) +{ + if (hasReturnValue()) { + return unsignedLongLongIntReturnValue(); + } + return defaultValue; +} + +#else + +cpputest_longlong MockSupport::longLongIntReturnValue() +{ + FAIL("Long Long type is not supported"); + cpputest_longlong ret = {}; + return ret; +} + +cpputest_ulonglong MockSupport::unsignedLongLongIntReturnValue() +{ + FAIL("Unsigned Long Long type is not supported"); + cpputest_ulonglong ret = {}; + return ret; +} + +cpputest_longlong MockSupport::returnLongLongIntValueOrDefault(cpputest_longlong defaultValue) +{ + FAIL("Long Long type is not supported"); + return defaultValue; +} + +cpputest_ulonglong MockSupport::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong defaultValue) +{ + FAIL("Unsigned Long Long type is not supported"); + return defaultValue; +} + +#endif + const char* MockSupport::stringReturnValue() { return returnValue().getStringValue(); diff --git a/src/CppUTestExt/MockSupportPlugin.cpp b/src/CppUTestExt/MockSupportPlugin.cpp index b2f97f9f6..e484c466c 100644 --- a/src/CppUTestExt/MockSupportPlugin.cpp +++ b/src/CppUTestExt/MockSupportPlugin.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -39,12 +39,12 @@ class MockSupportPluginReporter : public MockFailureReporter { } - virtual void failTest(const MockFailure& failure) _override + virtual void failTest(const MockFailure& failure) CPPUTEST_OVERRIDE { result_.addFailure(failure); } - virtual UtestShell* getTestToFail() _override + virtual UtestShell* getTestToFail() CPPUTEST_OVERRIDE { return &test_; } @@ -56,6 +56,11 @@ MockSupportPlugin::MockSupportPlugin(const SimpleString& name) } MockSupportPlugin::~MockSupportPlugin() +{ + clear(); +} + +void MockSupportPlugin::clear() { repository_.clear(); } @@ -72,7 +77,7 @@ void MockSupportPlugin::postTestAction(UtestShell& test, TestResult& result) if (!test.hasFailed()) mock().checkExpectations(); mock().clear(); - mock().setMockFailureStandardReporter(NULL); + mock().setMockFailureStandardReporter(NULLPTR); mock().removeAllComparatorsAndCopiers(); } diff --git a/src/CppUTestExt/MockSupport_c.cpp b/src/CppUTestExt/MockSupport_c.cpp index 69145b7de..640f4b93d 100644 --- a/src/CppUTestExt/MockSupport_c.cpp +++ b/src/CppUTestExt/MockSupport_c.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,22 +34,22 @@ typedef void (*cpputest_cpp_function_pointer)(); /* Cl2000 requires cast to C++ function */ -class MockFailureReporterTestTerminatorForInCOnlyCode : public TestTerminatorWithoutExceptions +class MockFailureReporterTestTerminatorForInCOnlyCode : public TestTerminator { public: MockFailureReporterTestTerminatorForInCOnlyCode(bool crashOnFailure) : crashOnFailure_(crashOnFailure) { } - virtual void exitCurrentTest() const _override + virtual void exitCurrentTest() const CPPUTEST_OVERRIDE { if (crashOnFailure_) UT_CRASH(); - TestTerminatorWithoutExceptions::exitCurrentTest(); + UtestShell::getCurrentTestTerminatorWithoutExceptions().exitCurrentTest(); } // LCOV_EXCL_LINE // LCOV_EXCL_START - virtual ~MockFailureReporterTestTerminatorForInCOnlyCode() + virtual ~MockFailureReporterTestTerminatorForInCOnlyCode() CPPUTEST_DESTRUCTOR_OVERRIDE { } // LCOV_EXCL_STOP @@ -61,7 +61,7 @@ class MockFailureReporterTestTerminatorForInCOnlyCode : public TestTerminatorWit class MockFailureReporterForInCOnlyCode : public MockFailureReporter { public: - void failTest(const MockFailure& failure) _override + void failTest(const MockFailure& failure) CPPUTEST_OVERRIDE { if (!getTestToFail()->hasFailed()) getTestToFail()->failWith(failure, MockFailureReporterTestTerminatorForInCOnlyCode(crashOnFailure_)); @@ -69,9 +69,9 @@ class MockFailureReporterForInCOnlyCode : public MockFailureReporter }; -static MockSupport* currentMockSupport = NULL; -static MockExpectedCall* expectedCall = NULL; -static MockActualCall* actualCall = NULL; +static MockSupport* currentMockSupport = NULLPTR; +static MockExpectedCall* expectedCall = NULLPTR; +static MockActualCall* actualCall = NULLPTR; static MockFailureReporterForInCOnlyCode failureReporterForC; class MockCFunctionComparatorNode : public MockNamedValueComparator @@ -79,13 +79,13 @@ class MockCFunctionComparatorNode : public MockNamedValueComparator public: MockCFunctionComparatorNode(MockCFunctionComparatorNode* next, MockTypeEqualFunction_c equal, MockTypeValueToStringFunction_c toString) : next_(next), equal_(equal), toString_(toString) {} - virtual ~MockCFunctionComparatorNode() {} + virtual ~MockCFunctionComparatorNode() CPPUTEST_DESTRUCTOR_OVERRIDE {} - virtual bool isEqual(const void* object1, const void* object2) _override + virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { return equal_(object1, object2) != 0; } - virtual SimpleString valueToString(const void* object) _override + virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { return SimpleString(toString_(object)); } @@ -95,16 +95,16 @@ class MockCFunctionComparatorNode : public MockNamedValueComparator MockTypeValueToStringFunction_c toString_; }; -static MockCFunctionComparatorNode* comparatorList_ = NULL; +static MockCFunctionComparatorNode* comparatorList_ = NULLPTR; class MockCFunctionCopierNode : public MockNamedValueCopier { public: MockCFunctionCopierNode(MockCFunctionCopierNode* next, MockTypeCopyFunction_c copier) : next_(next), copier_(copier) {} - virtual ~MockCFunctionCopierNode() {} + virtual ~MockCFunctionCopierNode() CPPUTEST_DESTRUCTOR_OVERRIDE {} - virtual void copy(void* dst, const void* src) _override + virtual void copy(void* dst, const void* src) CPPUTEST_OVERRIDE { copier_(dst, src); } @@ -113,14 +113,14 @@ class MockCFunctionCopierNode : public MockNamedValueCopier MockTypeCopyFunction_c copier_; }; -static MockCFunctionCopierNode* copierList_ = NULL; +static MockCFunctionCopierNode* copierList_ = NULLPTR; extern "C" { void strictOrder_c(); MockExpectedCall_c* expectOneCall_c(const char* name); void expectNoCall_c(const char* name); -MockExpectedCall_c* expectNCalls_c(const int number, const char* name); +MockExpectedCall_c* expectNCalls_c(const unsigned int number, const char* name); MockActualCall_c* actualCall_c(const char* name); void disable_c(); void enable_c(); @@ -128,12 +128,15 @@ void ignoreOtherCalls_c(); void setBoolData_c(const char* name, int value); void setIntData_c(const char* name, int value); void setUnsignedIntData_c(const char* name, unsigned int value); +void setLongIntData_c(const char* name, long int value); +void setUnsignedLongIntData_c(const char* name, unsigned long int value); void setDoubleData_c(const char* name, double value); void setStringData_c(const char* name, const char* value); void setPointerData_c(const char* name, void* value); void setConstPointerData_c(const char* name, const void* value); void setFunctionPointerData_c(const char* name, void (*value)()); void setDataObject_c(const char* name, const char* type, void* value); +void setDataConstObject_c(const char* name, const char* type, const void* value); MockValue_c getData_c(const char* name); int hasReturnValue_c(); @@ -147,7 +150,10 @@ MockExpectedCall_c* withIntParameters_c(const char* name, int value); MockExpectedCall_c* withUnsignedIntParameters_c(const char* name, unsigned int value); MockExpectedCall_c* withLongIntParameters_c(const char* name, long int value); MockExpectedCall_c* withUnsignedLongIntParameters_c(const char* name, unsigned long int value); +MockExpectedCall_c* withLongLongIntParameters_c(const char* name, cpputest_longlong value); +MockExpectedCall_c* withUnsignedLongLongIntParameters_c(const char* name, cpputest_ulonglong value); MockExpectedCall_c* withDoubleParameters_c(const char* name, double value); +MockExpectedCall_c* withDoubleParametersAndTolerance_c(const char* name, double value, double tolerance); MockExpectedCall_c* withStringParameters_c(const char* name, const char* value); MockExpectedCall_c* withPointerParameters_c(const char* name, void* value); MockExpectedCall_c* withConstPointerParameters_c(const char* name, const void* value); @@ -156,12 +162,15 @@ MockExpectedCall_c* withMemoryBufferParameters_c(const char* name, const unsigne MockExpectedCall_c* withParameterOfType_c(const char* type, const char* name, const void* value); MockExpectedCall_c* withOutputParameterReturning_c(const char* name, const void* value, size_t size); MockExpectedCall_c* withOutputParameterOfTypeReturning_c(const char* type, const char* name, const void* value); +MockExpectedCall_c* withUnmodifiedOutputParameter_c(const char* name); MockExpectedCall_c* ignoreOtherParameters_c(); MockExpectedCall_c* andReturnBoolValue_c(int value); MockExpectedCall_c* andReturnIntValue_c(int value); MockExpectedCall_c* andReturnUnsignedIntValue_c(unsigned int value); MockExpectedCall_c* andReturnLongIntValue_c(long int value); MockExpectedCall_c* andReturnUnsignedLongIntValue_c(unsigned long int value); +MockExpectedCall_c* andReturnLongLongIntValue_c(cpputest_longlong value); +MockExpectedCall_c* andReturnUnsignedLongLongIntValue_c(cpputest_ulonglong value); MockExpectedCall_c* andReturnDoubleValue_c(double value); MockExpectedCall_c* andReturnStringValue_c(const char* value); MockExpectedCall_c* andReturnPointerValue_c(void* value); @@ -173,6 +182,8 @@ MockActualCall_c* withActualIntParameters_c(const char* name, int value); MockActualCall_c* withActualUnsignedIntParameters_c(const char* name, unsigned int value); MockActualCall_c* withActualLongIntParameters_c(const char* name, long int value); MockActualCall_c* withActualUnsignedLongIntParameters_c(const char* name, unsigned long int value); +MockActualCall_c* withActualLongLongIntParameters_c(const char* name, cpputest_longlong value); +MockActualCall_c* withActualUnsignedLongLongIntParameters_c(const char* name, cpputest_ulonglong value); MockActualCall_c* withActualDoubleParameters_c(const char* name, double value); MockActualCall_c* withActualStringParameters_c(const char* name, const char* value); MockActualCall_c* withActualPointerParameters_c(const char* name, void* value); @@ -193,6 +204,10 @@ long int longIntReturnValue_c(); long int returnLongIntValueOrDefault_c(long int defaultValue); unsigned long int unsignedLongIntReturnValue_c(); unsigned long int returnUnsignedLongIntValueOrDefault_c(unsigned long int defaultValue); +cpputest_longlong longLongIntReturnValue_c(); +cpputest_longlong returnLongLongIntValueOrDefault_c(cpputest_longlong defaultValue); +cpputest_ulonglong unsignedLongLongIntReturnValue_c(); +cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault_c(cpputest_ulonglong defaultValue); const char* stringReturnValue_c(); const char* returnStringValueOrDefault_c(const char * defaultValue); double doubleReturnValue_c(); @@ -237,7 +252,10 @@ static MockExpectedCall_c gExpectedCall = { withUnsignedIntParameters_c, withLongIntParameters_c, withUnsignedLongIntParameters_c, + withLongLongIntParameters_c, + withUnsignedLongLongIntParameters_c, withDoubleParameters_c, + withDoubleParametersAndTolerance_c, withStringParameters_c, withPointerParameters_c, withConstPointerParameters_c, @@ -246,12 +264,15 @@ static MockExpectedCall_c gExpectedCall = { withParameterOfType_c, withOutputParameterReturning_c, withOutputParameterOfTypeReturning_c, + withUnmodifiedOutputParameter_c, ignoreOtherParameters_c, andReturnBoolValue_c, andReturnUnsignedIntValue_c, andReturnIntValue_c, andReturnLongIntValue_c, andReturnUnsignedLongIntValue_c, + andReturnLongLongIntValue_c, + andReturnUnsignedLongLongIntValue_c, andReturnDoubleValue_c, andReturnStringValue_c, andReturnPointerValue_c, @@ -265,6 +286,8 @@ static MockActualCall_c gActualCall = { withActualUnsignedIntParameters_c, withActualLongIntParameters_c, withActualUnsignedLongIntParameters_c, + withActualLongLongIntParameters_c, + withActualUnsignedLongLongIntParameters_c, withActualDoubleParameters_c, withActualStringParameters_c, withActualPointerParameters_c, @@ -286,6 +309,10 @@ static MockActualCall_c gActualCall = { returnLongIntValueOrDefault_c, unsignedLongIntReturnValue_c, returnUnsignedLongIntValueOrDefault_c, + longLongIntReturnValue_c, + returnLongLongIntValueOrDefault_c, + unsignedLongLongIntReturnValue_c, + returnUnsignedLongLongIntValueOrDefault_c, stringReturnValue_c, returnStringValueOrDefault_c, doubleReturnValue_c, @@ -316,6 +343,10 @@ static MockSupport_c gMockSupport = { returnLongIntValueOrDefault_c, unsignedLongIntReturnValue_c, returnUnsignedLongIntValueOrDefault_c, + longLongIntReturnValue_c, + returnLongLongIntValueOrDefault_c, + unsignedLongLongIntReturnValue_c, + returnUnsignedLongLongIntValueOrDefault_c, stringReturnValue_c, returnStringValueOrDefault_c, doubleReturnValue_c, @@ -329,12 +360,15 @@ static MockSupport_c gMockSupport = { setBoolData_c, setIntData_c, setUnsignedIntData_c, + setLongIntData_c, + setUnsignedLongIntData_c, setStringData_c, setDoubleData_c, setPointerData_c, setConstPointerData_c, setFunctionPointerData_c, setDataObject_c, + setDataConstObject_c, getData_c, disable_c, enable_c, @@ -378,12 +412,48 @@ MockExpectedCall_c* withUnsignedLongIntParameters_c(const char* name, unsigned l return &gExpectedCall; } +#if CPPUTEST_USE_LONG_LONG + +MockExpectedCall_c* withLongLongIntParameters_c(const char* name, cpputest_longlong value) +{ + expectedCall = &expectedCall->withParameter(name, value); + return &gExpectedCall; +} + +MockExpectedCall_c* withUnsignedLongLongIntParameters_c(const char* name, cpputest_ulonglong value) +{ + expectedCall = &expectedCall->withParameter(name, value); + return &gExpectedCall; +} + +#else + +MockExpectedCall_c* withLongLongIntParameters_c(const char*, cpputest_longlong) +{ + FAIL("Long Long type is not supported"); + return &gExpectedCall; +} + +MockExpectedCall_c* withUnsignedLongLongIntParameters_c(const char*, cpputest_ulonglong) +{ + FAIL("Unsigned Long Long type is not supported"); + return &gExpectedCall; +} + +#endif + MockExpectedCall_c* withDoubleParameters_c(const char* name, double value) { expectedCall = &expectedCall->withParameter(name, value); return &gExpectedCall; } +MockExpectedCall_c* withDoubleParametersAndTolerance_c(const char* name, double value, double tolerance) +{ + expectedCall = &expectedCall->withParameter(name, value, tolerance); + return &gExpectedCall; +} + MockExpectedCall_c* withStringParameters_c(const char* name, const char* value) { expectedCall = &expectedCall->withParameter(name, value); @@ -432,6 +502,12 @@ MockExpectedCall_c* withOutputParameterOfTypeReturning_c(const char* type, const return &gExpectedCall; } +MockExpectedCall_c* withUnmodifiedOutputParameter_c(const char* name) +{ + expectedCall = &expectedCall->withUnmodifiedOutputParameter(name); + return &gExpectedCall; +} + MockExpectedCall_c* ignoreOtherParameters_c() { expectedCall = &expectedCall->ignoreOtherParameters(); @@ -468,6 +544,36 @@ MockExpectedCall_c* andReturnUnsignedLongIntValue_c(unsigned long int value) return &gExpectedCall; } +#if CPPUTEST_USE_LONG_LONG + +MockExpectedCall_c* andReturnLongLongIntValue_c(cpputest_longlong value) +{ + expectedCall = &expectedCall->andReturnValue(value); + return &gExpectedCall; +} + +MockExpectedCall_c* andReturnUnsignedLongLongIntValue_c(cpputest_ulonglong value) +{ + expectedCall = &expectedCall->andReturnValue(value); + return &gExpectedCall; +} + +#else + +MockExpectedCall_c* andReturnLongLongIntValue_c(cpputest_longlong) +{ + FAIL("Long Long type is not supported"); + return &gExpectedCall; +} + +MockExpectedCall_c* andReturnUnsignedLongLongIntValue_c(cpputest_ulonglong) +{ + FAIL("Unsigned Long Long type is not supported"); + return &gExpectedCall; +} + +#endif + MockExpectedCall_c* andReturnDoubleValue_c(double value) { expectedCall = &expectedCall->andReturnValue(value); @@ -521,6 +627,16 @@ static MockValue_c getMockValueCFromNamedValue(const MockNamedValue& namedValue) returnValue.type = MOCKVALUETYPE_UNSIGNED_LONG_INTEGER; returnValue.value.unsignedLongIntValue = namedValue.getUnsignedLongIntValue(); } +#if CPPUTEST_USE_LONG_LONG + else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "long long int") == 0) { + returnValue.type = MOCKVALUETYPE_LONG_LONG_INTEGER; + returnValue.value.longLongIntValue = namedValue.getLongLongIntValue(); + } + else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "unsigned long long int") == 0) { + returnValue.type = MOCKVALUETYPE_UNSIGNED_LONG_LONG_INTEGER; + returnValue.value.unsignedLongLongIntValue = namedValue.getUnsignedLongLongIntValue(); + } +#endif else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "double") == 0) { returnValue.type = MOCKVALUETYPE_DOUBLE; returnValue.value.doubleValue = namedValue.getDoubleValue(); @@ -568,7 +684,7 @@ void expectNoCall_c(const char* name) currentMockSupport->expectNoCall(name); } -MockExpectedCall_c* expectNCalls_c(const int number, const char* name) +MockExpectedCall_c* expectNCalls_c(const unsigned int number, const char* name) { expectedCall = ¤tMockSupport->expectNCalls(number, name); return &gExpectedCall; @@ -610,6 +726,36 @@ MockActualCall_c* withActualUnsignedLongIntParameters_c(const char* name, unsign return &gActualCall; } +#if CPPUTEST_USE_LONG_LONG + +MockActualCall_c* withActualLongLongIntParameters_c(const char* name, cpputest_longlong value) +{ + actualCall = &actualCall->withParameter(name, value); + return &gActualCall; +} + +MockActualCall_c* withActualUnsignedLongLongIntParameters_c(const char* name, cpputest_ulonglong value) +{ + actualCall = &actualCall->withParameter(name, value); + return &gActualCall; +} + +#else + +MockActualCall_c* withActualLongLongIntParameters_c(const char*, cpputest_longlong) +{ + FAIL("Long Long type is not supported"); + return &gActualCall; +} + +MockActualCall_c* withActualUnsignedLongLongIntParameters_c(const char*, cpputest_ulonglong) +{ + FAIL("Unsigned Long Long type is not supported"); + return &gActualCall; +} + +#endif + MockActualCall_c* withActualDoubleParameters_c(const char* name, double value) { actualCall = &actualCall->withParameter(name, value); @@ -734,6 +880,66 @@ unsigned long int returnUnsignedLongIntValueOrDefault_c(unsigned long int defaul return unsignedLongIntReturnValue_c(); } +#if CPPUTEST_USE_LONG_LONG + +cpputest_longlong longLongIntReturnValue_c() +{ + return actualCall->returnLongLongIntValue(); +} + +cpputest_longlong returnLongLongIntValueOrDefault_c(cpputest_longlong defaultValue) +{ + if (!hasReturnValue_c()) { + return defaultValue; + } + return longLongIntReturnValue_c(); +} + +cpputest_ulonglong unsignedLongLongIntReturnValue_c() +{ + return actualCall->returnUnsignedLongLongIntValue(); +} + +cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault_c(cpputest_ulonglong defaultValue) +{ + if (!hasReturnValue_c()) { + return defaultValue; + } + return unsignedLongLongIntReturnValue_c(); +} + +#else + +cpputest_longlong longLongIntReturnValue_c() +{ + FAIL("Long Long type is not supported"); + cpputest_longlong ret = {}; + return ret; +} + +cpputest_longlong returnLongLongIntValueOrDefault_c(cpputest_longlong) +{ + FAIL("Long Long type is not supported"); + cpputest_longlong ret = {}; + return ret; +} + +cpputest_ulonglong unsignedLongLongIntReturnValue_c() +{ + FAIL("Unsigned Long Long type is not supported"); + cpputest_ulonglong ret = {}; + return ret; +} + +cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault_c(cpputest_ulonglong) +{ + FAIL("Unsigned Long Long type is not supported"); + cpputest_ulonglong ret = {}; + return ret; +} + +#endif + const char* stringReturnValue_c() { return actualCall->returnStringValue(); @@ -829,6 +1035,16 @@ void setUnsignedIntData_c(const char* name, unsigned int value) currentMockSupport->setData(name, value); } +void setLongIntData_c(const char* name, long int value) +{ + currentMockSupport->setData(name, value); +} + +void setUnsignedLongIntData_c(const char* name, unsigned long int value) +{ + currentMockSupport->setData(name, value); +} + void setDoubleData_c(const char* name, double value) { currentMockSupport->setData(name, value); @@ -859,6 +1075,11 @@ void setDataObject_c(const char* name, const char* type, void* value) currentMockSupport->setDataObject(name, type, value); } +void setDataConstObject_c(const char* name, const char* type, const void* value) +{ + currentMockSupport->setDataConstObject(name, type, value); +} + MockValue_c getData_c(const char* name) { return getMockValueCFromNamedValue(currentMockSupport->getData(name)); diff --git a/src/CppUTestExt/OrderedTest.cpp b/src/CppUTestExt/OrderedTest.cpp index a58dd5582..50d0b3440 100644 --- a/src/CppUTestExt/OrderedTest.cpp +++ b/src/CppUTestExt/OrderedTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -29,10 +29,10 @@ #include "CppUTest/TestRegistry.h" #include "CppUTestExt/OrderedTest.h" -OrderedTestShell* OrderedTestShell::_orderedTestsHead = 0; +OrderedTestShell* OrderedTestShell::_orderedTestsHead = NULLPTR; OrderedTestShell::OrderedTestShell() : - _nextOrderedTest(0), _level(0) + _nextOrderedTest(NULLPTR), _level(0) { } @@ -62,7 +62,7 @@ OrderedTestShell* OrderedTestShell::getOrderedTestHead() bool OrderedTestShell::firstOrderedTest() { - return (getOrderedTestHead() == 0); + return (getOrderedTestHead() == NULLPTR); } OrderedTestShell* OrderedTestShell::addOrderedTest(OrderedTestShell* test) @@ -77,7 +77,7 @@ void OrderedTestShell::addOrderedTestToHead(OrderedTestShell* test) TestRegistry *reg = TestRegistry::getCurrentRegistry(); UtestShell* head = getOrderedTestHead(); - if (NULL == reg->getFirstTest() || head == reg->getFirstTest()) { + if (NULLPTR == reg->getFirstTest() || head == reg->getFirstTest()) { reg->addTest(test); } else { @@ -96,7 +96,7 @@ OrderedTestShell* OrderedTestShell::getNextOrderedTest() OrderedTestInstaller::OrderedTestInstaller(OrderedTestShell& test, const char* groupName, const char* testName, const char* fileName, - int lineNumber, int level) + size_t lineNumber, int level) { test.setTestName(testName); test.setGroupName(groupName); diff --git a/src/Platforms/Borland/UtestPlatform.cpp b/src/Platforms/Borland/UtestPlatform.cpp new file mode 100644 index 000000000..3a09a3e68 --- /dev/null +++ b/src/Platforms/Borland/UtestPlatform.cpp @@ -0,0 +1,332 @@ +/* + * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "CppUTest/TestHarness.h" +#undef malloc +#undef free +#undef calloc +#undef realloc +#undef strdup +#undef strndup + +#ifdef CPPUTEST_HAVE_GETTIMEOFDAY +#include +#endif +#if defined(CPPUTEST_HAVE_FORK) && defined(CPPUTEST_HAVE_WAITPID) && defined(CPPUTEST_HAVE_KILL) +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK +#include +#endif + +#include "CppUTest/PlatformSpecificFunctions.h" + +const std::nothrow_t std::nothrow; + +static jmp_buf test_exit_jmp_buf[10]; +static int jmp_buf_index = 0; + +// There is a possibility that a compiler provides fork but not waitpid. +// TODO consider using spawn() and cwait()? +#if !defined(CPPUTEST_HAVE_FORK) || !defined(CPPUTEST_HAVE_WAITPID) || !defined(CPPUTEST_HAVE_KILL) + +static void BorlandPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result) +{ + result->addFailure(TestFailure(shell, "-p doesn't work on this platform, as it is lacking fork.\b")); +} + +static int PlatformSpecificForkImplementation(void) +{ + return 0; +} + +static int PlatformSpecificWaitPidImplementation(int, int*, int) +{ + return 0; +} + +#else + +static void SetTestFailureByStatusCode(UtestShell* shell, TestResult* result, int status) +{ + if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { + result->addFailure(TestFailure(shell, "Failed in separate process")); + } else if (WIFSIGNALED(status)) { + SimpleString message("Failed in separate process - killed by signal "); + message += StringFrom(WTERMSIG(status)); + result->addFailure(TestFailure(shell, message)); + } else if (WIFSTOPPED(status)) { + result->addFailure(TestFailure(shell, "Stopped in separate process - continuing")); + } +} + +static void BorlandPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) +{ + const pid_t syscallError = -1; + pid_t cpid; + pid_t w; + int status = 0; + + cpid = PlatformSpecificFork(); + + if (cpid == syscallError) { + result->addFailure(TestFailure(shell, "Call to fork() failed")); + return; + } + + if (cpid == 0) { /* Code executed by child */ + const size_t initialFailureCount = result->getFailureCount(); // LCOV_EXCL_LINE + shell->runOneTestInCurrentProcess(plugin, *result); // LCOV_EXCL_LINE + _exit(initialFailureCount < result->getFailureCount()); // LCOV_EXCL_LINE + } else { /* Code executed by parent */ + size_t amountOfRetries = 0; + do { + w = PlatformSpecificWaitPid(cpid, &status, WUNTRACED); + if (w == syscallError) { + // OS X debugger causes EINTR + if (EINTR == errno) { + if (amountOfRetries > 30) { + result->addFailure(TestFailure(shell, "Call to waitpid() failed with EINTR. Tried 30 times and giving up! Sometimes happens in debugger")); + return; + } + amountOfRetries++; + } + else { + result->addFailure(TestFailure(shell, "Call to waitpid() failed")); + return; + } + } else { + SetTestFailureByStatusCode(shell, result, status); + if (WIFSTOPPED(status)) kill(w, SIGCONT); + } + } while ((w == syscallError) || (!WIFEXITED(status) && !WIFSIGNALED(status))); + } +} + +static pid_t PlatformSpecificForkImplementation(void) +{ + return fork(); +} + +static pid_t PlatformSpecificWaitPidImplementation(int pid, int* status, int options) +{ + return waitpid(pid, status, options); +} + +#endif + +TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() +{ + return TestOutput::eclipse; +} + +void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) = + BorlandPlatformSpecificRunTestInASeperateProcess; +int (*PlatformSpecificFork)(void) = PlatformSpecificForkImplementation; +int (*PlatformSpecificWaitPid)(int, int*, int) = PlatformSpecificWaitPidImplementation; + +extern "C" { + +static int PlatformSpecificSetJmpImplementation(void (*function) (void* data), void* data) +{ + if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { + jmp_buf_index++; + function(data); + jmp_buf_index--; + return 1; + } + return 0; +} + +static void PlatformSpecificLongJmpImplementation() +{ + jmp_buf_index--; + longjmp(test_exit_jmp_buf[jmp_buf_index], 1); +} + +static void PlatformSpecificRestoreJumpBufferImplementation() +{ + jmp_buf_index--; +} + +void (*PlatformSpecificLongJmp)() = PlatformSpecificLongJmpImplementation; +int (*PlatformSpecificSetJmp)(void (*)(void*), void*) = PlatformSpecificSetJmpImplementation; +void (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferImplementation; + +///////////// Time in millis + +static unsigned long TimeInMillisImplementation() +{ +#ifdef CPPUTEST_HAVE_GETTIMEOFDAY + struct timeval tv; + gettimeofday(&tv, NULL); + return ((unsigned long)tv.tv_sec * 1000) + ((unsigned long)tv.tv_usec / 1000)); +#else + return 0; +#endif +} + +static const char* TimeStringImplementation() +{ + time_t theTime = time(NULLPTR); + static char dateTime[80]; + struct tm *tmp = localtime(&theTime); + strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp); + return dateTime; +} + +unsigned long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; +const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation; + +static int BorlandVSNprintf(char *str, size_t size, const char* format, va_list args) +{ + int result = vsnprintf( str, size, format, args); + str[size-1] = 0; + return result; +} + +int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = BorlandVSNprintf; + +static PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag) +{ + return fopen(filename, flag); +} + +static void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file) +{ + fputs(str, (FILE*)file); +} + +static void PlatformSpecificFCloseImplementation(PlatformSpecificFile file) +{ + fclose((FILE*)file); +} + +static void PlatformSpecificFlushImplementation() +{ + fflush(stdout); +} + +PlatformSpecificFile PlatformSpecificStdOut = stdout; +PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation; +void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation; +void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation; + +void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation; + +void* (*PlatformSpecificMalloc)(size_t size) = malloc; +void* (*PlatformSpecificRealloc)(void*, size_t) = realloc; +void (*PlatformSpecificFree)(void* memory) = free; +void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = memcpy; +void* (*PlatformSpecificMemset)(void*, int, size_t) = memset; + +static int IsNanImplementation(double d) +{ + return _isnan(d); +} + +static int IsInfImplementation(double d) +{ + return !(_finite(d) || _isnan(d)); +} + +double (*PlatformSpecificFabs)(double) = fabs; +void (*PlatformSpecificSrand)(unsigned int) = srand; +int (*PlatformSpecificRand)(void) = rand; +int (*PlatformSpecificIsNan)(double) = IsNanImplementation; +int (*PlatformSpecificIsInf)(double) = IsInfImplementation; +int (*PlatformSpecificAtExit)(void(*func)(void)) = atexit; /// this was undefined before + +static PlatformSpecificMutex PThreadMutexCreate(void) +{ +#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK + pthread_mutex_t *mutex = new pthread_mutex_t; + + pthread_mutex_init(mutex, NULLPTR); + return (PlatformSpecificMutex)mutex; +#else + return NULLPTR; +#endif + +} + +#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK +static void PThreadMutexLock(PlatformSpecificMutex mtx) +{ + pthread_mutex_lock((pthread_mutex_t *)mtx); +} +#else +static void PThreadMutexLock(PlatformSpecificMutex) +{ +} +#endif + +#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK +static void PThreadMutexUnlock(PlatformSpecificMutex mtx) +{ + pthread_mutex_unlock((pthread_mutex_t *)mtx); +} +#else +static void PThreadMutexUnlock(PlatformSpecificMutex) +{ +} +#endif + +#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK +static void PThreadMutexDestroy(PlatformSpecificMutex mtx) +{ + pthread_mutex_t *mutex = (pthread_mutex_t *)mtx; + pthread_mutex_destroy(mutex); + delete mutex; +} +#else +static void PThreadMutexDestroy(PlatformSpecificMutex) +{ +} +#endif + +PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = PThreadMutexCreate; +void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = PThreadMutexLock; +void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = PThreadMutexUnlock; +void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = PThreadMutexDestroy; +void (*PlatformSpecificAbort)(void) = abort; + +} diff --git a/src/Platforms/C2000/UtestPlatform.cpp b/src/Platforms/C2000/UtestPlatform.cpp index 46498f572..558245c5d 100644 --- a/src/Platforms/C2000/UtestPlatform.cpp +++ b/src/Platforms/C2000/UtestPlatform.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,8 +34,10 @@ #undef free #undef calloc #undef realloc - +#undef strdup +#undef strndup #define far // eliminate "meaningless type qualifier" warning +extern "C" { #include #include #include @@ -43,8 +45,8 @@ #include #include #include +} #undef far - #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; @@ -98,7 +100,7 @@ int (*PlatformSpecificSetJmp)(void (*function) (void*), void*) = C2000SetJmp; void (*PlatformSpecificLongJmp)(void) = C2000LongJmp; void (*PlatformSpecificRestoreJumpBuffer)(void) = C2000RestoreJumpBuffer; -static long C2000TimeInMillis() +static unsigned long C2000TimeInMillis() { /* The TI c2000 platform does not have Posix support and thus lacks struct timespec. * Also, clock() always returns 0 in the simulator. Hence we work with struct tm.tm_hour @@ -110,7 +112,7 @@ static long C2000TimeInMillis() */ time_t t = time((time_t*)0); struct tm * ptm = gmtime(&t); - long result = (long) + unsigned long result = (unsigned long) ((ptm->tm_sec + ptm->tm_min * (time_t)60 + ptm->tm_hour * (time_t)3600) * (time_t)1000); return result; } @@ -121,7 +123,7 @@ static const char* TimeStringImplementation() return ctime(&tm); } -long (*GetPlatformSpecificTimeInMillis)() = C2000TimeInMillis; +unsigned long (*GetPlatformSpecificTimeInMillis)() = C2000TimeInMillis; const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation; extern int vsnprintf(char*, size_t, const char*, va_list); // not std::vsnprintf() @@ -135,7 +137,17 @@ PlatformSpecificFile C2000FOpen(const char* filename, const char* flag) static void C2000FPuts(const char* str, PlatformSpecificFile file) { - fputs(str, (FILE*)file); +#if USE_BUFFER_OUTPUT + if (file == PlatformSpecificStdOut) { + while (*str && (idx < BUFFER_SIZE)) { + buf[idx++] = *str++; + } + } + else +#endif + { + fputs(str, (FILE*)file); + } } static void C2000FClose(PlatformSpecificFile file) @@ -143,53 +155,36 @@ static void C2000FClose(PlatformSpecificFile file) fclose((FILE*)file); } +PlatformSpecificFile PlatformSpecificStdOut = stdout; PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = C2000FOpen; void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = C2000FPuts; void (*PlatformSpecificFClose)(PlatformSpecificFile file) = C2000FClose; -static int CL2000Putchar(int c) -{ -#if USE_BUFFER_OUTPUT - if(idx < BUFFER_SIZE) { - buffer[idx] = (char) c; - idx++; - /* "buffer[idx]" instead of "c" eliminates "never used" warning */ - return (buffer[idx]); - } - else { - return EOF; - } -#else - return putchar(c); -#endif -} - static void CL2000Flush() { fflush(stdout); } -extern int (*PlatformSpecificPutchar)(int c) = CL2000Putchar; extern void (*PlatformSpecificFlush)(void) = CL2000Flush; static void* C2000Malloc(size_t size) { - return (void*)far_malloc((unsigned long)size); + return (void*)malloc((unsigned long)size); } static void* C2000Realloc (void* memory, size_t size) { - return (void*)far_realloc((long)memory, (unsigned long)size); + return (void*)realloc(memory, (unsigned long)size); } static void C2000Free(void* memory) { - far_free((long)memory); + free(memory); } static void* C2000MemCpy(void* s1, const void* s2, size_t size) { - return (void*)far_memlcpy((long)s1, (long)s2, size); + return (void*)memcpy(s1, s2, size); } static void* C2000Memset(void* mem, int c, size_t size) @@ -245,8 +240,11 @@ static void DummyMutexDestroy(PlatformSpecificMutex mtx) } PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = DummyMutexCreate; +void (*PlatformSpecificSrand)(unsigned int) = srand; +int (*PlatformSpecificRand)(void) = rand; void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy; +void (*PlatformSpecificAbort)(void) = abort; -} \ No newline at end of file +} diff --git a/src/Platforms/Dos/UtestPlatform.cpp b/src/Platforms/Dos/UtestPlatform.cpp index ce978bd46..c17cd1a4a 100644 --- a/src/Platforms/Dos/UtestPlatform.cpp +++ b/src/Platforms/Dos/UtestPlatform.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,6 +34,8 @@ #undef free #undef calloc #undef realloc +#undef strdup +#undef strndup #define far // eliminate "meaningless type qualifier" warning #include @@ -102,9 +104,9 @@ int (*PlatformSpecificSetJmp)(void (*function) (void*), void*) = DosSetJmp; void (*PlatformSpecificLongJmp)(void) = DosLongJmp; void (*PlatformSpecificRestoreJumpBuffer)(void) = DosRestoreJumpBuffer; -static long DosTimeInMillis() +static unsigned long DosTimeInMillis() { - return clock() * 1000 / CLOCKS_PER_SEC; + return (unsigned long)(clock() * 1000 / CLOCKS_PER_SEC); } static const char* DosTimeString() @@ -117,7 +119,7 @@ static int DosVSNprintf(char* str, size_t size, const char* format, va_list args return vsnprintf(str, size, format, args); } -long (*GetPlatformSpecificTimeInMillis)() = DosTimeInMillis; +unsigned long (*GetPlatformSpecificTimeInMillis)() = DosTimeInMillis; const char* (*GetPlatformSpecificTimeString)() = DosTimeString; int (*PlatformSpecificVSNprintf)(char *, size_t, const char*, va_list) = DosVSNprintf; @@ -136,21 +138,16 @@ static void DosFClose(PlatformSpecificFile file) fclose((FILE*)file); } +PlatformSpecificFile PlatformSpecificStdOut = stdout; PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = DosFOpen; void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = DosFPuts; void (*PlatformSpecificFClose)(PlatformSpecificFile file) = DosFClose; -static int DosPutchar(int c) -{ - return putchar(c); -} - static void DosFlush() { fflush(stdout); } -extern int (*PlatformSpecificPutchar)(int c) = DosPutchar; extern void (*PlatformSpecificFlush)(void) = DosFlush; static void* DosMalloc(size_t size) @@ -184,6 +181,16 @@ void (*PlatformSpecificFree)(void* memory) = DosFree; void* (*PlatformSpecificMemCpy)(void* s1, const void* s2, size_t size) = DosMemCpy; void* (*PlatformSpecificMemset)(void* mem, int c, size_t size) = DosMemset; +static void DosSrand(unsigned int seed) +{ + srand(seed); +} + +static int DosRand() +{ + return rand(); +} + static double DosFabs(double d) { return fabs(d); @@ -199,6 +206,8 @@ static int DosIsInf(double d) return isinf(d); } +void (*PlatformSpecificSrand)(unsigned int) = DosSrand; +int (*PlatformSpecificRand)(void) = DosRand; double (*PlatformSpecificFabs)(double) = DosFabs; int (*PlatformSpecificIsNan)(double d) = DosIsNan; int (*PlatformSpecificIsInf)(double d) = DosIsInf; @@ -225,4 +234,11 @@ void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy; +static void DosAbort() +{ + abort(); +} + +void (*PlatformSpecificAbort)(void) = DosAbort; + } diff --git a/src/Platforms/Gcc/UtestPlatform.cpp b/src/Platforms/Gcc/UtestPlatform.cpp index a9f0b2301..c86b47839 100644 --- a/src/Platforms/Gcc/UtestPlatform.cpp +++ b/src/Platforms/Gcc/UtestPlatform.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -31,8 +31,19 @@ #undef free #undef calloc #undef realloc +#undef strdup +#undef strndup +#ifdef CPPUTEST_HAVE_GETTIMEOFDAY #include +#endif +#if defined(CPPUTEST_HAVE_FORK) && defined(CPPUTEST_HAVE_WAITPID) && defined(CPPUTEST_HAVE_KILL) +#include +#include +#include +#include +#endif + #include #include #include @@ -40,20 +51,18 @@ #include #include #include -#include -#include -#ifndef __MINGW32__ -#include -#include -#endif + +#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK #include +#endif #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; -#ifndef CPPUTEST_HAVE_FORK +// There is a possibility that a compiler provides fork but not waitpid. +#if !defined(CPPUTEST_HAVE_FORK) || !defined(CPPUTEST_HAVE_WAITPID) || !defined(CPPUTEST_HAVE_KILL) static void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result) { @@ -72,44 +81,59 @@ static int PlatformSpecificWaitPidImplementation(int, int*, int) #else +static void SetTestFailureByStatusCode(UtestShell* shell, TestResult* result, int status) +{ + if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { + result->addFailure(TestFailure(shell, "Failed in separate process")); + } else if (WIFSIGNALED(status)) { + SimpleString message("Failed in separate process - killed by signal "); + message += StringFrom(WTERMSIG(status)); + result->addFailure(TestFailure(shell, message)); + } else if (WIFSTOPPED(status)) { + result->addFailure(TestFailure(shell, "Stopped in separate process - continuing")); + } +} + static void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) { - pid_t cpid, w; - int status; + const pid_t syscallError = -1; + pid_t cpid; + pid_t w; + int status = 0; cpid = PlatformSpecificFork(); - if (cpid == -1) { + if (cpid == syscallError) { result->addFailure(TestFailure(shell, "Call to fork() failed")); return; } if (cpid == 0) { /* Code executed by child */ - shell->runOneTestInCurrentProcess(plugin, *result); // LCOV_EXCL_LINE - _exit(result->getFailureCount()); // LCOV_EXCL_LINE + const size_t initialFailureCount = result->getFailureCount(); // LCOV_EXCL_LINE + shell->runOneTestInCurrentProcess(plugin, *result); // LCOV_EXCL_LINE + _exit(initialFailureCount < result->getFailureCount()); // LCOV_EXCL_LINE } else { /* Code executed by parent */ + size_t amountOfRetries = 0; do { w = PlatformSpecificWaitPid(cpid, &status, WUNTRACED); - if (w == -1) { - if(EINTR ==errno) continue; /* OS X debugger */ - result->addFailure(TestFailure(shell, "Call to waitpid() failed")); - return; - } - - if (WIFEXITED(status) && WEXITSTATUS(status) > result->getFailureCount()) { - result->addFailure(TestFailure(shell, "Failed in separate process")); - } else if (WIFSIGNALED(status)) { - SimpleString signal(StringFrom(WTERMSIG(status))); - { - SimpleString message("Failed in separate process - killed by signal "); - message += signal; - result->addFailure(TestFailure(shell, message)); + if (w == syscallError) { + // OS X debugger causes EINTR + if (EINTR == errno) { + if (amountOfRetries > 30) { + result->addFailure(TestFailure(shell, "Call to waitpid() failed with EINTR. Tried 30 times and giving up! Sometimes happens in debugger")); + return; + } + amountOfRetries++; + } + else { + result->addFailure(TestFailure(shell, "Call to waitpid() failed")); + return; } - } else if (WIFSTOPPED(status)) { - result->addFailure(TestFailure(shell, "Stopped in separate process - continuing")); - kill(w, SIGCONT); + } else { + SetTestFailureByStatusCode(shell, result, status); + if (WIFSTOPPED(status)) kill(w, SIGCONT); } - } while (!WIFEXITED(status) && !WIFSIGNALED(status)); + } while ((w == syscallError) || (!WIFEXITED(status) && !WIFSIGNALED(status))); } } @@ -149,11 +173,13 @@ static int PlatformSpecificSetJmpImplementation(void (*function) (void* data), v } /* - * MacOSX clang 3.0 doesn't seem to recognize longjmp and thus complains about __no_return_. + * MacOSX clang 3.0 doesn't seem to recognize longjmp and thus complains about CPPUTEST_NORETURN. * The later clang compilers complain when it isn't there. So only way is to check the clang compiler here :( */ -#if !((__clang_major__ == 3) && (__clang_minor__ == 0)) -__no_return__ +#ifdef __clang__ + #if !((__clang_major__ == 3) && (__clang_minor__ == 0)) + CPPUTEST_NORETURN + #endif #endif static void PlatformSpecificLongJmpImplementation() { @@ -172,24 +198,33 @@ void (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferI ///////////// Time in millis -static long TimeInMillisImplementation() +static unsigned long TimeInMillisImplementation() { +#ifdef CPPUTEST_HAVE_GETTIMEOFDAY struct timeval tv; - struct timezone tz; - gettimeofday(&tv, &tz); - return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001); + gettimeofday(&tv, NULL); + return (((unsigned long)tv.tv_sec * 1000) + ((unsigned long)tv.tv_usec / 1000)); +#else + return 0; +#endif } static const char* TimeStringImplementation() { - time_t tm = time(NULL); + time_t theTime = time(NULLPTR); static char dateTime[80]; - struct tm *tmp = localtime(&tm); +#ifdef STDC_WANT_SECURE_LIB + static struct tm lastlocaltime; + localtime_s(&lastlocaltime, &theTime); + struct tm *tmp = &lastlocaltime; +#else + struct tm *tmp = localtime(&theTime); +#endif strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp); return dateTime; } -long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; +unsigned long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation; /* Wish we could add an attribute to the format for discovering mis-use... but the __attribute__(format) seems to not work on va_list */ @@ -197,11 +232,20 @@ const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation; #pragma clang diagnostic ignored "-Wformat-nonliteral" #endif +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wused-but-marked-unused" +#endif int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = vsnprintf; static PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag) { +#ifdef STDC_WANT_SECURE_LIB + FILE* file; + fopen_s(&file, filename, flag); + return file; +#else return fopen(filename, flag); +#endif } static void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file) @@ -219,11 +263,12 @@ static void PlatformSpecificFlushImplementation() fflush(stdout); } +PlatformSpecificFile PlatformSpecificStdOut = stdout; + PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation; void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation; void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation; -int (*PlatformSpecificPutchar)(int) = putchar; void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation; void* (*PlatformSpecificMalloc)(size_t size) = malloc; @@ -250,39 +295,64 @@ static int IsInfImplementation(double d) } double (*PlatformSpecificFabs)(double) = fabs; +void (*PlatformSpecificSrand)(unsigned int) = srand; +int (*PlatformSpecificRand)(void) = rand; int (*PlatformSpecificIsNan)(double) = IsNanImplementation; int (*PlatformSpecificIsInf)(double) = IsInfImplementation; int (*PlatformSpecificAtExit)(void(*func)(void)) = atexit; /// this was undefined before static PlatformSpecificMutex PThreadMutexCreate(void) { +#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK pthread_mutex_t *mutex = new pthread_mutex_t; - pthread_mutex_init(mutex, NULL); - + pthread_mutex_init(mutex, NULLPTR); return (PlatformSpecificMutex)mutex; +#else + return NULLPTR; +#endif + } +#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK static void PThreadMutexLock(PlatformSpecificMutex mtx) { pthread_mutex_lock((pthread_mutex_t *)mtx); } +#else +static void PThreadMutexLock(PlatformSpecificMutex) +{ +} +#endif +#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK static void PThreadMutexUnlock(PlatformSpecificMutex mtx) { pthread_mutex_unlock((pthread_mutex_t *)mtx); } +#else +static void PThreadMutexUnlock(PlatformSpecificMutex) +{ +} +#endif +#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK static void PThreadMutexDestroy(PlatformSpecificMutex mtx) { pthread_mutex_t *mutex = (pthread_mutex_t *)mtx; pthread_mutex_destroy(mutex); delete mutex; } +#else +static void PThreadMutexDestroy(PlatformSpecificMutex) +{ +} +#endif PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = PThreadMutexCreate; void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = PThreadMutexLock; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = PThreadMutexUnlock; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = PThreadMutexDestroy; +void (*PlatformSpecificAbort)(void) = abort; } diff --git a/src/Platforms/GccNoStdC/UtestPlatform.cpp b/src/Platforms/GccNoStdC/UtestPlatform.cpp index 73312bd27..3b3c996b3 100644 --- a/src/Platforms/GccNoStdC/UtestPlatform.cpp +++ b/src/Platforms/GccNoStdC/UtestPlatform.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,49 +30,54 @@ #undef free #undef calloc #undef realloc +#undef strdup +#undef strndup #include "CppUTest/PlatformSpecificFunctions.h" -void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell*, TestPlugin*, TestResult*) = NULL; -int (*PlatformSpecificFork)() = NULL; -int (*PlatformSpecificWaitPid)(int, int*, int) = NULL; +void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell*, TestPlugin*, TestResult*) = NULLPTR; +int (*PlatformSpecificFork)() = NULLPTR; +int (*PlatformSpecificWaitPid)(int, int*, int) = NULLPTR; TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() { return TestOutput::eclipse; } -void (*PlatformSpecificLongJmp)() = NULL; -int (*PlatformSpecificSetJmp)(void (*)(void*), void*) = NULL; -void (*PlatformSpecificRestoreJumpBuffer)() = NULL; +void (*PlatformSpecificLongJmp)() = NULLPTR; +int (*PlatformSpecificSetJmp)(void (*)(void*), void*) = NULLPTR; +void (*PlatformSpecificRestoreJumpBuffer)() = NULLPTR; -long (*GetPlatformSpecificTimeInMillis)() = NULL; -const char* (*GetPlatformSpecificTimeString)() = NULL; +unsigned long (*GetPlatformSpecificTimeInMillis)() = NULLPTR; +const char* (*GetPlatformSpecificTimeString)() = NULLPTR; /* IO operations */ -PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = NULL; -void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = NULL; -void (*PlatformSpecificFClose)(PlatformSpecificFile file) = NULL; +PlatformSpecificFile PlatformSpecificStdOut = NULLPTR; +PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = NULLPTR; +void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = NULLPTR; +void (*PlatformSpecificFClose)(PlatformSpecificFile file) = NULLPTR; -int (*PlatformSpecificPutchar)(int c) = NULL; -void (*PlatformSpecificFlush)(void) = NULL; +void (*PlatformSpecificFlush)(void) = NULLPTR; -int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = NULL; +int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = NULLPTR; /* Dynamic Memory operations */ -void* (*PlatformSpecificMalloc)(size_t) = NULL; -void* (*PlatformSpecificRealloc)(void*, size_t) = NULL; -void (*PlatformSpecificFree)(void*) = NULL; -void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = NULL; -void* (*PlatformSpecificMemset)(void*, int, size_t) = NULL; +void* (*PlatformSpecificMalloc)(size_t) = NULLPTR; +void* (*PlatformSpecificRealloc)(void*, size_t) = NULLPTR; +void (*PlatformSpecificFree)(void*) = NULLPTR; +void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = NULLPTR; +void* (*PlatformSpecificMemset)(void*, int, size_t) = NULLPTR; -double (*PlatformSpecificFabs)(double) = NULL; -int (*PlatformSpecificIsNan)(double) = NULL; -int (*PlatformSpecificIsInf)(double) = NULL; -int (*PlatformSpecificAtExit)(void(*func)(void)) = NULL; +double (*PlatformSpecificFabs)(double) = NULLPTR; +int (*PlatformSpecificIsNan)(double) = NULLPTR; +int (*PlatformSpecificIsInf)(double) = NULLPTR; +int (*PlatformSpecificAtExit)(void(*func)(void)) = NULLPTR; -PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = NULL; -void (*PlatformSpecificMutexLock)(PlatformSpecificMutex mtx) = NULL; -void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex mtx) = NULL; -void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex mtx) = NULL; +PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = NULLPTR; +void (*PlatformSpecificMutexLock)(PlatformSpecificMutex mtx) = NULLPTR; +void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex mtx) = NULLPTR; +void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex mtx) = NULLPTR; +void (*PlatformSpecificSrand)(unsigned int) = NULLPTR; +int (*PlatformSpecificRand)(void) = NULLPTR; +void (*PlatformSpecificAbort)(void) = NULLPTR; diff --git a/src/Platforms/Iar/UtestPlatform.cpp b/src/Platforms/Iar/UtestPlatform.cpp index 98b99e754..771ca5804 100644 --- a/src/Platforms/Iar/UtestPlatform.cpp +++ b/src/Platforms/Iar/UtestPlatform.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -39,6 +39,8 @@ #undef calloc #undef realloc #undef free +#undef strdup +#undef strndup #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; @@ -99,13 +101,13 @@ void (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferI ///////////// Time in millis -static long TimeInMillisImplementation() +static unsigned long TimeInMillisImplementation() { clock_t t = clock(); t = t * 10; - return t; + return (unsigned long)t; } ///////////// Time in String @@ -113,25 +115,31 @@ static long TimeInMillisImplementation() static const char* TimeStringImplementation() { time_t tm = time(NULL); - return ctime(&tm); + char* pTimeStr = ctime(&tm); + char* newlineChar = strchr(pTimeStr, '\n'); // Find the terminating newline character. + if(newlineChar != NULL) *newlineChar = '\0'; //If newline is found replace it with the string terminator. + return (pTimeStr); } -long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; +unsigned long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation; int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list args) = vsnprintf; static PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag) { + static int fileNo = 0; (void)filename; (void)flag; - return 0; + fileNo++; + return (void*)fileNo; } static void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file) { (void)str; (void)file; + printf("FILE%d:%s",(int)file, str); } static void PlatformSpecificFCloseImplementation(PlatformSpecificFile file) @@ -143,11 +151,11 @@ static void PlatformSpecificFlushImplementation() { } +PlatformSpecificFile PlatformSpecificStdOut = stdout; PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation; void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation; void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation; -int (*PlatformSpecificPutchar)(int) = putchar; void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation; void* (*PlatformSpecificMalloc)(size_t size) = malloc; @@ -192,5 +200,7 @@ PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = DummyMutexCreate; void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy; - +void (*PlatformSpecificSrand)(unsigned int) = srand; +int (*PlatformSpecificRand)(void) = rand; +void (*PlatformSpecificAbort)(void) = abort; } diff --git a/src/Platforms/Keil/UtestPlatform.cpp b/src/Platforms/Keil/UtestPlatform.cpp index 5201b2fe7..9d2582eaa 100644 --- a/src/Platforms/Keil/UtestPlatform.cpp +++ b/src/Platforms/Keil/UtestPlatform.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -31,6 +31,8 @@ #undef free #undef calloc #undef realloc +#undef strdup +#undef strndup #define far // eliminate "meaningless type qualifier" warning #include @@ -106,16 +108,16 @@ extern "C" * In Keil MDK-ARM, clock() default implementation used semihosting. * Resolutions is user adjustable (1 ms for now) */ - static long TimeInMillisImplementation() + static unsigned long TimeInMillisImplementation() { clock_t t = clock(); - t = t * 10; + t = t * 10; - return t; + return (unsigned long)t; } - long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; + unsigned long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; static const char* TimeStringImplementation() { @@ -153,11 +155,11 @@ extern "C" { } + PlatformSpecificFile PlatformSpecificStdOut = stdout; PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation; void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation; void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation; - int (*PlatformSpecificPutchar)(int) = putchar; void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation; void* (*PlatformSpecificMalloc)(size_t) = malloc; void* (*PlatformSpecificRealloc) (void*, size_t) = realloc; @@ -214,5 +216,6 @@ extern "C" void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy; + void (*PlatformSpecificAbort)(void) = abort; } diff --git a/src/Platforms/Symbian/SymbianMemoryLeakWarning.cpp b/src/Platforms/Symbian/SymbianMemoryLeakWarning.cpp index 0003442d2..dbea37a3c 100644 --- a/src/Platforms/Symbian/SymbianMemoryLeakWarning.cpp +++ b/src/Platforms/Symbian/SymbianMemoryLeakWarning.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/src/Platforms/Symbian/UtestPlatform.cpp b/src/Platforms/Symbian/UtestPlatform.cpp index a4d5df7e0..2829a6f7d 100644 --- a/src/Platforms/Symbian/UtestPlatform.cpp +++ b/src/Platforms/Symbian/UtestPlatform.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -67,14 +67,14 @@ void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* pl shell->runOneTest(plugin, *result); } -static long TimeInMillisImplementation() { +static unsigned long TimeInMillisImplementation() { struct timeval tv; struct timezone tz; ::gettimeofday(&tv, &tz); - return (tv.tv_sec * 1000) + (long)(tv.tv_usec * 0.001); + return ((unsigned long)tv.tv_sec * 1000) + ((unsigned long)tv.tv_usec / 1000); } -long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; +unsigned long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() { @@ -96,10 +96,6 @@ void PlatformSpecificFlush() { fflush(stdout); } -int PlatformSpecificPutchar(int c) { - return putchar(c); -} - double PlatformSpecificFabs(double d) { return fabs(d); } @@ -125,6 +121,8 @@ void* PlatformSpecificMemset(void* mem, int c, size_t size) return memset(mem, c, size); } +PlatformSpecificFile PlatformSpecificStdOut = stdout; + PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { return fopen(filename, flag); } @@ -179,4 +177,5 @@ PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = DummyMutexCreate; void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy; +void (*PlatformSpecificAbort)(void) = abort; diff --git a/src/Platforms/VisualCpp/UtestPlatform.cpp b/src/Platforms/VisualCpp/UtestPlatform.cpp index 8dff3fcd4..992c6b863 100644 --- a/src/Platforms/VisualCpp/UtestPlatform.cpp +++ b/src/Platforms/VisualCpp/UtestPlatform.cpp @@ -4,6 +4,8 @@ #undef free #undef calloc #undef realloc +#undef strdup +#undef strndup #include #include @@ -14,19 +16,19 @@ #include #include "CppUTest/PlatformSpecificFunctions.h" -#include +#include #include #include #ifdef STDC_WANT_SECURE_LIB - #define FOPEN(fp, filename, flag) fopen_s((fp), (filename), (flag)) - #define _VSNPRINTF(str, size, trunc, format, args) _vsnprintf_s((str), (size), (trunc), (format), (args)) - #define LOCALTIME(_tm, timer) localtime_s((_tm), (timer)) + #define MAYBE_SECURE_FOPEN(fp, filename, flag) fopen_s((fp), (filename), (flag)) + #define MAYBE_SECURE_VSNPRINTF(str, size, trunc, format, args) _vsnprintf_s((str), (size), (trunc), (format), (args)) + #define MAYBE_SECURE_LOCALTIME(_tm, timer) localtime_s((_tm), (timer)) #else - #define FOPEN(fp, filename, flag) *(fp) = fopen((filename), (flag)) - #define _VSNPRINTF(str, size, trunc, format, args) _vsnprintf((str), (size), (format), (args)) - #define LOCALTIME(_tm, timer) memcpy(_tm, localtime(timer), sizeof(tm)); + #define MAYBE_SECURE_FOPEN(fp, filename, flag) *(fp) = fopen((filename), (flag)) + #define MAYBE_SECURE_VSNPRINTF(str, size, trunc, format, args) _vsnprintf((str), (size), (format), (args)) + #define MAYBE_SECURE_LOCALTIME(_tm, timer) memcpy(_tm, localtime(timer), sizeof(tm)); #endif static jmp_buf test_exit_jmp_buf[10]; @@ -43,7 +45,7 @@ static int VisualCppSetJmp(void (*function) (void* data), void* data) return 0; } -static void VisualCppLongJmp() +CPPUTEST_NORETURN static void VisualCppLongJmp() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); @@ -58,7 +60,7 @@ int (*PlatformSpecificSetJmp)(void (*function) (void*), void* data) = VisualCppS void (*PlatformSpecificLongJmp)(void) = VisualCppLongJmp; void (*PlatformSpecificRestoreJumpBuffer)(void) = VisualCppRestoreJumpBuffer; -static void VisualCppRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) +static void VisualCppRunTestInASeperateProcess(UtestShell* shell, TestPlugin* /* plugin */, TestResult* result) { result->addFailure(TestFailure(shell, "-p doesn't work on this platform, as it is lacking fork.\b")); } @@ -73,21 +75,40 @@ TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() ///////////// Time in millis -static long VisualCppTimeInMillis() -{ - return timeGetTime(); -} - -long (*GetPlatformSpecificTimeInMillis)() = VisualCppTimeInMillis; +static unsigned long VisualCppTimeInMillis() +{ + static LARGE_INTEGER s_frequency; + static const BOOL s_use_qpc = QueryPerformanceFrequency(&s_frequency); + if (s_use_qpc) + { + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + return (unsigned long)((now.QuadPart * 1000) / s_frequency.QuadPart); + } + else + { + #ifdef TIMERR_NOERROR + return (unsigned long)timeGetTime(); + #else + #if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || (_WIN32_WINNT < _WIN32_WINNT_VISTA) + return (unsigned long)GetTickCount(); + #else + return (unsigned long)GetTickCount64(); + #endif + #endif + } +} + +unsigned long (*GetPlatformSpecificTimeInMillis)() = VisualCppTimeInMillis; ///////////// Time in String static const char* VisualCppTimeString() { - time_t the_time = time(NULL); + time_t the_time = time(NULLPTR); struct tm the_local_time; static char dateTime[80]; - LOCALTIME(&the_local_time, &the_time); + MAYBE_SECURE_LOCALTIME(&the_local_time, &the_time); strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", &the_local_time); return dateTime; } @@ -98,21 +119,21 @@ const char* (*GetPlatformSpecificTimeString)() = VisualCppTimeString; static int VisualCppVSNprintf(char *str, size_t size, const char* format, va_list args) { - char* buf = 0; + char* buf = NULLPTR; size_t sizeGuess = size; - int result = _VSNPRINTF( str, size, _TRUNCATE, format, args); + int result = MAYBE_SECURE_VSNPRINTF( str, size, _TRUNCATE, format, args); str[size-1] = 0; while (result == -1) { - if (buf != 0) + if (buf) free(buf); sizeGuess += 10; buf = (char*)malloc(sizeGuess); - result = _VSNPRINTF( buf, sizeGuess, _TRUNCATE, format, args); + result = MAYBE_SECURE_VSNPRINTF( buf, sizeGuess, _TRUNCATE, format, args); } - if (buf != 0) + if (buf) free(buf); return result; @@ -123,7 +144,7 @@ int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_ static PlatformSpecificFile VisualCppFOpen(const char* filename, const char* flag) { FILE* file; - FOPEN(&file, filename, flag); + MAYBE_SECURE_FOPEN(&file, filename, flag); return file; } @@ -137,6 +158,7 @@ static void VisualCppFClose(PlatformSpecificFile file) fclose((FILE*)file); } +PlatformSpecificFile PlatformSpecificStdOut = stdout; PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = VisualCppFOpen; void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = VisualCppFPuts; void (*PlatformSpecificFClose)(PlatformSpecificFile file) = VisualCppFClose; @@ -146,7 +168,6 @@ static void VisualCppFlush() fflush(stdout); } -int (*PlatformSpecificPutchar)(int c) = putchar; void (*PlatformSpecificFlush)(void) = VisualCppFlush; static void* VisualCppMalloc(size_t size) @@ -164,6 +185,8 @@ static void VisualCppFree(void* memory) free(memory); } +void (*PlatformSpecificSrand)(unsigned int) = srand; +int (*PlatformSpecificRand)(void) = rand; void* (*PlatformSpecificMalloc)(size_t size) = VisualCppMalloc; void* (*PlatformSpecificRealloc)(void* memory, size_t size) = VisualCppReAlloc; void (*PlatformSpecificFree)(void* memory) = VisualCppFree; @@ -208,3 +231,4 @@ PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = VisualCppMutexCreat void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = VisualCppMutexLock; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = VisualCppMutexUnlock; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = VisualCppMutexDestroy; +void (*PlatformSpecificAbort)(void) = abort; diff --git a/src/Platforms/armcc/UtestPlatform.cpp b/src/Platforms/armcc/UtestPlatform.cpp index 06952ab45..8c686c25a 100644 --- a/src/Platforms/armcc/UtestPlatform.cpp +++ b/src/Platforms/armcc/UtestPlatform.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -39,6 +39,8 @@ #undef calloc #undef realloc #undef free +#undef strdup +#undef strndup #define far // eliminate "meaningless type qualifier" warning @@ -105,10 +107,10 @@ void (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferI * In Keil MDK-ARM, clock() default implementation used semihosting. * Resolutions is user adjustable (1 ms for now) */ -static long TimeInMillisImplementation() +static unsigned long TimeInMillisImplementation() { clock_t t = clock(); - return t; + return (unsigned long)t; } ///////////// Time in String @@ -119,7 +121,7 @@ static const char* DummyTimeStringImplementation() return ctime(&tm); } -long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; +unsigned long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; const char* (*GetPlatformSpecificTimeString)() = DummyTimeStringImplementation; int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list args) = vsnprintf; @@ -144,11 +146,11 @@ static void PlatformSpecificFlushImplementation() fflush(stdout); } +PlatformSpecificFile PlatformSpecificStdOut = stdout; PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation; void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation; void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation; -int (*PlatformSpecificPutchar)(int) = putchar; void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation; void* (*PlatformSpecificMalloc)(size_t size) = malloc; @@ -157,6 +159,9 @@ void (*PlatformSpecificFree)(void* memory) = free; void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = memcpy; void* (*PlatformSpecificMemset)(void*, int, size_t) = memset; +void (*PlatformSpecificSrand)(unsigned int) = srand; +int (*PlatformSpecificRand)(void) = rand; + static int IsNanImplementation(double d) { return isnan(d); @@ -198,5 +203,6 @@ PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = DummyMutexCreate; void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy; +void (*PlatformSpecificAbort)(void) = abort; } diff --git a/tests/AllTests.dep b/tests/AllTests.dep deleted file mode 100644 index 164ffb00e..000000000 --- a/tests/AllTests.dep +++ /dev/null @@ -1,740 +0,0 @@ -# Microsoft Developer Studio Generated Dependency File, included by AllTests.mak - -.\AllocationInCFile.c : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorMallocMacros.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - ".\AllocationInCFile.h"\ - - -.\AllocationInCppFile.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - ".\AllocationInCppFile.h"\ - - -.\CppUTestExt\AllTests.cpp : \ - "..\include\CppUTest\CommandLineArguments.h"\ - "..\include\CppUTest\CommandLineTestRunner.h"\ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestMemoryAllocator.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\CppUTestExt\MemoryReportAllocator.h"\ - "..\include\CppUTestExt\MemoryReporterPlugin.h"\ - "..\include\CppUTestExt\MockNamedValue.h"\ - "..\include\CppUTestExt\MockSupportPlugin.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\CheatSheetTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\CppUTestExt\CodeMemoryReportFormatterTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestMemoryAllocator.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\CppUTestExt\CodeMemoryReportFormatter.h"\ - "..\include\CppUTestExt\MemoryReportAllocator.h"\ - "..\include\CppUTestExt\MemoryReportFormatter.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\CommandLineArgumentsTest.cpp : \ - "..\include\CppUTest\CommandLineArguments.h"\ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\CommandLineTestRunnerTest.cpp : \ - "..\include\CppUTest\CommandLineArguments.h"\ - "..\include\CppUTest\CommandLineTestRunner.h"\ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\TestTestingFixture.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\CppUTestExt\GTest2ConvertorTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\TestTestingFixture.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\JUnitOutputTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\JunitTestOutput.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\PlatformSpecificFunctions.h"\ - "..\include\CppUTest\PlatformSpecificFunctions_c.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\MemoryLeakDetectorTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetector.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\PlatformSpecificFunctions.h"\ - "..\include\CppUTest\PlatformSpecificFunctions_c.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestMemoryAllocator.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\MemoryLeakOperatorOverloadsTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetector.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\PlatformSpecificFunctions.h"\ - "..\include\CppUTest\PlatformSpecificFunctions_c.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestHarness_c.h"\ - "..\include\CppUTest\TestMemoryAllocator.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\TestTestingFixture.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - ".\AllocationInCFile.h"\ - ".\AllocationInCppFile.h"\ - - -.\MemoryLeakWarningTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetector.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\PlatformSpecificFunctions.h"\ - "..\include\CppUTest\PlatformSpecificFunctions_c.h"\ - "..\include\CppUTest\SimpleMutex.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestHarness_c.h"\ - "..\include\CppUTest\TestMemoryAllocator.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\TestTestingFixture.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\CppUTestExt\MemoryReportAllocatorTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestMemoryAllocator.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\CppUTestExt\MemoryReportAllocator.h"\ - "..\include\CppUTestExt\MemoryReportFormatter.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\CppUTestExt\MemoryReporterPluginTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestMemoryAllocator.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\CppUTestExt\MemoryReportAllocator.h"\ - "..\include\CppUTestExt\MemoryReporterPlugin.h"\ - "..\include\CppUTestExt\MemoryReportFormatter.h"\ - "..\include\cpputestext\mockactualcall.h"\ - "..\include\CppUTestExt\MockCheckedActualCall.h"\ - "..\include\CppUTestExt\MockCheckedExpectedCall.h"\ - "..\include\cpputestext\mockexpectedcall.h"\ - "..\include\CppUTestExt\MockExpectedCallsList.h"\ - "..\include\CppUTestExt\MockFailure.h"\ - "..\include\CppUTestExt\MockNamedValue.h"\ - "..\include\CppUTestExt\MockSupport.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\CppUTestExt\MemoryReportFormatterTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestMemoryAllocator.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\CppUTestExt\MemoryReportAllocator.h"\ - "..\include\CppUTestExt\MemoryReportFormatter.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\CppUTestExt\MockActualCallTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\cpputestext\mockactualcall.h"\ - "..\include\CppUTestExt\MockCheckedActualCall.h"\ - "..\include\CppUTestExt\MockCheckedExpectedCall.h"\ - "..\include\cpputestext\mockexpectedcall.h"\ - "..\include\CppUTestExt\MockExpectedCallsList.h"\ - "..\include\CppUTestExt\MockFailure.h"\ - "..\include\CppUTestExt\MockNamedValue.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - ".\CppUTestExt\MockFailureTest.h"\ - - -.\CppUTestExt\MockCheatSheetTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\cpputestext\mockactualcall.h"\ - "..\include\CppUTestExt\MockCheckedActualCall.h"\ - "..\include\CppUTestExt\MockCheckedExpectedCall.h"\ - "..\include\cpputestext\mockexpectedcall.h"\ - "..\include\CppUTestExt\MockExpectedCallsList.h"\ - "..\include\CppUTestExt\MockFailure.h"\ - "..\include\CppUTestExt\MockNamedValue.h"\ - "..\include\CppUTestExt\MockSupport.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\CppUTestExt\MockExpectedCallTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\CppUTestExt\MockCheckedExpectedCall.h"\ - "..\include\cpputestext\mockexpectedcall.h"\ - "..\include\CppUTestExt\MockFailure.h"\ - "..\include\CppUTestExt\MockNamedValue.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - ".\CppUTestExt\MockFailureTest.h"\ - - -.\CppUTestExt\MockExpectedFunctionsListTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\CppUTestExt\MockCheckedExpectedCall.h"\ - "..\include\cpputestext\mockexpectedcall.h"\ - "..\include\CppUTestExt\MockExpectedCallsList.h"\ - "..\include\CppUTestExt\MockFailure.h"\ - "..\include\CppUTestExt\MockNamedValue.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - ".\CppUTestExt\MockFailureTest.h"\ - - -.\CppUTestExt\MockFailureTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\CppUTestExt\MockCheckedExpectedCall.h"\ - "..\include\cpputestext\mockexpectedcall.h"\ - "..\include\CppUTestExt\MockExpectedCallsList.h"\ - "..\include\CppUTestExt\MockFailure.h"\ - "..\include\CppUTestExt\MockNamedValue.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - ".\CppUTestExt\MockFailureTest.h"\ - - -.\CppUTestExt\MockPluginTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\cpputestext\mockactualcall.h"\ - "..\include\CppUTestExt\MockCheckedActualCall.h"\ - "..\include\CppUTestExt\MockCheckedExpectedCall.h"\ - "..\include\cpputestext\mockexpectedcall.h"\ - "..\include\CppUTestExt\MockExpectedCallsList.h"\ - "..\include\CppUTestExt\MockFailure.h"\ - "..\include\CppUTestExt\MockNamedValue.h"\ - "..\include\CppUTestExt\MockSupport.h"\ - "..\include\CppUTestExt\MockSupportPlugin.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - ".\CppUTestExt\MockFailureTest.h"\ - - -.\CppUTestExt\MockSupport_cTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestHarness_c.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\TestTestingFixture.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\CppUTestExt\MockSupport_c.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - ".\CppUTestExt\MockSupport_cTestCFile.h"\ - - -.\CppUTestExt\MockSupport_cTestCFile.c : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTestExt\MockSupport_c.h"\ - ".\CppUTestExt\MockSupport_cTestCFile.h"\ - - -.\CppUTestExt\MockSupportTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\cpputestext\mockactualcall.h"\ - "..\include\CppUTestExt\MockCheckedActualCall.h"\ - "..\include\CppUTestExt\MockCheckedExpectedCall.h"\ - "..\include\cpputestext\mockexpectedcall.h"\ - "..\include\CppUTestExt\MockExpectedCallsList.h"\ - "..\include\CppUTestExt\MockFailure.h"\ - "..\include\CppUTestExt\MockNamedValue.h"\ - "..\include\CppUTestExt\MockSupport.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - ".\CppUTestExt\MockFailureTest.h"\ - - -.\CppUTestExt\OrderedTestTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\TestTestingFixture.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\CppUTestExt\OrderedTest.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\PluginTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\TestTestingFixture.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\PreprocessorTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\SetPluginTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\SimpleStringTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\PlatformSpecificFunctions.h"\ - "..\include\CppUTest\PlatformSpecificFunctions_c.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestMemoryAllocator.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\TestFailureTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\TestFilterTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\TestHarness_cTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\PlatformSpecificFunctions.h"\ - "..\include\CppUTest\PlatformSpecificFunctions_c.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestHarness_c.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\TestTestingFixture.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\TestHarness_cTestCFile.c : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\PlatformSpecificFunctions_c.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestHarness_c.h"\ - - -.\TestInstallerTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\TestMemoryAllocatorTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\PlatformSpecificFunctions.h"\ - "..\include\CppUTest\PlatformSpecificFunctions_c.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestMemoryAllocator.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\TestOutputTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\PlatformSpecificFunctions.h"\ - "..\include\CppUTest\PlatformSpecificFunctions_c.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\TestRegistryTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\TestResultTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\PlatformSpecificFunctions.h"\ - "..\include\CppUTest\PlatformSpecificFunctions_c.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - - -.\UtestTest.cpp : \ - "..\include\CppUTest\CppUTestConfig.h"\ - "..\include\CppUTest\MemoryLeakDetectorNewMacros.h"\ - "..\include\CppUTest\MemoryLeakWarningPlugin.h"\ - "..\include\CppUTest\PlatformSpecificFunctions.h"\ - "..\include\CppUTest\PlatformSpecificFunctions_c.h"\ - "..\include\CppUTest\SimpleString.h"\ - "..\include\CppUTest\StandardCLibrary.h"\ - "..\include\CppUTest\TestFailure.h"\ - "..\include\CppUTest\TestFilter.h"\ - "..\include\CppUTest\TestHarness.h"\ - "..\include\CppUTest\TestOutput.h"\ - "..\include\CppUTest\TestPlugin.h"\ - "..\include\CppUTest\TestRegistry.h"\ - "..\include\CppUTest\TestResult.h"\ - "..\include\CppUTest\TestTestingFixture.h"\ - "..\include\CppUTest\Utest.h"\ - "..\include\CppUTest\UtestMacros.h"\ - "..\include\platforms\visualcpp\stdint.h"\ - diff --git a/tests/AllTests.dsp b/tests/AllTests.dsp deleted file mode 100644 index da3578ac2..000000000 --- a/tests/AllTests.dsp +++ /dev/null @@ -1,381 +0,0 @@ -# Microsoft Developer Studio Project File - Name="AllTests" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=AllTests - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "AllTests.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "AllTests.mak" CFG="AllTests - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "AllTests - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "AllTests - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "AllTests - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W3 /GX /O2 /Ob0 /I "..\include" /I "..\include\Platforms\VisualCpp" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "CPPUTEST_MEM_LEAK_DETECTION_DISABLED" /D "CPPUTEST_USE_LONG_LONG" /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib /nologo /subsystem:console /incremental:yes /machine:I386 -# Begin Special Build Tool -TargetPath=.\Release\AllTests.exe -SOURCE="$(InputPath)" -PostBuild_Cmds=$(TargetPath) -# End Special Build Tool - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /MDd /W3 /GX /ZI /Od /I "..\include" /I "..\include\Platforms\VisualCpp" /FI"CppUTest/MemoryLeakDetectorMallocMacros.h" /FI"CppUTest/MemoryLeakDetectorNewMacros.h" /D "_CONSOLE" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "CPPUTEST_MEM_LEAK_DETECTION_DISABLED" /D "CPPUTEST_USE_LONG_LONG" /FR /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 ..\lib\CppUTestd.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# SUBTRACT LINK32 /incremental:no -# Begin Special Build Tool -TargetPath=.\Debug\AllTests.exe -SOURCE="$(InputPath)" -PostBuild_Cmds=$(TargetPath) -v -# End Special Build Tool - -!ENDIF - -# Begin Target - -# Name "AllTests - Win32 Release" -# Name "AllTests - Win32 Debug" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\AllocationInCFile.c -# End Source File -# Begin Source File - -SOURCE=.\AllocationInCppFile.cpp -# End Source File -# Begin Source File - -SOURCE=.\AllocLetTestFree.c -# End Source File -# Begin Source File - -SOURCE=.\AllocLetTestFreeTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\AllTests.cpp -# End Source File -# Begin Source File - -SOURCE=.\CheatSheetTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\CodeMemoryReporterTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CommandLineArgumentsTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CommandLineTestRunnerTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\ExpectedFunctionsListTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\GMockTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\GTest1Test.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\GTest2ConvertorTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\JUnitOutputTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\MemoryLeakDetectorTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\MemoryLeakWarningTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\MemoryOperatorOverloadTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MemoryReportAllocatorTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MemoryReporterPluginTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MemoryReportFormatterTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockActualCallTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockCheatSheetTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockExpectedCallTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockFailureReporterForTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockFailureReporterForTest.h -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockFailureTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockNamedValueTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockPluginTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockSupport_cTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockSupport_cTestCFile.c -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockSupport_cTestCFile.h -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\MockSupportTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\CppUTestExt\OrderedTestTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\PluginTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\PreprocessorTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\SetPluginTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\SimpleMutexTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\SimpleStringTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\TestFailureNaNTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\TestFailureTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\TestFilterTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\TestHarness_cTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\TestHarness_cTestCFile.c -# End Source File -# Begin Source File - -SOURCE=.\TestInstallerTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\TestMemoryAllocatorTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\TestOutputTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\TestRegistryTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\TestResultTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\TestUtestMacro.cpp -# End Source File -# Begin Source File - -SOURCE=.\UtestPlatformTest.cpp -# End Source File -# Begin Source File - -SOURCE=.\UtestTest.cpp -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=.\AllocationInCFile.h -# End Source File -# Begin Source File - -SOURCE=.\AllocationInCppFile.h -# End Source File -# Begin Source File - -SOURCE=.\AllTests.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\CommandLineArguments.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\CppUTestConfig.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\MemoryLeakDetector.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\MemoryLeakDetectorMallocMacros.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\MemoryLeakDetectorNewMacros.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\PlatformSpecificFunctions.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\PlatformSpecificFunctions_c.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\SimpleMutex.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\StandardCLibrary.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\TestFailure.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\TestFilter.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\TestMemoryAllocator.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\TestTestingFixture.h -# End Source File -# Begin Source File - -SOURCE=..\include\CppUTest\UtestMacros.h -# End Source File -# End Group -# Begin Group "Resource Files" - -# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" -# End Group -# End Target -# End Project diff --git a/tests/AllTests.mak b/tests/AllTests.mak deleted file mode 100644 index 775a82d4c..000000000 --- a/tests/AllTests.mak +++ /dev/null @@ -1,1166 +0,0 @@ -# Microsoft Developer Studio Generated NMAKE File, Based on AllTests.dsp -!IF "$(CFG)" == "" -CFG=AllTests - Win32 Debug -!MESSAGE No configuration specified. Defaulting to AllTests - Win32 Debug. -!ENDIF - -!IF "$(CFG)" != "AllTests - Win32 Release" && "$(CFG)" != "AllTests - Win32 Debug" -!MESSAGE Invalid configuration "$(CFG)" specified. -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "AllTests.mak" CFG="AllTests - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "AllTests - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "AllTests - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE -!ERROR An invalid configuration is specified. -!ENDIF - -!IF "$(OS)" == "Windows_NT" -NULL= -!ELSE -NULL=nul -!ENDIF - -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "AllTests - Win32 Release" - -OUTDIR=.\Release -INTDIR=.\Release -# Begin Custom Macros -OutDir=.\Release -# End Custom Macros - -!IF "$(RECURSE)" == "0" - -ALL : "$(OUTDIR)\AllTests.exe" - -!ELSE - -ALL : "CppUTest - Win32 Release" "$(OUTDIR)\AllTests.exe" - -!ENDIF - -!IF "$(RECURSE)" == "1" -CLEAN :"CppUTest - Win32 ReleaseCLEAN" -!ELSE -CLEAN : -!ENDIF - -@erase "$(INTDIR)\AllocationInCFile.obj" - -@erase "$(INTDIR)\AllocationInCppFile.obj" - -@erase "$(INTDIR)\AllTests.obj" - -@erase "$(INTDIR)\CheatSheetTest.obj" - -@erase "$(INTDIR)\CodeMemoryReportFormatterTest.obj" - -@erase "$(INTDIR)\CommandLineArgumentsTest.obj" - -@erase "$(INTDIR)\CommandLineTestRunnerTest.obj" - -@erase "$(INTDIR)\GMockTest.obj" - -@erase "$(INTDIR)\GTest1Test.obj" - -@erase "$(INTDIR)\GTest2ConvertorTest.obj" - -@erase "$(INTDIR)\JUnitOutputTest.obj" - -@erase "$(INTDIR)\MemoryLeakDetectorTest.obj" - -@erase "$(INTDIR)\MemoryLeakOperatorOverloadsTest.obj" - -@erase "$(INTDIR)\MemoryLeakWarningTest.obj" - -@erase "$(INTDIR)\MemoryReportAllocatorTest.obj" - -@erase "$(INTDIR)\MemoryReporterPluginTest.obj" - -@erase "$(INTDIR)\MemoryReportFormatterTest.obj" - -@erase "$(INTDIR)\MockActualCallTest.obj" - -@erase "$(INTDIR)\MockCheatSheetTest.obj" - -@erase "$(INTDIR)\MockExpectedCallTest.obj" - -@erase "$(INTDIR)\MockExpectedFunctionsListTest.obj" - -@erase "$(INTDIR)\MockFailureTest.obj" - -@erase "$(INTDIR)\MockPluginTest.obj" - -@erase "$(INTDIR)\MockSupport_cTest.obj" - -@erase "$(INTDIR)\MockSupport_cTestCFile.obj" - -@erase "$(INTDIR)\MockSupportTest.obj" - -@erase "$(INTDIR)\OrderedTestTest.obj" - -@erase "$(INTDIR)\PluginTest.obj" - -@erase "$(INTDIR)\PreprocessorTest.obj" - -@erase "$(INTDIR)\SetPluginTest.obj" - -@erase "$(INTDIR)\SimpleStringTest.obj" - -@erase "$(INTDIR)\TestFailureTest.obj" - -@erase "$(INTDIR)\TestFilterTest.obj" - -@erase "$(INTDIR)\TestHarness_cTest.obj" - -@erase "$(INTDIR)\TestHarness_cTestCFile.obj" - -@erase "$(INTDIR)\TestInstallerTest.obj" - -@erase "$(INTDIR)\TestMemoryAllocatorTest.obj" - -@erase "$(INTDIR)\TestOutputTest.obj" - -@erase "$(INTDIR)\TestRegistryTest.obj" - -@erase "$(INTDIR)\TestResultTest.obj" - -@erase "$(INTDIR)\UtestTest.obj" - -@erase "$(INTDIR)\vc60.idb" - -@erase "$(OUTDIR)\AllTests.exe" - -@erase "$(OUTDIR)\AllTests.ilk" - -"$(OUTDIR)" : - if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" - -CPP_PROJ=/nologo /ML /W3 /GX /O2 /I "..\include" /I "..\include\Platforms\VisualCpp" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "CPPUTEST_MEM_LEAK_DETECTION_DISABLED" /D "CPPUTEST_USE_LONG_LONG" /Fp"$(INTDIR)\AllTests.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c -BSC32=bscmake.exe -BSC32_FLAGS=/nologo /o"$(OUTDIR)\AllTests.bsc" -BSC32_SBRS= \ - -LINK32=link.exe -LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib /nologo /subsystem:console /incremental:yes /pdb:"$(OUTDIR)\AllTests.pdb" /machine:I386 /out:"$(OUTDIR)\AllTests.exe" -LINK32_OBJS= \ - "$(INTDIR)\AllocationInCFile.obj" \ - "$(INTDIR)\AllocationInCppFile.obj" \ - "$(INTDIR)\AllTests.obj" \ - "$(INTDIR)\CheatSheetTest.obj" \ - "$(INTDIR)\CodeMemoryReportFormatterTest.obj" \ - "$(INTDIR)\CommandLineArgumentsTest.obj" \ - "$(INTDIR)\CommandLineTestRunnerTest.obj" \ - "$(INTDIR)\GMockTest.obj" \ - "$(INTDIR)\GTest1Test.obj" \ - "$(INTDIR)\GTest2ConvertorTest.obj" \ - "$(INTDIR)\JUnitOutputTest.obj" \ - "$(INTDIR)\MemoryLeakDetectorTest.obj" \ - "$(INTDIR)\MemoryLeakOperatorOverloadsTest.obj" \ - "$(INTDIR)\MemoryLeakWarningTest.obj" \ - "$(INTDIR)\MemoryReportAllocatorTest.obj" \ - "$(INTDIR)\MemoryReporterPluginTest.obj" \ - "$(INTDIR)\MemoryReportFormatterTest.obj" \ - "$(INTDIR)\MockActualCallTest.obj" \ - "$(INTDIR)\MockCheatSheetTest.obj" \ - "$(INTDIR)\MockExpectedCallTest.obj" \ - "$(INTDIR)\MockExpectedFunctionsListTest.obj" \ - "$(INTDIR)\MockFailureTest.obj" \ - "$(INTDIR)\MockPluginTest.obj" \ - "$(INTDIR)\MockSupport_cTest.obj" \ - "$(INTDIR)\MockSupport_cTestCFile.obj" \ - "$(INTDIR)\MockSupportTest.obj" \ - "$(INTDIR)\OrderedTestTest.obj" \ - "$(INTDIR)\PluginTest.obj" \ - "$(INTDIR)\PreprocessorTest.obj" \ - "$(INTDIR)\SetPluginTest.obj" \ - "$(INTDIR)\SimpleStringTest.obj" \ - "$(INTDIR)\TestFailureTest.obj" \ - "$(INTDIR)\TestFilterTest.obj" \ - "$(INTDIR)\TestHarness_cTest.obj" \ - "$(INTDIR)\TestHarness_cTestCFile.obj" \ - "$(INTDIR)\TestInstallerTest.obj" \ - "$(INTDIR)\TestMemoryAllocatorTest.obj" \ - "$(INTDIR)\TestOutputTest.obj" \ - "$(INTDIR)\TestRegistryTest.obj" \ - "$(INTDIR)\TestResultTest.obj" \ - "$(INTDIR)\UtestTest.obj" \ - "..\Release\CppUTest.lib" - -"$(OUTDIR)\AllTests.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) - $(LINK32) @<< - $(LINK32_FLAGS) $(LINK32_OBJS) -<< - -TargetPath=.\Release\AllTests.exe -SOURCE="$(InputPath)" -DS_POSTBUILD_DEP=$(INTDIR)\postbld.dep - -ALL : $(DS_POSTBUILD_DEP) - -# Begin Custom Macros -OutDir=.\Release -# End Custom Macros - -$(DS_POSTBUILD_DEP) : "CppUTest - Win32 Release" "$(OUTDIR)\AllTests.exe" - .\Release\AllTests.exe - echo Helper for Post-build step > "$(DS_POSTBUILD_DEP)" - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - -OUTDIR=.\Debug -INTDIR=.\Debug -# Begin Custom Macros -OutDir=.\Debug -# End Custom Macros - -!IF "$(RECURSE)" == "0" - -ALL : "$(OUTDIR)\AllTests.exe" "$(OUTDIR)\AllTests.bsc" - -!ELSE - -ALL : "CppUTest - Win32 Debug" "$(OUTDIR)\AllTests.exe" "$(OUTDIR)\AllTests.bsc" - -!ENDIF - -!IF "$(RECURSE)" == "1" -CLEAN :"CppUTest - Win32 DebugCLEAN" -!ELSE -CLEAN : -!ENDIF - -@erase "$(INTDIR)\AllocationInCFile.obj" - -@erase "$(INTDIR)\AllocationInCFile.sbr" - -@erase "$(INTDIR)\AllocationInCppFile.obj" - -@erase "$(INTDIR)\AllocationInCppFile.sbr" - -@erase "$(INTDIR)\AllTests.obj" - -@erase "$(INTDIR)\AllTests.sbr" - -@erase "$(INTDIR)\CheatSheetTest.obj" - -@erase "$(INTDIR)\CheatSheetTest.sbr" - -@erase "$(INTDIR)\CodeMemoryReportFormatterTest.obj" - -@erase "$(INTDIR)\CodeMemoryReportFormatterTest.sbr" - -@erase "$(INTDIR)\CommandLineArgumentsTest.obj" - -@erase "$(INTDIR)\CommandLineArgumentsTest.sbr" - -@erase "$(INTDIR)\CommandLineTestRunnerTest.obj" - -@erase "$(INTDIR)\CommandLineTestRunnerTest.sbr" - -@erase "$(INTDIR)\GMockTest.obj" - -@erase "$(INTDIR)\GMockTest.sbr" - -@erase "$(INTDIR)\GTest1Test.obj" - -@erase "$(INTDIR)\GTest1Test.sbr" - -@erase "$(INTDIR)\GTest2ConvertorTest.obj" - -@erase "$(INTDIR)\GTest2ConvertorTest.sbr" - -@erase "$(INTDIR)\JUnitOutputTest.obj" - -@erase "$(INTDIR)\JUnitOutputTest.sbr" - -@erase "$(INTDIR)\MemoryLeakDetectorTest.obj" - -@erase "$(INTDIR)\MemoryLeakDetectorTest.sbr" - -@erase "$(INTDIR)\MemoryLeakOperatorOverloadsTest.obj" - -@erase "$(INTDIR)\MemoryLeakOperatorOverloadsTest.sbr" - -@erase "$(INTDIR)\MemoryLeakWarningTest.obj" - -@erase "$(INTDIR)\MemoryLeakWarningTest.sbr" - -@erase "$(INTDIR)\MemoryReportAllocatorTest.obj" - -@erase "$(INTDIR)\MemoryReportAllocatorTest.sbr" - -@erase "$(INTDIR)\MemoryReporterPluginTest.obj" - -@erase "$(INTDIR)\MemoryReporterPluginTest.sbr" - -@erase "$(INTDIR)\MemoryReportFormatterTest.obj" - -@erase "$(INTDIR)\MemoryReportFormatterTest.sbr" - -@erase "$(INTDIR)\MockActualCallTest.obj" - -@erase "$(INTDIR)\MockActualCallTest.sbr" - -@erase "$(INTDIR)\MockCheatSheetTest.obj" - -@erase "$(INTDIR)\MockCheatSheetTest.sbr" - -@erase "$(INTDIR)\MockExpectedCallTest.obj" - -@erase "$(INTDIR)\MockExpectedCallTest.sbr" - -@erase "$(INTDIR)\MockExpectedFunctionsListTest.obj" - -@erase "$(INTDIR)\MockExpectedFunctionsListTest.sbr" - -@erase "$(INTDIR)\MockFailureTest.obj" - -@erase "$(INTDIR)\MockFailureTest.sbr" - -@erase "$(INTDIR)\MockPluginTest.obj" - -@erase "$(INTDIR)\MockPluginTest.sbr" - -@erase "$(INTDIR)\MockSupport_cTest.obj" - -@erase "$(INTDIR)\MockSupport_cTest.sbr" - -@erase "$(INTDIR)\MockSupport_cTestCFile.obj" - -@erase "$(INTDIR)\MockSupport_cTestCFile.sbr" - -@erase "$(INTDIR)\MockSupportTest.obj" - -@erase "$(INTDIR)\MockSupportTest.sbr" - -@erase "$(INTDIR)\OrderedTestTest.obj" - -@erase "$(INTDIR)\OrderedTestTest.sbr" - -@erase "$(INTDIR)\PluginTest.obj" - -@erase "$(INTDIR)\PluginTest.sbr" - -@erase "$(INTDIR)\PreprocessorTest.obj" - -@erase "$(INTDIR)\PreprocessorTest.sbr" - -@erase "$(INTDIR)\SetPluginTest.obj" - -@erase "$(INTDIR)\SetPluginTest.sbr" - -@erase "$(INTDIR)\SimpleStringTest.obj" - -@erase "$(INTDIR)\SimpleStringTest.sbr" - -@erase "$(INTDIR)\TestFailureTest.obj" - -@erase "$(INTDIR)\TestFailureTest.sbr" - -@erase "$(INTDIR)\TestFilterTest.obj" - -@erase "$(INTDIR)\TestFilterTest.sbr" - -@erase "$(INTDIR)\TestHarness_cTest.obj" - -@erase "$(INTDIR)\TestHarness_cTest.sbr" - -@erase "$(INTDIR)\TestHarness_cTestCFile.obj" - -@erase "$(INTDIR)\TestHarness_cTestCFile.sbr" - -@erase "$(INTDIR)\TestInstallerTest.obj" - -@erase "$(INTDIR)\TestInstallerTest.sbr" - -@erase "$(INTDIR)\TestMemoryAllocatorTest.obj" - -@erase "$(INTDIR)\TestMemoryAllocatorTest.sbr" - -@erase "$(INTDIR)\TestOutputTest.obj" - -@erase "$(INTDIR)\TestOutputTest.sbr" - -@erase "$(INTDIR)\TestRegistryTest.obj" - -@erase "$(INTDIR)\TestRegistryTest.sbr" - -@erase "$(INTDIR)\TestResultTest.obj" - -@erase "$(INTDIR)\TestResultTest.sbr" - -@erase "$(INTDIR)\UtestTest.obj" - -@erase "$(INTDIR)\UtestTest.sbr" - -@erase "$(INTDIR)\vc60.idb" - -@erase "$(INTDIR)\vc60.pdb" - -@erase "$(OUTDIR)\AllTests.bsc" - -@erase "$(OUTDIR)\AllTests.exe" - -@erase "$(OUTDIR)\AllTests.ilk" - -@erase "$(OUTDIR)\AllTests.pdb" - -"$(OUTDIR)" : - if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" - -CPP_PROJ=/nologo /MDd /W3 /GX /ZI /Od /I "..\include" /I "..\include\Platforms\VisualCpp" /FI"CppUTest/MemoryLeakDetectorMallocMacros.h" /FI"CppUTest/MemoryLeakDetectorNewMacros.h" /D "_CONSOLE" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "CPPUTEST_MEM_LEAK_DETECTION_DISABLED" /D "CPPUTEST_USE_LONG_LONG" /FR"$(INTDIR)\\" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /GZ /c -BSC32=bscmake.exe -BSC32_FLAGS=/nologo /o"$(OUTDIR)\AllTests.bsc" -BSC32_SBRS= \ - "$(INTDIR)\AllocationInCFile.sbr" \ - "$(INTDIR)\AllocationInCppFile.sbr" \ - "$(INTDIR)\AllTests.sbr" \ - "$(INTDIR)\CheatSheetTest.sbr" \ - "$(INTDIR)\CodeMemoryReportFormatterTest.sbr" \ - "$(INTDIR)\CommandLineArgumentsTest.sbr" \ - "$(INTDIR)\CommandLineTestRunnerTest.sbr" \ - "$(INTDIR)\GMockTest.sbr" \ - "$(INTDIR)\GTest1Test.sbr" \ - "$(INTDIR)\GTest2ConvertorTest.sbr" \ - "$(INTDIR)\JUnitOutputTest.sbr" \ - "$(INTDIR)\MemoryLeakDetectorTest.sbr" \ - "$(INTDIR)\MemoryLeakOperatorOverloadsTest.sbr" \ - "$(INTDIR)\MemoryLeakWarningTest.sbr" \ - "$(INTDIR)\MemoryReportAllocatorTest.sbr" \ - "$(INTDIR)\MemoryReporterPluginTest.sbr" \ - "$(INTDIR)\MemoryReportFormatterTest.sbr" \ - "$(INTDIR)\MockActualCallTest.sbr" \ - "$(INTDIR)\MockCheatSheetTest.sbr" \ - "$(INTDIR)\MockExpectedCallTest.sbr" \ - "$(INTDIR)\MockExpectedFunctionsListTest.sbr" \ - "$(INTDIR)\MockFailureTest.sbr" \ - "$(INTDIR)\MockPluginTest.sbr" \ - "$(INTDIR)\MockSupport_cTest.sbr" \ - "$(INTDIR)\MockSupport_cTestCFile.sbr" \ - "$(INTDIR)\MockSupportTest.sbr" \ - "$(INTDIR)\OrderedTestTest.sbr" \ - "$(INTDIR)\PluginTest.sbr" \ - "$(INTDIR)\PreprocessorTest.sbr" \ - "$(INTDIR)\SetPluginTest.sbr" \ - "$(INTDIR)\SimpleStringTest.sbr" \ - "$(INTDIR)\TestFailureTest.sbr" \ - "$(INTDIR)\TestFilterTest.sbr" \ - "$(INTDIR)\TestHarness_cTest.sbr" \ - "$(INTDIR)\TestHarness_cTestCFile.sbr" \ - "$(INTDIR)\TestInstallerTest.sbr" \ - "$(INTDIR)\TestMemoryAllocatorTest.sbr" \ - "$(INTDIR)\TestOutputTest.sbr" \ - "$(INTDIR)\TestRegistryTest.sbr" \ - "$(INTDIR)\TestResultTest.sbr" \ - "$(INTDIR)\UtestTest.sbr" - -"$(OUTDIR)\AllTests.bsc" : "$(OUTDIR)" $(BSC32_SBRS) - $(BSC32) @<< - $(BSC32_FLAGS) $(BSC32_SBRS) -<< - -LINK32=link.exe -LINK32_FLAGS=..\lib\CppUTest.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib /nologo /subsystem:console /incremental:yes /pdb:"$(OUTDIR)\AllTests.pdb" /debug /machine:I386 /out:"$(OUTDIR)\AllTests.exe" /pdbtype:sept -LINK32_OBJS= \ - "$(INTDIR)\AllocationInCFile.obj" \ - "$(INTDIR)\AllocationInCppFile.obj" \ - "$(INTDIR)\AllTests.obj" \ - "$(INTDIR)\CheatSheetTest.obj" \ - "$(INTDIR)\CodeMemoryReportFormatterTest.obj" \ - "$(INTDIR)\CommandLineArgumentsTest.obj" \ - "$(INTDIR)\CommandLineTestRunnerTest.obj" \ - "$(INTDIR)\GMockTest.obj" \ - "$(INTDIR)\GTest1Test.obj" \ - "$(INTDIR)\GTest2ConvertorTest.obj" \ - "$(INTDIR)\JUnitOutputTest.obj" \ - "$(INTDIR)\MemoryLeakDetectorTest.obj" \ - "$(INTDIR)\MemoryLeakOperatorOverloadsTest.obj" \ - "$(INTDIR)\MemoryLeakWarningTest.obj" \ - "$(INTDIR)\MemoryReportAllocatorTest.obj" \ - "$(INTDIR)\MemoryReporterPluginTest.obj" \ - "$(INTDIR)\MemoryReportFormatterTest.obj" \ - "$(INTDIR)\MockActualCallTest.obj" \ - "$(INTDIR)\MockCheatSheetTest.obj" \ - "$(INTDIR)\MockExpectedCallTest.obj" \ - "$(INTDIR)\MockExpectedFunctionsListTest.obj" \ - "$(INTDIR)\MockFailureTest.obj" \ - "$(INTDIR)\MockPluginTest.obj" \ - "$(INTDIR)\MockSupport_cTest.obj" \ - "$(INTDIR)\MockSupport_cTestCFile.obj" \ - "$(INTDIR)\MockSupportTest.obj" \ - "$(INTDIR)\OrderedTestTest.obj" \ - "$(INTDIR)\PluginTest.obj" \ - "$(INTDIR)\PreprocessorTest.obj" \ - "$(INTDIR)\SetPluginTest.obj" \ - "$(INTDIR)\SimpleStringTest.obj" \ - "$(INTDIR)\TestFailureTest.obj" \ - "$(INTDIR)\TestFilterTest.obj" \ - "$(INTDIR)\TestHarness_cTest.obj" \ - "$(INTDIR)\TestHarness_cTestCFile.obj" \ - "$(INTDIR)\TestInstallerTest.obj" \ - "$(INTDIR)\TestMemoryAllocatorTest.obj" \ - "$(INTDIR)\TestOutputTest.obj" \ - "$(INTDIR)\TestRegistryTest.obj" \ - "$(INTDIR)\TestResultTest.obj" \ - "$(INTDIR)\UtestTest.obj" \ - "..\lib\CppUTest.lib" - -"$(OUTDIR)\AllTests.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) - $(LINK32) @<< - $(LINK32_FLAGS) $(LINK32_OBJS) -<< - -TargetPath=.\Debug\AllTests.exe -SOURCE="$(InputPath)" -DS_POSTBUILD_DEP=$(INTDIR)\postbld.dep - -ALL : $(DS_POSTBUILD_DEP) - -# Begin Custom Macros -OutDir=.\Debug -# End Custom Macros - -$(DS_POSTBUILD_DEP) : "CppUTest - Win32 Debug" "$(OUTDIR)\AllTests.exe" "$(OUTDIR)\AllTests.bsc" - .\Debug\AllTests.exe -v - echo Helper for Post-build step > "$(DS_POSTBUILD_DEP)" - -!ENDIF - -.c{$(INTDIR)}.obj:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - -.cpp{$(INTDIR)}.obj:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - -.cxx{$(INTDIR)}.obj:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - -.c{$(INTDIR)}.sbr:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - -.cpp{$(INTDIR)}.sbr:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - -.cxx{$(INTDIR)}.sbr:: - $(CPP) @<< - $(CPP_PROJ) $< -<< - - -!IF "$(NO_EXTERNAL_DEPS)" != "1" -!IF EXISTS("AllTests.dep") -!INCLUDE "AllTests.dep" -!ELSE -!MESSAGE Warning: cannot find "AllTests.dep" -!ENDIF -!ENDIF - - -!IF "$(CFG)" == "AllTests - Win32 Release" || "$(CFG)" == "AllTests - Win32 Debug" -SOURCE=.\AllocationInCFile.c - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\AllocationInCFile.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\AllocationInCFile.obj" "$(INTDIR)\AllocationInCFile.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\AllocationInCppFile.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\AllocationInCppFile.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\AllocationInCppFile.obj" "$(INTDIR)\AllocationInCppFile.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\CppUTestExt\AllTests.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\AllTests.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\AllTests.obj" "$(INTDIR)\AllTests.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CheatSheetTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\CheatSheetTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\CheatSheetTest.obj" "$(INTDIR)\CheatSheetTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\CppUTestExt\CodeMemoryReportFormatterTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\CodeMemoryReportFormatterTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\CodeMemoryReportFormatterTest.obj" "$(INTDIR)\CodeMemoryReportFormatterTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CommandLineArgumentsTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\CommandLineArgumentsTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\CommandLineArgumentsTest.obj" "$(INTDIR)\CommandLineArgumentsTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\CommandLineTestRunnerTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\CommandLineTestRunnerTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\CommandLineTestRunnerTest.obj" "$(INTDIR)\CommandLineTestRunnerTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\CppUTestExt\GMockTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\GMockTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\GMockTest.obj" "$(INTDIR)\GMockTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\GTest1Test.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\GTest1Test.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\GTest1Test.obj" "$(INTDIR)\GTest1Test.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\GTest2ConvertorTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\GTest2ConvertorTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\GTest2ConvertorTest.obj" "$(INTDIR)\GTest2ConvertorTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\JUnitOutputTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\JUnitOutputTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\JUnitOutputTest.obj" "$(INTDIR)\JUnitOutputTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\MemoryLeakDetectorTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MemoryLeakDetectorTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MemoryLeakDetectorTest.obj" "$(INTDIR)\MemoryLeakDetectorTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\MemoryLeakOperatorOverloadsTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MemoryLeakOperatorOverloadsTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MemoryLeakOperatorOverloadsTest.obj" "$(INTDIR)\MemoryLeakOperatorOverloadsTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\MemoryLeakWarningTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MemoryLeakWarningTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MemoryLeakWarningTest.obj" "$(INTDIR)\MemoryLeakWarningTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\CppUTestExt\MemoryReportAllocatorTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MemoryReportAllocatorTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MemoryReportAllocatorTest.obj" "$(INTDIR)\MemoryReportAllocatorTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\MemoryReporterPluginTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MemoryReporterPluginTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MemoryReporterPluginTest.obj" "$(INTDIR)\MemoryReporterPluginTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\MemoryReportFormatterTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MemoryReportFormatterTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MemoryReportFormatterTest.obj" "$(INTDIR)\MemoryReportFormatterTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\MockActualCallTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MockActualCallTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MockActualCallTest.obj" "$(INTDIR)\MockActualCallTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\MockCheatSheetTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MockCheatSheetTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MockCheatSheetTest.obj" "$(INTDIR)\MockCheatSheetTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\MockExpectedCallTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MockExpectedCallTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MockExpectedCallTest.obj" "$(INTDIR)\MockExpectedCallTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\MockExpectedFunctionsListTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MockExpectedFunctionsListTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MockExpectedFunctionsListTest.obj" "$(INTDIR)\MockExpectedFunctionsListTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\MockFailureTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MockFailureTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MockFailureTest.obj" "$(INTDIR)\MockFailureTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\MockPluginTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MockPluginTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MockPluginTest.obj" "$(INTDIR)\MockPluginTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\MockSupport_cTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MockSupport_cTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MockSupport_cTest.obj" "$(INTDIR)\MockSupport_cTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\MockSupport_cTestCFile.c - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MockSupport_cTestCFile.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MockSupport_cTestCFile.obj" "$(INTDIR)\MockSupport_cTestCFile.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\MockSupportTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\MockSupportTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\MockSupportTest.obj" "$(INTDIR)\MockSupportTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\CppUTestExt\OrderedTestTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\OrderedTestTest.obj" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\OrderedTestTest.obj" "$(INTDIR)\OrderedTestTest.sbr" : $(SOURCE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -!ENDIF - -SOURCE=.\PluginTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\PluginTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\PluginTest.obj" "$(INTDIR)\PluginTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\PreprocessorTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\PreprocessorTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\PreprocessorTest.obj" "$(INTDIR)\PreprocessorTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\SetPluginTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\SetPluginTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\SetPluginTest.obj" "$(INTDIR)\SetPluginTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\SimpleStringTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\SimpleStringTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\SimpleStringTest.obj" "$(INTDIR)\SimpleStringTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\TestFailureTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\TestFailureTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\TestFailureTest.obj" "$(INTDIR)\TestFailureTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\TestFilterTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\TestFilterTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\TestFilterTest.obj" "$(INTDIR)\TestFilterTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\TestHarness_cTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\TestHarness_cTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\TestHarness_cTest.obj" "$(INTDIR)\TestHarness_cTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\TestHarness_cTestCFile.c - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\TestHarness_cTestCFile.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\TestHarness_cTestCFile.obj" "$(INTDIR)\TestHarness_cTestCFile.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\TestInstallerTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\TestInstallerTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\TestInstallerTest.obj" "$(INTDIR)\TestInstallerTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\TestMemoryAllocatorTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\TestMemoryAllocatorTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\TestMemoryAllocatorTest.obj" "$(INTDIR)\TestMemoryAllocatorTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\TestOutputTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\TestOutputTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\TestOutputTest.obj" "$(INTDIR)\TestOutputTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\TestRegistryTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\TestRegistryTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\TestRegistryTest.obj" "$(INTDIR)\TestRegistryTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\TestResultTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\TestResultTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\TestResultTest.obj" "$(INTDIR)\TestResultTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -SOURCE=.\UtestTest.cpp - -!IF "$(CFG)" == "AllTests - Win32 Release" - - -"$(INTDIR)\UtestTest.obj" : $(SOURCE) "$(INTDIR)" - - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - - -"$(INTDIR)\UtestTest.obj" "$(INTDIR)\UtestTest.sbr" : $(SOURCE) "$(INTDIR)" - - -!ENDIF - -!IF "$(CFG)" == "AllTests - Win32 Release" - -"CppUTest - Win32 Release" : - cd "\DEV\05_CPPUTEST\CPPUTEST" - $(MAKE) /$(MAKEFLAGS) /F .\CppUTest.mak CFG="CppUTest - Win32 Release" - cd ".\tests" - -"CppUTest - Win32 ReleaseCLEAN" : - cd "\DEV\05_CPPUTEST\CPPUTEST" - $(MAKE) /$(MAKEFLAGS) /F .\CppUTest.mak CFG="CppUTest - Win32 Release" RECURSE=1 CLEAN - cd ".\tests" - -!ELSEIF "$(CFG)" == "AllTests - Win32 Debug" - -"CppUTest - Win32 Debug" : - cd "\DEV\05_CPPUTEST\CPPUTEST" - $(MAKE) /$(MAKEFLAGS) /F .\CppUTest.mak CFG="CppUTest - Win32 Debug" - cd ".\tests" - -"CppUTest - Win32 DebugCLEAN" : - cd "\DEV\05_CPPUTEST\CPPUTEST" - $(MAKE) /$(MAKEFLAGS) /F .\CppUTest.mak CFG="CppUTest - Win32 Debug" RECURSE=1 CLEAN - cd ".\tests" - -!ENDIF - - -!ENDIF - diff --git a/tests/AllTests.vcproj b/tests/AllTests.vcproj index 0225cba2e..7e32f154e 100644 --- a/tests/AllTests.vcproj +++ b/tests/AllTests.vcproj @@ -45,7 +45,7 @@ Name="VCCLCompilerTool" Optimization="0" InlineFunctionExpansion="1" - AdditionalIncludeDirectories="..\include,..\include\Platforms\VisualCpp" + AdditionalIncludeDirectories="..\include" PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;CPPUTEST_USE_LONG_LONG" StringPooling="true" RuntimeLibrary="0" @@ -129,14 +129,14 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + Debug Win32 + + Debug + x64 + Release Win32 + + Release + x64 + {913088F6-37C0-4195-80E9-548C7C5303CB} @@ -19,11 +27,21 @@ false MultiByte + + Application + false + MultiByte + Application false MultiByte + + Application + false + MultiByte + @@ -31,19 +49,33 @@ + + + + + + + + <_ProjectFileVersion>10.0.30319.1 - ..\cpputest_build\ - ..\cpputest_build\Release\$(ProjectName)\ + ..\cpputest_build\x86\ + ..\cpputest_build\x64\ + ..\cpputest_build\Release\x86\$(ProjectName)\ + ..\cpputest_build\Release\x64\$(ProjectName)\ false - ..\cpputest_build\ - ..\cpputest_build\Debug\$(ProjectName)\ + false + ..\cpputest_build\x86\ + ..\cpputest_build\x64\ + ..\cpputest_build\Debug\x86\$(ProjectName)\ + ..\cpputest_build\Debug\x64\$(ProjectName)\ true + true @@ -60,8 +92,9 @@ true Level3 true - ..\include;..\include\CppUTestExt\CppUTestGTest;..\include\CppUTestExt\CppUTestGMock;..\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) + ..\include;..\include\CppUTestExt\CppUTestGTest;..\include\CppUTestExt\CppUTestGMock;%(AdditionalIncludeDirectories) OldStyle + true NDEBUG;%(PreprocessorDefinitions) @@ -83,6 +116,44 @@ "$(TargetPath)" + + + .\Release/AllTests.tlb + + + + + MaxSpeed + OnlyExplicitInline + WIN32;NDEBUG;_CONSOLE;CPPUTEST_USE_LONG_LONG;%(PreprocessorDefinitions) + true + MultiThreadedDLL + true + Level3 + true + ..\include;..\include\CppUTestExt\CppUTestGTest;..\include\CppUTestExt\CppUTestGMock;%(AdditionalIncludeDirectories) + OldStyle + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + Console + false + + + + + true + .\Release/AllTests.bsc + + + "$(TargetPath)" + + .\Debug/AllTests.tlb @@ -91,7 +162,7 @@ Disabled - ..\include;..\include\CppUTestExt\CppUTestGTest;..\include\CppUTestExt\CppUTestGMock;..\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) + ..\include;..\include\CppUTestExt\CppUTestGTest;..\include\CppUTestExt\CppUTestGMock;%(AdditionalIncludeDirectories) _CONSOLE;WIN32;_DEBUG;CPPUTEST_USE_LONG_LONG;%(PreprocessorDefinitions) EnableFastChecks MultiThreadedDebugDLL @@ -122,6 +193,44 @@ "$(TargetPath)" + + + .\Debug/AllTests.tlb + + + + + Disabled + ..\include;..\include\CppUTestExt\CppUTestGTest;..\include\CppUTestExt\CppUTestGMock;..\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) + _CONSOLE;WIN32;_DEBUG;CPPUTEST_USE_LONG_LONG;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + true + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + + + true + true + Console + false + + + + + true + + + "$(TargetPath)" + + {f468f539-27bd-468e-be64-dde641400b51} @@ -133,13 +242,14 @@ - - - - - - - + + + + + + + + @@ -168,40 +278,43 @@ - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + - + + diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2759e3785..5d090ace3 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,59 +1,23 @@ -enable_testing() +# Helper to handle generating a map file, which is annoyingly tricky. +function(add_mapfile target) + if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.13") + set(mapfile "$.map") + if(CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC") + # ClangCL (lld-link) can't generate map files + elseif(CMAKE_CXX_COMPILER_ID STREQUAL "IAR") + target_link_options(${target} PRIVATE "SHELL:--map ${mapfile}.map") + elseif(MSVC) + target_link_options(${target} PRIVATE "/MAP:${mapfile}") + elseif( + (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") OR + (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + ) + target_link_options(${target} PRIVATE "LINKER:-Map=${mapfile}") + endif() + endif() +endfunction() -set(CppUTestTests_src - AllTests.cpp - SetPluginTest.cpp - CheatSheetTest.cpp - SimpleStringTest.cpp - CommandLineArgumentsTest.cpp - TestFailureTest.cpp - TestFailureNaNTest.cpp - CommandLineTestRunnerTest.cpp - TestFilterTest.cpp - TestHarness_cTest.cpp - JUnitOutputTest.cpp - TestHarness_cTestCFile.c - MemoryLeakDetectorTest.cpp - TestInstallerTest.cpp - AllocLetTestFree.c - MemoryOperatorOverloadTest.cpp - TestMemoryAllocatorTest.cpp - MemoryLeakWarningTest.cpp - TestOutputTest.cpp - AllocLetTestFreeTest.cpp - TestRegistryTest.cpp - AllocationInCFile.c - PluginTest.cpp - TestResultTest.cpp - PreprocessorTest.cpp - TestUTestMacro.cpp - TestUTestStringMacro.cpp - AllocationInCppFile.cpp - UtestTest.cpp - SimpleMutexTest.cpp - UtestPlatformTest.cpp - TeamCityOutputTest.cpp -) - -if (MSVC) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4723") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4723") -endif (MSVC) - -if (MINGW) - find_package (Threads REQUIRED) - set(THREAD_LIB "pthread") -endif (MINGW) - -if (${CMAKE_HOST_SYSTEM_NAME} MATCHES "OpenBSD") - set (THREADS_HAVE_PTHREAD_ARG 1) - find_package (Threads REQUIRED) - set (THREAD_LIB "pthread") +add_subdirectory(CppUTest) +if (CPPUTEST_EXTENSIONS) + add_subdirectory(CppUTestExt) endif () - -add_executable(CppUTestTests ${CppUTestTests_src}) -cpputest_normalize_test_output_location(CppUTestTests) -target_link_libraries(CppUTestTests CppUTest ${THREAD_LIB}) - -add_subdirectory(CppUTestExt) -cpputest_buildtime_discover_tests(CppUTestTests) diff --git a/tests/CppUTest/AllTests.cpp b/tests/CppUTest/AllTests.cpp new file mode 100644 index 000000000..e9e6a2b75 --- /dev/null +++ b/tests/CppUTest/AllTests.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "CppUTest/CommandLineTestRunner.h" +#include "CppUTest/TestMemoryAllocator.h" +#include "CppUTest/SimpleStringInternalCache.h" + +#define SHOW_MEMORY_REPORT 0 + +int main(int ac, char **av) +{ + int returnValue = 0; + GlobalSimpleStringCache stringCache; + + { + /* These checks are here to make sure assertions outside test runs don't crash */ + CHECK(true); + LONGS_EQUAL(1, 1); + +#if SHOW_MEMORY_REPORT + GlobalMemoryAccountant accountant; + accountant.start(); +#endif + + returnValue = CommandLineTestRunner::RunAllTests(ac, av); /* cover alternate method */ + +#if SHOW_MEMORY_REPORT + accountant.stop(); + printf("%s", accountant.report().asCharString()); +#endif + } + + return returnValue; +} + diff --git a/platforms/iar/tests/AllTests.h b/tests/CppUTest/AllTests.h similarity index 96% rename from platforms/iar/tests/AllTests.h rename to tests/CppUTest/AllTests.h index 9e2fb1649..32ef2c770 100644 --- a/platforms/iar/tests/AllTests.h +++ b/tests/CppUTest/AllTests.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/tests/AllocLetTestFree.c b/tests/CppUTest/AllocLetTestFree.c similarity index 97% rename from tests/AllocLetTestFree.c rename to tests/CppUTest/AllocLetTestFree.c index 163583141..82358074f 100644 --- a/tests/AllocLetTestFree.c +++ b/tests/CppUTest/AllocLetTestFree.c @@ -22,6 +22,7 @@ void AllocLetTestFree_Destroy(AllocLetTestFree self) AllocLetTestFree no_use = self; self = NULL; self = no_use; + (void)self; } #endif diff --git a/tests/AllocLetTestFree.h b/tests/CppUTest/AllocLetTestFree.h similarity index 100% rename from tests/AllocLetTestFree.h rename to tests/CppUTest/AllocLetTestFree.h diff --git a/tests/AllocLetTestFreeTest.cpp b/tests/CppUTest/AllocLetTestFreeTest.cpp similarity index 87% rename from tests/AllocLetTestFreeTest.cpp rename to tests/CppUTest/AllocLetTestFreeTest.cpp index ef4edcef8..5c05464b7 100644 --- a/tests/AllocLetTestFreeTest.cpp +++ b/tests/CppUTest/AllocLetTestFreeTest.cpp @@ -16,12 +16,12 @@ TEST_GROUP(AllocLetTestFree) { AllocLetTestFree allocLetTestFree; - void setup() + void setup() CPPUTEST_OVERRIDE { allocLetTestFree = AllocLetTestFree_Create(); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { AllocLetTestFree_Destroy(allocLetTestFree); } diff --git a/tests/AllocationInCFile.c b/tests/CppUTest/AllocationInCFile.c similarity index 54% rename from tests/AllocationInCFile.c rename to tests/CppUTest/AllocationInCFile.c index d60c8c307..03165a958 100644 --- a/tests/AllocationInCFile.c +++ b/tests/CppUTest/AllocationInCFile.c @@ -4,11 +4,30 @@ /* This file is for simulating overloads of malloc */ -char* mallocAllocation() +char* mallocAllocation(void) { return (char*) malloc(10UL); } +char* strdupAllocation(void) +{ +#ifdef CPPUTEST_USE_STRDUP_MACROS + return strdup("0123456789"); +#else + return NULL; +#endif +} + + +char* strndupAllocation(void) +{ +#ifdef CPPUTEST_USE_STRDUP_MACROS + return strndup("0123456789", 10); +#else + return NULL; +#endif +} + void freeAllocation(void* memory) { free(memory); diff --git a/tests/AllocationInCFile.h b/tests/CppUTest/AllocationInCFile.h similarity index 78% rename from tests/AllocationInCFile.h rename to tests/CppUTest/AllocationInCFile.h index 30345568a..c2131b949 100644 --- a/tests/AllocationInCFile.h +++ b/tests/CppUTest/AllocationInCFile.h @@ -6,6 +6,8 @@ extern "C" { #endif extern char* mallocAllocation(void); +extern char* strdupAllocation(void); +extern char* strndupAllocation(void); extern void freeAllocation(void* memory); extern void freeAllocationWithoutMacro(void* memory); diff --git a/tests/AllocationInCppFile.cpp b/tests/CppUTest/AllocationInCppFile.cpp similarity index 95% rename from tests/AllocationInCppFile.cpp rename to tests/CppUTest/AllocationInCppFile.cpp index d85e66bb5..b1a662b1c 100644 --- a/tests/AllocationInCppFile.cpp +++ b/tests/CppUTest/AllocationInCppFile.cpp @@ -27,7 +27,7 @@ char* newArrayAllocationWithoutMacro() return new char[100]; } -#if CPPUTEST_USE_STD_CPP_LIB +#if CPPUTEST_HAVE_EXCEPTIONS ClassThatThrowsAnExceptionInTheConstructor::ClassThatThrowsAnExceptionInTheConstructor() { diff --git a/tests/AllocationInCppFile.h b/tests/CppUTest/AllocationInCppFile.h similarity index 73% rename from tests/AllocationInCppFile.h rename to tests/CppUTest/AllocationInCppFile.h index c4642b598..1d59789df 100644 --- a/tests/AllocationInCppFile.h +++ b/tests/CppUTest/AllocationInCppFile.h @@ -7,12 +7,12 @@ char* newArrayAllocation(); char* newAllocationWithoutMacro(); char* newArrayAllocationWithoutMacro(); -#if CPPUTEST_USE_STD_CPP_LIB +#if CPPUTEST_HAVE_EXCEPTIONS class ClassThatThrowsAnExceptionInTheConstructor { public: - ClassThatThrowsAnExceptionInTheConstructor() __no_return__; + CPPUTEST_NORETURN ClassThatThrowsAnExceptionInTheConstructor(); }; #endif diff --git a/tests/CppUTest/CMakeLists.txt b/tests/CppUTest/CMakeLists.txt new file mode 100644 index 000000000..0471ce762 --- /dev/null +++ b/tests/CppUTest/CMakeLists.txt @@ -0,0 +1,101 @@ +add_library(CppUTestTests_main OBJECT + AllTests.cpp +) + +if(CPPUTEST_STD_C_LIB_DISABLED) + target_sources(CppUTestTests_main + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/../DummyUTestPlatform/DummyUTestPlatform.cpp + ) +endif() + +target_link_libraries(CppUTestTests_main + PUBLIC CppUTest +) + +include(CppUTest) + +if(NOT CPPUTEST_SPLIT_TESTS) + add_executable(CppUTestTests) + + add_mapfile(CppUTestTests) + + cpputest_discover_tests(CppUTestTests) +endif() + +function(add_cpputest_test number) + set(name CppUTestTests) + + if(CPPUTEST_SPLIT_TESTS) + string(APPEND name ${number}) + add_executable(${name}) + add_mapfile(${name}) + cpputest_discover_tests(${name}) + endif() + + target_sources(${name} + PRIVATE ${ARGN} + ) + target_link_libraries(${name} + PRIVATE CppUTestTests_main + ) +endfunction() + +add_cpputest_test(1 + AllocLetTestFree.c + AllocLetTestFreeTest.cpp + CheatSheetTest.cpp + CompatabilityTests.cpp + CommandLineArgumentsTest.cpp + CommandLineTestRunnerTest.cpp + JUnitOutputTest.cpp +) + +add_cpputest_test(2 + DummyMemoryLeakDetector.cpp + MemoryLeakWarningTest.cpp + PluginTest.cpp + PreprocessorTest.cpp + SetPluginTest.cpp + SimpleMutexTest.cpp + TeamCityOutputTest.cpp + TestFailureNaNTest.cpp + TestFailureTest.cpp + TestResultTest.cpp +) + +add_cpputest_test(3 + MemoryLeakDetectorTest.cpp + SimpleStringTest.cpp + SimpleStringCacheTest.cpp +) + +add_cpputest_test(4 + TestOutputTest.cpp + TestRegistryTest.cpp +) + +add_cpputest_test(5 + AllocationInCFile.c + AllocationInCppFile.cpp + MemoryOperatorOverloadTest.cpp + TeamCityOutputTest.cpp +) + +add_cpputest_test(6 + TestFilterTest.cpp + TestHarness_cTest.cpp + TestHarness_cTestCFile.c + TestInstallerTest.cpp +) + +add_cpputest_test(7 + TestMemoryAllocatorTest.cpp + TestUTestMacro.cpp +) + +add_cpputest_test(8 + UtestPlatformTest.cpp + UtestTest.cpp + TestUTestStringMacro.cpp +) diff --git a/tests/CheatSheetTest.cpp b/tests/CppUTest/CheatSheetTest.cpp similarity index 90% rename from tests/CheatSheetTest.cpp rename to tests/CppUTest/CheatSheetTest.cpp index fd44b8609..dbde888b7 100644 --- a/tests/CheatSheetTest.cpp +++ b/tests/CppUTest/CheatSheetTest.cpp @@ -9,14 +9,14 @@ static void stub(){} TEST_GROUP(CheatSheet) { /* declare a setup method for the test group. Optional. */ - void setup () + void setup() CPPUTEST_OVERRIDE { /* Set method real_one to stub. Automatically restore in teardown */ UT_PTR_SET(real_one, stub); } /* Declare a teardown method for the test group. Optional */ - void teardown() + void teardown() CPPUTEST_OVERRIDE { } }; /* Do not forget semicolumn */ @@ -33,4 +33,3 @@ TEST(CheatSheet, TestName) /* Check a string */ STRCMP_EQUAL("HelloWorld", "HelloWorld"); } - diff --git a/tests/CommandLineArgumentsTest.cpp b/tests/CppUTest/CommandLineArgumentsTest.cpp old mode 100755 new mode 100644 similarity index 64% rename from tests/CommandLineArgumentsTest.cpp rename to tests/CppUTest/CommandLineArgumentsTest.cpp index c2d5dd537..2a4e29b7f --- a/tests/CommandLineArgumentsTest.cpp +++ b/tests/CppUTest/CommandLineArgumentsTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -36,10 +36,10 @@ class OptionsPlugin: public TestPlugin TestPlugin(name) { } - ~OptionsPlugin() + ~OptionsPlugin() CPPUTEST_DESTRUCTOR_OVERRIDE { } - bool parseArguments(int /*ac*/, const char** /*av*/, int /*index*/) + bool parseArguments(int /*ac*/, const char *const * /*av*/, int /*index*/) CPPUTEST_OVERRIDE { return true; } @@ -50,18 +50,18 @@ TEST_GROUP(CommandLineArguments) CommandLineArguments* args; OptionsPlugin* plugin; - void setup() + void setup() CPPUTEST_OVERRIDE { plugin = new OptionsPlugin("options"); - args = NULL; + args = NULLPTR; } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete args; delete plugin; } - bool newArgumentParser(int argc, const char** argv) + bool newArgumentParser(int argc, const char *const *argv) { args = new CommandLineArguments(argc, argv); return args->parse(plugin); @@ -79,6 +79,13 @@ TEST(CommandLineArguments, verboseSetMultipleParameters) CHECK(args->isVerbose()); } +TEST(CommandLineArguments, veryVerbose) +{ + const char* argv[] = { "tests.exe", "-vv" }; + CHECK(newArgumentParser(2, argv)); + CHECK(args->isVeryVerbose()); +} + TEST(CommandLineArguments, setColor) { const char* argv[] = { "tests.exe", "-c" }; @@ -102,7 +109,7 @@ TEST(CommandLineArguments, repeatSetDifferentParameter) LONGS_EQUAL(4, args->getRepeatCount()); } -TEST(CommandLineArguments, repeatSetDefaultsToTwo) +TEST(CommandLineArguments, repeatSetDefaultsToTwoAndShuffleDisabled) { int argc = 2; const char* argv[] = { "tests.exe", "-r" }; @@ -110,6 +117,73 @@ TEST(CommandLineArguments, repeatSetDefaultsToTwo) LONGS_EQUAL(2, args->getRepeatCount()); } +TEST(CommandLineArguments, reverseEnabled) +{ + int argc = 2; + const char* argv[] = { "tests.exe", "-b" }; + CHECK(newArgumentParser(argc, argv)); + CHECK_TRUE(args->isReversing()); +} + +TEST(CommandLineArguments, shuffleDisabledByDefault) +{ + int argc = 1; + const char* argv[] = { "tests.exe" }; + CHECK(newArgumentParser(argc, argv)); + CHECK_FALSE(args->isShuffling()); +} + +TEST(CommandLineArguments, shuffleEnabled) +{ + int argc = 2; + const char* argv[] = { "tests.exe", "-s" }; + CHECK(newArgumentParser(argc, argv)); + CHECK_TRUE(args->isShuffling()); +} + +TEST(CommandLineArguments, shuffleWithSeedZeroIsOk) +{ + int argc = 2; + const char* argv[] = { "tests.exe", "-s0" }; + CHECK_FALSE(newArgumentParser(argc, argv)); + CHECK_EQUAL(0, args->getShuffleSeed()); +} + +TEST(CommandLineArguments, shuffleEnabledSpecificSeedCase1) +{ + int argc = 2; + const char* argv[] = { "tests.exe", "-s999"}; + CHECK(newArgumentParser(argc, argv)); + CHECK_EQUAL(999, args->getShuffleSeed()); +} + +TEST(CommandLineArguments, shuffleEnabledSpecificSeedCase2) +{ + int argc = 2; + const char* argv[] = { "tests.exe", "-s 888"}; + CHECK(newArgumentParser(argc, argv)); + CHECK_EQUAL(888, args->getShuffleSeed()); +} + +TEST(CommandLineArguments, shuffleEnabledSpecificSeedCase3) +{ + int argc = 3; + const char* argv[] = { "tests.exe", "-s", "777"}; + CHECK(newArgumentParser(argc, argv)); + CHECK_EQUAL(777, args->getShuffleSeed()); +} + +TEST(CommandLineArguments, shuffleBeforeDoesNotDisturbOtherSwitch) +{ + int argc = 4; + const char* argv[] = { "tests.exe", "-s", "-sg", "group" }; + CHECK(newArgumentParser(argc, argv)); + TestFilter groupFilter("group"); + groupFilter.strictMatching(); + CHECK_EQUAL(groupFilter, *args->getGroupFilters()); + CHECK_TRUE(args->isShuffling()); +} + TEST(CommandLineArguments, runningTestsInSeperateProcesses) { int argc = 2; @@ -126,6 +200,84 @@ TEST(CommandLineArguments, setGroupFilter) CHECK_EQUAL(TestFilter("group"), *args->getGroupFilters()); } +TEST(CommandLineArguments, setCompleteGroupDotNameFilterInvalidArgument) +{ + int argc = 3; + const char* argv[] = { "tests.exe", "-t", "groupname" }; + CHECK_FALSE(newArgumentParser(argc, argv)); +} + +TEST(CommandLineArguments, setCompleteGroupDotNameFilter) +{ + int argc = 3; + const char* argv[] = { "tests.exe", "-t", "group.name" }; + CHECK(newArgumentParser(argc, argv)); + CHECK_EQUAL(TestFilter("group"), *args->getGroupFilters()); + CHECK_EQUAL(TestFilter("name"), *args->getNameFilters()); +} + +TEST(CommandLineArguments, setCompleteStrictGroupDotNameFilterInvalidArgument) +{ + int argc = 3; + const char* argv[] = { "tests.exe", "-st", "groupname" }; + CHECK_FALSE(newArgumentParser(argc, argv)); +} + +TEST(CommandLineArguments, setCompleteStrictGroupDotNameFilter) +{ + int argc = 3; + const char* argv[] = { "tests.exe", "-st", "group.name" }; + CHECK(newArgumentParser(argc, argv)); + TestFilter groupFilter("group"); + groupFilter.strictMatching(); + CHECK_EQUAL(groupFilter, *args->getGroupFilters()); + TestFilter nameFilter("name"); + nameFilter.strictMatching(); + CHECK_EQUAL(nameFilter, *args->getNameFilters()); +} + +TEST(CommandLineArguments, setCompleteExcludeGroupDotNameFilterInvalidArgument) +{ + int argc = 3; + const char* argv[] = { "tests.exe", "-xt", "groupname" }; + CHECK_FALSE(newArgumentParser(argc, argv)); +} + +TEST(CommandLineArguments, setCompleteExcludeGroupDotNameFilter) +{ + int argc = 3; + const char* argv[] = { "tests.exe", "-xt", "group.name" }; + CHECK(newArgumentParser(argc, argv)); + TestFilter groupFilter("group"); + groupFilter.invertMatching(); + CHECK_EQUAL(groupFilter, *args->getGroupFilters()); + TestFilter nameFilter("name"); + nameFilter.invertMatching(); + CHECK_EQUAL(nameFilter, *args->getNameFilters()); +} + +TEST(CommandLineArguments, setCompleteExcludeStrictGroupDotNameFilterInvalidArgument) +{ + int argc = 3; + const char* argv[] = { "tests.exe", "-xst", "groupname" }; + CHECK_FALSE(newArgumentParser(argc, argv)); +} + +TEST(CommandLineArguments, setCompleteExcludeStrictGroupDotNameFilter) +{ + int argc = 3; + const char* argv[] = { "tests.exe", "-xst", "group.name" }; + CHECK(newArgumentParser(argc, argv)); + TestFilter groupFilter("group"); + groupFilter.strictMatching(); + groupFilter.invertMatching(); + CHECK_EQUAL(groupFilter, *args->getGroupFilters()); + TestFilter nameFilter("name"); + nameFilter.strictMatching(); + nameFilter.invertMatching(); + CHECK_EQUAL(nameFilter, *args->getNameFilters()); +} + TEST(CommandLineArguments, setGroupFilterSameParameter) { int argc = 2; @@ -365,15 +517,33 @@ TEST(CommandLineArguments, setPrintGroupsAndNames) CHECK(args->isListingTestGroupAndCaseNames()); } -TEST(CommandLineArguments, weirdParamatersPrintsUsageAndReturnsFalse) +TEST(CommandLineArguments, weirdParamatersReturnsFalse) { int argc = 2; const char* argv[] = { "tests.exe", "-SomethingWeird" }; CHECK(!newArgumentParser(argc, argv)); - STRCMP_EQUAL("usage [-v] [-c] [-p] [-lg] [-ln] [-ri] [-r#] [-g|sg|xg|xsg groupName]... [-n|sn|xn|xsn testName]... [\"TEST(groupName, testName)\"]... [-o{normal, junit, teamcity}] [-k packageName]\n", +} + +TEST(CommandLineArguments, printUsage) +{ + STRCMP_EQUAL( + "use -h for more extensive help\n" + "usage [-h] [-v] [-vv] [-c] [-p] [-lg] [-ln] [-ll] [-ri] [-r[<#>]] [-f] [-e] [-ci]\n" + " [-g|sg|xg|xsg ]... [-n|sn|xn|xsn ]... [-t|st|xt|xst .]...\n" + " [-b] [-s []] [\"[IGNORE_]TEST(, )\"]...\n" + " [-o{normal|eclipse|junit|teamcity}] [-k ]\n", args->usage()); } +TEST(CommandLineArguments, helpPrintsTheHelp) +{ + int argc = 2; + const char* argv[] = { "tests.exe", "-h" }; + CHECK(!newArgumentParser(argc, argv)); + CHECK(args->needHelp()); +} + + TEST(CommandLineArguments, pluginKnowsOption) { int argc = 2; @@ -391,10 +561,27 @@ TEST(CommandLineArguments, checkDefaultArguments) CHECK(newArgumentParser(argc, argv)); CHECK(!args->isVerbose()); LONGS_EQUAL(1, args->getRepeatCount()); - CHECK(NULL == args->getGroupFilters()); - CHECK(NULL == args->getNameFilters()); + CHECK(NULLPTR == args->getGroupFilters()); + CHECK(NULLPTR == args->getNameFilters()); + CHECK(args->isEclipseOutput()); + CHECK(SimpleString("") == args->getPackageName()); + CHECK(!args->isCrashingOnFail()); + CHECK(args->isRethrowingExceptions()); +} + +TEST(CommandLineArguments, checkContinuousIntegrationMode) +{ + int argc = 2; + const char* argv[] = { "tests.exe", "-ci" }; + CHECK(newArgumentParser(argc, argv)); + CHECK(!args->isVerbose()); + LONGS_EQUAL(1, args->getRepeatCount()); + CHECK(NULLPTR == args->getGroupFilters()); + CHECK(NULLPTR == args->getNameFilters()); CHECK(args->isEclipseOutput()); CHECK(SimpleString("") == args->getPackageName()); + CHECK(!args->isCrashingOnFail()); + CHECK_FALSE(args->isRethrowingExceptions()); } TEST(CommandLineArguments, setPackageName) @@ -434,3 +621,18 @@ TEST(CommandLineArguments, setOptRun) CHECK(args->isRunIgnored()); } +TEST(CommandLineArguments, setOptCrashOnFail) +{ + int argc = 2; + const char* argv[] = { "tests.exe", "-f"}; + CHECK(newArgumentParser(argc, argv)); + CHECK(args->isCrashingOnFail()); +} + +TEST(CommandLineArguments, setOptRethrowExceptions) +{ + int argc = 2; + const char* argv[] = { "tests.exe", "-e"}; + CHECK(newArgumentParser(argc, argv)); + CHECK_FALSE(args->isRethrowingExceptions()); +} diff --git a/tests/CommandLineTestRunnerTest.cpp b/tests/CppUTest/CommandLineTestRunnerTest.cpp old mode 100755 new mode 100644 similarity index 54% rename from tests/CommandLineTestRunnerTest.cpp rename to tests/CppUTest/CommandLineTestRunnerTest.cpp index 722739acd..e0beed18e --- a/tests/CommandLineTestRunnerTest.cpp +++ b/tests/CppUTest/CommandLineTestRunnerTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -32,7 +32,6 @@ #include "CppUTest/TestPlugin.h" #include "CppUTest/JUnitTestOutput.h" #include "CppUTest/PlatformSpecificFunctions.h" -#include "CppUTestExt/MockSupport.h" class DummyPluginWhichCountsThePlugins : public TestPlugin @@ -47,7 +46,7 @@ class DummyPluginWhichCountsThePlugins : public TestPlugin { } - virtual bool parseArguments(int, const char**, int) + virtual bool parseArguments(int, const char *const *, int) CPPUTEST_OVERRIDE { /* Remove ourselves from the count */ amountOfPlugins = registry_->countPlugins() - 1; @@ -64,24 +63,24 @@ class CommandLineTestRunnerWithStringBufferOutput : public CommandLineTestRunner StringBufferTestOutput* fakeConsoleOutputWhichIsReallyABuffer; StringBufferTestOutput* fakeTCOutputWhichIsReallyABuffer; - CommandLineTestRunnerWithStringBufferOutput(int argc, const char** argv, TestRegistry* registry) - : CommandLineTestRunner(argc, argv, registry), fakeJUnitOutputWhichIsReallyABuffer_(NULL), - fakeConsoleOutputWhichIsReallyABuffer(NULL), fakeTCOutputWhichIsReallyABuffer(NULL) + CommandLineTestRunnerWithStringBufferOutput(int argc, const char *const *argv, TestRegistry* registry) + : CommandLineTestRunner(argc, argv, registry), fakeJUnitOutputWhichIsReallyABuffer_(NULLPTR), + fakeConsoleOutputWhichIsReallyABuffer(NULLPTR), fakeTCOutputWhichIsReallyABuffer(NULLPTR) {} - TestOutput* createConsoleOutput() + TestOutput* createConsoleOutput() CPPUTEST_OVERRIDE { fakeConsoleOutputWhichIsReallyABuffer = new StringBufferTestOutput; return fakeConsoleOutputWhichIsReallyABuffer; } - TestOutput* createJUnitOutput(const SimpleString&) + TestOutput* createJUnitOutput(const SimpleString&) CPPUTEST_OVERRIDE { fakeJUnitOutputWhichIsReallyABuffer_ = new StringBufferTestOutput; return fakeJUnitOutputWhichIsReallyABuffer_; } - TestOutput* createTeamCityOutput() + TestOutput* createTeamCityOutput() CPPUTEST_OVERRIDE { fakeTCOutputWhichIsReallyABuffer = new StringBufferTestOutput; return fakeTCOutputWhichIsReallyABuffer; @@ -91,19 +90,29 @@ class CommandLineTestRunnerWithStringBufferOutput : public CommandLineTestRunner TEST_GROUP(CommandLineTestRunner) { TestRegistry registry; - UtestShell *oneTest_; + UtestShell *test1; + UtestShell *test2; DummyPluginWhichCountsThePlugins* pluginCountingPlugin; - void setup() + void setup() CPPUTEST_OVERRIDE { - oneTest_ = new UtestShell("group", "test", "file", 1); - registry.addTest(oneTest_); + test1 = new UtestShell("group1", "test1", "file1", 1); + test2 = new UtestShell("group2", "test2", "file2", 2); + registry.addTest(test1); pluginCountingPlugin = new DummyPluginWhichCountsThePlugins("PluginCountingPlugin", ®istry); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete pluginCountingPlugin; - delete oneTest_; + delete test2; + delete test1; + } + + SimpleString runAndGetOutput(const int argc, const char* argv[]) + { + CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(argc, argv, ®istry); + commandLineTestRunner.runAllTestsMain(); + return commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput(); } }; @@ -132,12 +141,54 @@ TEST(CommandLineTestRunner, NoPluginsAreInstalledAtTheEndOfARunWhenTheArgumentsA } +TEST(CommandLineTestRunner, ReturnsOneWhenTheArgumentsAreInvalid) +{ + const char* argv[] = { "tests.exe", "-some-invalid=parameter" }; + + CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, ®istry); + int returned = commandLineTestRunner.runAllTestsMain(); + + LONGS_EQUAL(1, returned); +} + +TEST(CommandLineTestRunner, ReturnsOnePrintsHelpOnHelp) +{ + const char* argv[] = { "tests.exe", "-h" }; + + CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, ®istry); + int returned = commandLineTestRunner.runAllTestsMain(); + + LONGS_EQUAL(1, returned); + STRCMP_CONTAINS("Thanks for using CppUTest.", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); +} + + +TEST(CommandLineTestRunner, ReturnsZeroWhenNoErrors) +{ + const char* argv[] = { "tests.exe" }; + + CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(1, argv, ®istry); + int returned = commandLineTestRunner.runAllTestsMain(); + + LONGS_EQUAL(0, returned); +} + +TEST(CommandLineTestRunner, ReturnsOneWhenNoTestsMatchProvidedFilter) +{ + const char* argv[] = { "tests.exe", "-g", "NoSuchGroup"}; + + CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(3, argv, ®istry); + int returned = commandLineTestRunner.runAllTestsMain(); + + LONGS_EQUAL(1, returned); +} + TEST(CommandLineTestRunner, TeamcityOutputEnabled) { const char* argv[] = {"tests.exe", "-oteamcity"}; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, ®istry); commandLineTestRunner.runAllTestsMain(); - CHECK(commandLineTestRunner.fakeTCOutputWhichIsReallyABuffer); + CHECK(commandLineTestRunner.fakeTCOutputWhichIsReallyABuffer != NULLPTR); } TEST(CommandLineTestRunner, JunitOutputEnabled) @@ -146,7 +197,7 @@ TEST(CommandLineTestRunner, JunitOutputEnabled) CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, ®istry); commandLineTestRunner.runAllTestsMain(); - CHECK(commandLineTestRunner.fakeJUnitOutputWhichIsReallyABuffer_); + CHECK(commandLineTestRunner.fakeJUnitOutputWhichIsReallyABuffer_ != NULLPTR); } TEST(CommandLineTestRunner, JunitOutputAndVerboseEnabled) @@ -155,8 +206,46 @@ TEST(CommandLineTestRunner, JunitOutputAndVerboseEnabled) CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(3, argv, ®istry); commandLineTestRunner.runAllTestsMain(); - STRCMP_CONTAINS("TEST(group, test)", commandLineTestRunner.fakeJUnitOutputWhichIsReallyABuffer_->getOutput().asCharString()); - STRCMP_CONTAINS("TEST(group, test)", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); + STRCMP_CONTAINS("TEST(group1, test1)", commandLineTestRunner.fakeJUnitOutputWhichIsReallyABuffer_->getOutput().asCharString()); + STRCMP_CONTAINS("TEST(group1, test1)", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); +} + +TEST(CommandLineTestRunner, veryVerboseSetOnOutput) +{ + const char* argv[] = { "tests.exe", "-vv"}; + + CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, ®istry); + commandLineTestRunner.runAllTestsMain(); + STRCMP_CONTAINS("TEST(group1, test1)", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); + STRCMP_CONTAINS("destroyTest", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); +} + +TEST(CommandLineTestRunner, defaultTestsAreRunInOrderTheyAreInRepository) +{ + const char* argv[] = { "tests.exe", "-v"}; + + registry.addTest(test2); + CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, ®istry); + commandLineTestRunner.runAllTestsMain(); + + SimpleStringCollection stringCollection; + commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().split("\n", stringCollection); + STRCMP_CONTAINS("test2", stringCollection[0].asCharString()); + STRCMP_CONTAINS("test1", stringCollection[1].asCharString()); +} + +TEST(CommandLineTestRunner, testsCanBeRunInReverseOrder) +{ + const char* argv[] = { "tests.exe", "-v", "-b"}; + + registry.addTest(test2); + CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(3, argv, ®istry); + commandLineTestRunner.runAllTestsMain(); + + SimpleStringCollection stringCollection; + commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().split("\n", stringCollection); + STRCMP_CONTAINS("test1", stringCollection[0].asCharString()); + STRCMP_CONTAINS("test2", stringCollection[1].asCharString()); } TEST(CommandLineTestRunner, listTestGroupNamesShouldWorkProperly) @@ -176,91 +265,136 @@ TEST(CommandLineTestRunner, listTestGroupAndCaseNamesShouldWorkProperly) CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, ®istry); commandLineTestRunner.runAllTestsMain(); - STRCMP_CONTAINS("group.test", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); + STRCMP_CONTAINS("group1.test1", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); +} + +TEST(CommandLineTestRunner, listTestLocationsShouldWorkProperly) +{ + const char* argv[] = { "tests.exe", "-ll" }; + + CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, ®istry); + commandLineTestRunner.runAllTestsMain(); + + STRCMP_CONTAINS("group1.test1", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); +} + +TEST(CommandLineTestRunner, randomShuffleSeedIsPrintedAndRandFuncIsExercised) +{ + // more than 1 item in test list ensures that shuffle algorithm calls rand_() + UtestShell *anotherTest = new UtestShell("group", "test2", "file", 1); + registry.addTest(anotherTest); + + const char* argv[] = { "tests.exe", "-s"}; + SimpleString text = runAndGetOutput(2, argv); + STRCMP_CONTAINS("shuffling enabled with seed:", text.asCharString()); + + delete anotherTest; +} + +TEST(CommandLineTestRunner, specificShuffleSeedIsPrintedVerbose) +{ + const char* argv[] = { "tests.exe", "-s2", "-v"}; + SimpleString text = runAndGetOutput(3, argv); + STRCMP_CONTAINS("shuffling enabled with seed: 2", text.asCharString()); } extern "C" { typedef PlatformSpecificFile (*FOpenFunc)(const char*, const char*); typedef void (*FPutsFunc)(const char*, PlatformSpecificFile); typedef void (*FCloseFunc)(PlatformSpecificFile); - typedef int (*PutcharFunc)(int); } struct FakeOutput { FakeOutput() : SaveFOpen(PlatformSpecificFOpen), SaveFPuts(PlatformSpecificFPuts), - SaveFClose(PlatformSpecificFClose), SavePutchar(PlatformSpecificPutchar) + SaveFClose(PlatformSpecificFClose) + { + installFakes(); + currentFake = this; + } + + ~FakeOutput() + { + currentFake = NULLPTR; + restoreOriginals(); + } + + void installFakes() { PlatformSpecificFOpen = (FOpenFunc)fopen_fake; PlatformSpecificFPuts = (FPutsFunc)fputs_fake; PlatformSpecificFClose = (FCloseFunc)fclose_fake; - PlatformSpecificPutchar = (PutcharFunc)putchar_fake; } - ~FakeOutput() + + void restoreOriginals() { - PlatformSpecificPutchar = SavePutchar; PlatformSpecificFOpen = SaveFOpen; PlatformSpecificFPuts = SaveFPuts; PlatformSpecificFClose = SaveFClose; } + static PlatformSpecificFile fopen_fake(const char*, const char*) { - return (PlatformSpecificFile)0; + return (PlatformSpecificFile) NULLPTR; } - static void fputs_fake(const char* str, PlatformSpecificFile) + + static void fputs_fake(const char* str, PlatformSpecificFile f) { - file += str; + if (f == PlatformSpecificStdOut) { + currentFake->console += str; + } + else { + currentFake->file += str; + } } + static void fclose_fake(PlatformSpecificFile) { } - static int putchar_fake(int c) - { - console += StringFrom((char)c); - return c; - } - static SimpleString file; - static SimpleString console; + + SimpleString file; + SimpleString console; + + static FakeOutput* currentFake; private: FOpenFunc SaveFOpen; FPutsFunc SaveFPuts; FCloseFunc SaveFClose; - PutcharFunc SavePutchar; }; -SimpleString FakeOutput::console = ""; -SimpleString FakeOutput::file = ""; +FakeOutput* FakeOutput::currentFake = NULLPTR; TEST(CommandLineTestRunner, realJunitOutputShouldBeCreatedAndWorkProperly) { const char* argv[] = { "tests.exe", "-ojunit", "-v", "-kpackage", }; - FakeOutput* fakeOutput = new FakeOutput; /* UT_PTR_SET() is not reentrant */ + FakeOutput fakeOutput; /* UT_PTR_SET() is not reentrant */ CommandLineTestRunner commandLineTestRunner(4, argv, ®istry); commandLineTestRunner.runAllTestsMain(); - delete fakeOutput; /* Original output must be restored before further output occurs */ + fakeOutput.restoreOriginals(); + + STRCMP_CONTAINS(" + +TEST_GROUP(StandardCppLibrary) +{ +}; + +#if defined(__cplusplus) && __cplusplus >= 201402L + +TEST(StandardCppLibrary, UniquePtrConversationToBool) +{ + auto const aNull = std::unique_ptr(NULLPTR); + CHECK_FALSE(aNull); + + auto const notNull = std::make_unique(1); + CHECK_TRUE(notNull); +} + +#endif + +#endif + diff --git a/tests/CppUTest/DummyMemoryLeakDetector.cpp b/tests/CppUTest/DummyMemoryLeakDetector.cpp new file mode 100644 index 000000000..dc28bab68 --- /dev/null +++ b/tests/CppUTest/DummyMemoryLeakDetector.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "CppUTest/TestHarness.h" +#include "CppUTest/MemoryLeakDetector.h" +#include "DummyMemoryLeakDetector.h" + +DummyMemoryLeakDetector::DummyMemoryLeakDetector(MemoryLeakFailure* reporter) : MemoryLeakDetector(reporter) +{ + memoryLeakDetectorWasDeleted = false; +} + +DummyMemoryLeakDetector::~DummyMemoryLeakDetector() +{ + memoryLeakDetectorWasDeleted = true; +} + +bool DummyMemoryLeakDetector::wasDeleted() +{ + return memoryLeakDetectorWasDeleted; +} + +bool DummyMemoryLeakDetector::memoryLeakDetectorWasDeleted = false; + +DummyMemoryLeakFailure::DummyMemoryLeakFailure() + : MemoryLeakFailure() +{ + memoryLeakFailureWasDelete = false; +} + +DummyMemoryLeakFailure::~DummyMemoryLeakFailure() +{ + memoryLeakFailureWasDelete = true; +} + +bool DummyMemoryLeakFailure::wasDeleted() +{ + return memoryLeakFailureWasDelete; +} + +void DummyMemoryLeakFailure::fail(char*) +{ +} + +bool DummyMemoryLeakFailure::memoryLeakFailureWasDelete = false; + + + diff --git a/tests/AllTests.h b/tests/CppUTest/DummyMemoryLeakDetector.h similarity index 67% rename from tests/AllTests.h rename to tests/CppUTest/DummyMemoryLeakDetector.h index 9e2fb1649..73824af27 100644 --- a/tests/AllTests.h +++ b/tests/CppUTest/DummyMemoryLeakDetector.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -25,19 +25,31 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -//Include this in the test main to execute these tests -IMPORT_TEST_GROUP( Utest); -IMPORT_TEST_GROUP( Failure); -IMPORT_TEST_GROUP( TestOutput); -IMPORT_TEST_GROUP( SimpleString); -IMPORT_TEST_GROUP( TestInstaller); -IMPORT_TEST_GROUP( NullTest); -IMPORT_TEST_GROUP( MemoryLeakWarningTest); -IMPORT_TEST_GROUP( TestHarness_c); -IMPORT_TEST_GROUP( CommandLineTestRunner); -IMPORT_TEST_GROUP( JUnitOutputTest); -IMPORT_TEST_GROUP( MemoryLeakDetectorTest); +#ifndef DUMMYMEMORYLEAKDETECTOR_H +#define DUMMYMEMORYLEAKDETECTOR_H -/* In allTest.cpp */ -IMPORT_TEST_GROUP(CheatSheet); +class DummyMemoryLeakDetector : public MemoryLeakDetector +{ +public: + DummyMemoryLeakDetector(MemoryLeakFailure* reporter); + virtual ~DummyMemoryLeakDetector() CPPUTEST_DESTRUCTOR_OVERRIDE; + static bool wasDeleted(); +private: + static bool memoryLeakDetectorWasDeleted; +}; + +class DummyMemoryLeakFailure : public MemoryLeakFailure +{ +public: + DummyMemoryLeakFailure(); + + virtual ~DummyMemoryLeakFailure() CPPUTEST_DESTRUCTOR_OVERRIDE; + static bool wasDeleted(); + virtual void fail(char*) CPPUTEST_OVERRIDE; + +private: + static bool memoryLeakFailureWasDelete; +}; + +#endif /* DUMMYMEMORYLEAKDETECTOR_H */ diff --git a/tests/JUnitOutputTest.cpp b/tests/CppUTest/JUnitOutputTest.cpp similarity index 66% rename from tests/JUnitOutputTest.cpp rename to tests/CppUTest/JUnitOutputTest.cpp index 159253799..32b5654d4 100644 --- a/tests/JUnitOutputTest.cpp +++ b/tests/CppUTest/JUnitOutputTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -42,7 +42,7 @@ class FileForJUnitOutputTests public: - FileForJUnitOutputTests(SimpleString filename, FileForJUnitOutputTests* next) : + FileForJUnitOutputTests(const SimpleString& filename, FileForJUnitOutputTests* next) : name_(filename), isOpen_(true), next_(next) {} FileForJUnitOutputTests* nextFile() @@ -94,7 +94,7 @@ class FileSystemForJUnitTestOutputTests FileForJUnitOutputTests* firstFile_; public: - FileSystemForJUnitTestOutputTests() : firstFile_(0) {} + FileSystemForJUnitTestOutputTests() : firstFile_(NULLPTR) {} ~FileSystemForJUnitTestOutputTests() { clear(); } void clear(void) @@ -114,7 +114,7 @@ class FileSystemForJUnitTestOutputTests int amountOfFiles() { int totalAmountOfFiles = 0; - for (FileForJUnitOutputTests* current = firstFile_; current != NULL; current = current->nextFile()) + for (FileForJUnitOutputTests* current = firstFile_; current != NULLPTR; current = current->nextFile()) totalAmountOfFiles++; return totalAmountOfFiles; } @@ -122,23 +122,23 @@ class FileSystemForJUnitTestOutputTests bool fileExists(const char* filename) { FileForJUnitOutputTests *searchedFile = file(filename); - return (searchedFile != NULL); + return (searchedFile != NULLPTR); } FileForJUnitOutputTests* file(const char* filename) { - for (FileForJUnitOutputTests* current = firstFile_; current != NULL; current = current->nextFile()) + for (FileForJUnitOutputTests* current = firstFile_; current != NULLPTR; current = current->nextFile()) if (current->name() == filename) return current; - return NULL; + return NULLPTR; } }; extern "C" { - static long millisTime = 0; + static unsigned long millisTime = 0; static const char* theTime = ""; - static long MockGetPlatformSpecificTimeInMillis() + static unsigned long MockGetPlatformSpecificTimeInMillis() { return millisTime; } @@ -156,13 +156,14 @@ class JUnitTestOutputTestRunner const char* currentGroupName_; UtestShell* currentTest_; bool firstTestInGroup_; - int timeTheTestTakes_; + unsigned int timeTheTestTakes_; + unsigned int numberOfChecksInTest_; TestFailure* testFailure_; public: - JUnitTestOutputTestRunner(TestResult result) : - result_(result), currentGroupName_(0), currentTest_(0), firstTestInGroup_(true), timeTheTestTakes_(0), testFailure_(0) + explicit JUnitTestOutputTestRunner(const TestResult& result) : + result_(result), currentGroupName_(NULLPTR), currentTest_(NULLPTR), firstTestInGroup_(true), timeTheTestTakes_(0), numberOfChecksInTest_(0), testFailure_(NULLPTR) { millisTime = 0; theTime = "1978-10-03T00:00:00"; @@ -185,6 +186,14 @@ class JUnitTestOutputTestRunner return *this; } + JUnitTestOutputTestRunner& endGroupAndClearTest() + { + endOfPreviousTestGroup(); + delete currentTest_; + currentTest_ = NULLPTR; + return *this; + } + void endOfPreviousTestGroup() { runPreviousTest(); @@ -193,7 +202,7 @@ class JUnitTestOutputTestRunner firstTestInGroup_ = true; } - currentGroupName_ = 0; + currentGroupName_ = NULLPTR; } JUnitTestOutputTestRunner& withGroup(const char* groupName) @@ -223,9 +232,25 @@ class JUnitTestOutputTestRunner return *this; } + JUnitTestOutputTestRunner& inFile(const char* fileName) + { + if(currentTest_) { + currentTest_->setFileName(fileName); + } + return *this; + } + + JUnitTestOutputTestRunner& onLine(size_t lineNumber) + { + if(currentTest_) { + currentTest_->setLineNumber(lineNumber); + } + return *this; + } + void runPreviousTest() { - if (currentTest_ == 0) return; + if (currentTest_ == NULLPTR) return; if (firstTestInGroup_) { result_.currentGroupStarted(currentTest_); @@ -234,17 +259,27 @@ class JUnitTestOutputTestRunner result_.currentTestStarted(currentTest_); millisTime += timeTheTestTakes_; + for(unsigned int i = 0; i < numberOfChecksInTest_; i++) { + result_.countCheck(); + } + numberOfChecksInTest_ = 0; if (testFailure_) { result_.addFailure(*testFailure_); delete testFailure_; - testFailure_ = 0; + testFailure_ = NULLPTR; } result_.currentTestEnded(currentTest_); } - JUnitTestOutputTestRunner& thatTakes(int timeElapsed) + JUnitTestOutputTestRunner& thatHasChecks(unsigned int numOfChecks) + { + numberOfChecksInTest_ = numOfChecks; + return *this; + } + + JUnitTestOutputTestRunner& thatTakes(unsigned int timeElapsed) { timeTheTestTakes_ = timeElapsed; return *this; @@ -255,7 +290,7 @@ class JUnitTestOutputTestRunner return *this; } - JUnitTestOutputTestRunner& thatFails(const char* message, const char* file, int line) + JUnitTestOutputTestRunner& thatFails(const char* message, const char* file, size_t line) { testFailure_ = new TestFailure( currentTest_, file, line, message); return *this; @@ -266,23 +301,39 @@ class JUnitTestOutputTestRunner theTime = newTime; return *this; } + + JUnitTestOutputTestRunner& thatPrints(const char* output) + { + runPreviousTest(); + result_.print(output); + return *this; + } }; extern "C" { static FileSystemForJUnitTestOutputTests fileSystem; + static FileForJUnitOutputTests* currentFile = NULLPTR; static PlatformSpecificFile mockFOpen(const char* filename, const char*) { - return fileSystem.openFile(filename); + currentFile = fileSystem.openFile(filename); + return currentFile; } + static void (*originalFPuts)(const char* str, PlatformSpecificFile file); static void mockFPuts(const char* str, PlatformSpecificFile file) { - ((FileForJUnitOutputTests*)file)->write(str); + if (file == currentFile) { + ((FileForJUnitOutputTests*)file)->write(str); + } + else { + originalFPuts(str, file); + } } static void mockFClose(PlatformSpecificFile file) { + currentFile = NULLPTR; ((FileForJUnitOutputTests*)file)->close(); } } @@ -294,9 +345,10 @@ TEST_GROUP(JUnitOutputTest) JUnitTestOutputTestRunner *testCaseRunner; FileForJUnitOutputTests* outputFile; - void setup() + void setup() CPPUTEST_OVERRIDE { UT_PTR_SET(PlatformSpecificFOpen, mockFOpen); + originalFPuts = PlatformSpecificFPuts; UT_PTR_SET(PlatformSpecificFPuts, mockFPuts); UT_PTR_SET(PlatformSpecificFClose, mockFClose); junitOutput = new JUnitTestOutput(); @@ -304,7 +356,7 @@ TEST_GROUP(JUnitOutputTest) testCaseRunner = new JUnitTestOutputTestRunner(*result); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete testCaseRunner; delete result; @@ -323,6 +375,16 @@ TEST(JUnitOutputTest, withOneTestGroupAndOneTestOnlyWriteToOneFile) CHECK(fileSystem.fileExists("cpputest_groupname.xml")); } +TEST(JUnitOutputTest, withReservedCharactersInPackageOrTestGroupUsesUnderscoresForFileName) +{ + junitOutput->setPackageName("p/a\\c?k%a*g:e|n\"ae."); + testCaseRunner->start() + .withGroup("g/r\\o?u%p*n:a|m\"eere").withTest("testname") + .end(); + + CHECK(fileSystem.fileExists("cpputest_p_a_c_k_a_g_e_n_a_m_e._g_r_o_u_p_n_a_m_e_h_ere.xml")); +} + TEST(JUnitOutputTest, withOneTestGroupAndOneTestOutputsValidXMLFiles) { testCaseRunner->start() @@ -333,7 +395,7 @@ TEST(JUnitOutputTest, withOneTestGroupAndOneTestOutputsValidXMLFiles) STRCMP_EQUAL("\n", outputFile->line(1)); } -TEST(JUnitOutputTest, withOneTestGroupAndOneTestoutputsTestSuiteStartAndEndBlocks) +TEST(JUnitOutputTest, withOneTestGroupAndOneTestOutputsTestSuiteStartAndEndBlocks) { testCaseRunner->start() .withGroup("groupname").withTest("testname") @@ -341,7 +403,7 @@ TEST(JUnitOutputTest, withOneTestGroupAndOneTestoutputsTestSuiteStartAndEndBlock outputFile = fileSystem.file("cpputest_groupname.xml"); STRCMP_EQUAL("\n", outputFile->line(2)); - STRCMP_EQUAL("", outputFile->lineFromTheBack(1)); + STRCMP_EQUAL("\n", outputFile->lineFromTheBack(1)); } TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainAnEmptyPropertiesBlock) @@ -383,7 +445,7 @@ TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainsATestCaseBlock outputFile = fileSystem.file("cpputest_groupname.xml"); - STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(5)); STRCMP_EQUAL("\n", outputFile->line(6)); } @@ -396,9 +458,9 @@ TEST(JUnitOutputTest, withOneTestGroupAndTwoTestCasesCreateCorrectTestgroupBlock outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); STRCMP_EQUAL("\n", outputFile->line(2)); - STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(5)); STRCMP_EQUAL("\n", outputFile->line(6)); - STRCMP_EQUAL("\n", outputFile->line(7)); + STRCMP_EQUAL("\n", outputFile->line(7)); STRCMP_EQUAL("\n", outputFile->line(8)); } @@ -423,9 +485,9 @@ TEST(JUnitOutputTest, withOneTestGroupAndMultipleTestCasesWithElapsedTime) outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); STRCMP_EQUAL("\n", outputFile->line(2)); - STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(5)); STRCMP_EQUAL("\n", outputFile->line(6)); - STRCMP_EQUAL("\n", outputFile->line(7)); + STRCMP_EQUAL("\n", outputFile->line(7)); STRCMP_EQUAL("\n", outputFile->line(8)); } @@ -438,7 +500,7 @@ TEST(JUnitOutputTest, withOneTestGroupAndOneFailingTest) outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); STRCMP_EQUAL("\n", outputFile->line(2)); - STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(5)); STRCMP_EQUAL("\n", outputFile->line(6)); STRCMP_EQUAL("\n", outputFile->line(7)); STRCMP_EQUAL("\n", outputFile->line(8)); @@ -455,7 +517,7 @@ TEST(JUnitOutputTest, withTwoTestGroupAndOneFailingTest) outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); STRCMP_EQUAL("\n", outputFile->line(2)); - STRCMP_EQUAL("\n", outputFile->line(7)); + STRCMP_EQUAL("\n", outputFile->line(7)); STRCMP_EQUAL("\n", outputFile->line(8)); } @@ -468,7 +530,7 @@ TEST(JUnitOutputTest, testFailureWithLessThanAndGreaterThanInsideIt) outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); - STRCMP_EQUAL("\n", outputFile->line(6)); + STRCMP_EQUAL("\n", outputFile->line(6)); } TEST(JUnitOutputTest, testFailureWithQuotesInIt) @@ -480,7 +542,7 @@ TEST(JUnitOutputTest, testFailureWithQuotesInIt) outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); - STRCMP_EQUAL("\n", outputFile->line(6)); + STRCMP_EQUAL("\n", outputFile->line(6)); } TEST(JUnitOutputTest, testFailureWithNewlineInIt) @@ -492,7 +554,7 @@ TEST(JUnitOutputTest, testFailureWithNewlineInIt) outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); - STRCMP_EQUAL("\n", outputFile->line(6)); + STRCMP_EQUAL("\n", outputFile->line(6)); } TEST(JUnitOutputTest, testFailureWithDifferentFileAndLine) @@ -507,6 +569,18 @@ TEST(JUnitOutputTest, testFailureWithDifferentFileAndLine) STRCMP_EQUAL("\n", outputFile->line(6)); } +TEST(JUnitOutputTest, testFailureWithAmpersandsAndLessThan) +{ + testCaseRunner->start() + .withGroup("testGroupWithFailingTest") + .withTest("FailingTestName").thatFails("&object1 < &object2", "importantFile", 999) + .end(); + + outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); + + STRCMP_EQUAL("\n", outputFile->line(6)); +} + TEST(JUnitOutputTest, testFailureWithAmpersands) { testCaseRunner->start() @@ -563,8 +637,8 @@ TEST(JUnitOutputTest, twoTestGroupsWriteToTwoDifferentFiles) .withTest("testName") .end(); - CHECK(fileSystem.file("cpputest_firstTestGroup.xml")); - CHECK(fileSystem.file("cpputest_secondTestGroup.xml")); + CHECK(fileSystem.file("cpputest_firstTestGroup.xml") != NULLPTR); + CHECK(fileSystem.file("cpputest_secondTestGroup.xml") != NULLPTR); } @@ -580,9 +654,9 @@ TEST(JUnitOutputTest, TestCaseBlockWithAPackageName) .withGroup("groupname").withTest("testname") .end(); - outputFile = fileSystem.file("cpputest_groupname.xml"); + outputFile = fileSystem.file("cpputest_packagename_groupname.xml"); - STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(5)); STRCMP_EQUAL("\n", outputFile->line(6)); } @@ -593,9 +667,103 @@ TEST(JUnitOutputTest, TestCaseBlockForIgnoredTest) .withGroup("groupname").withIgnoredTest("testname") .end(); - outputFile = fileSystem.file("cpputest_groupname.xml"); + outputFile = fileSystem.file("cpputest_packagename_groupname.xml"); - STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(5)); STRCMP_EQUAL("\n", outputFile->line(6)); STRCMP_EQUAL("\n", outputFile->line(7)); } + +TEST(JUnitOutputTest, TestCaseWithTestLocation) +{ + junitOutput->setPackageName("packagename"); + testCaseRunner->start() + .withGroup("groupname") + .withTest("testname").inFile("MySource.c").onLine(159) + .end(); + + outputFile = fileSystem.file("cpputest_packagename_groupname.xml"); + + STRCMP_EQUAL("\n", outputFile->line(5)); +} + +TEST(JUnitOutputTest, MultipleTestCaseWithTestLocations) +{ + testCaseRunner->start() + .withGroup("twoTestsGroup") + .withTest("firstTestName").inFile("MyFirstSource.c").onLine(846) + .withTest("secondTestName").inFile("MySecondSource.c").onLine(513) + .end(); + + outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); + + STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(7)); +} + +TEST(JUnitOutputTest, TestCaseBlockWithAssertions) +{ + junitOutput->setPackageName("packagename"); + testCaseRunner->start() + .withGroup("groupname") + .withTest("testname") + .thatHasChecks(24) + .end(); + + outputFile = fileSystem.file("cpputest_packagename_groupname.xml"); + + STRCMP_EQUAL("\n", outputFile->line(5)); +} + +TEST(JUnitOutputTest, MultipleTestCaseBlocksWithAssertions) +{ + testCaseRunner->start() + .withGroup("twoTestsGroup") + .withTest("firstTestName").thatHasChecks(456) + .withTest("secondTestName").thatHasChecks(567) + .end(); + + outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); + + STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(7)); +} + +TEST(JUnitOutputTest, MultipleTestCasesInDifferentGroupsWithAssertions) +{ + testCaseRunner->start() + .withGroup("groupOne") + .withTest("testA").thatHasChecks(456) + .endGroupAndClearTest() + .withGroup("groupTwo") + .withTest("testB").thatHasChecks(678) + .end(); + + outputFile = fileSystem.file("cpputest_groupOne.xml"); + STRCMP_EQUAL("\n", outputFile->line(5)); + + outputFile = fileSystem.file("cpputest_groupTwo.xml"); + STRCMP_EQUAL("\n", outputFile->line(5)); +} + +TEST(JUnitOutputTest, UTPRINTOutputInJUnitOutput) +{ + testCaseRunner->start() + .withGroup("groupname") + .withTest("testname").thatPrints("someoutput") + .end(); + + outputFile = fileSystem.file("cpputest_groupname.xml"); + STRCMP_EQUAL("someoutput\n", outputFile->lineFromTheBack(3)); +} + +TEST(JUnitOutputTest, UTPRINTOutputInJUnitOutputWithSpecials) +{ + testCaseRunner->start() + .withGroup("groupname") + .withTest("testname").thatPrints("The in \"Spain\"\nGoes\r \\mainly\\ down the Dr&in\n") + .end(); + + outputFile = fileSystem.file("cpputest_groupname.xml"); + STRCMP_EQUAL("The <rain> in "Spain" Goes \\mainly\\ down the Dr&in \n", outputFile->lineFromTheBack(3)); +} diff --git a/tests/MemoryLeakDetectorTest.cpp b/tests/CppUTest/MemoryLeakDetectorTest.cpp similarity index 88% rename from tests/MemoryLeakDetectorTest.cpp rename to tests/CppUTest/MemoryLeakDetectorTest.cpp index 13865cba9..825ed312e 100644 --- a/tests/MemoryLeakDetectorTest.cpp +++ b/tests/CppUTest/MemoryLeakDetectorTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -33,11 +33,11 @@ class MemoryLeakFailureForTest: public MemoryLeakFailure { public: - virtual ~MemoryLeakFailureForTest() + virtual ~MemoryLeakFailureForTest() CPPUTEST_DESTRUCTOR_OVERRIDE { } - virtual void fail(char* fail_string) + virtual void fail(char* fail_string) CPPUTEST_OVERRIDE { *message = fail_string; } @@ -56,15 +56,15 @@ class NewAllocatorForMemoryLeakDetectionTest: public TestMemoryAllocator int alloc_called; int free_called; - char* alloc_memory(size_t size, const char*, int) + char* alloc_memory(size_t size, const char*, size_t) CPPUTEST_OVERRIDE { alloc_called++; return TestMemoryAllocator::alloc_memory(size, "file", 1); } - void free_memory(char* memory, const char* file, int line) + void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE { free_called++; - TestMemoryAllocator::free_memory(memory, file, line); + TestMemoryAllocator::free_memory(memory, size, file, line); } }; @@ -81,27 +81,27 @@ class AllocatorForMemoryLeakDetectionTest: public TestMemoryAllocator int allocMemoryLeakNodeCalled; int freeMemoryLeakNodeCalled; - char* alloc_memory(size_t size, const char* file, int line) + char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE { alloc_called++; return TestMemoryAllocator::alloc_memory(size, file, line); } - void free_memory(char* memory, const char* file, int line) + void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE { free_called++; - TestMemoryAllocator::free_memory(memory, file, line); + TestMemoryAllocator::free_memory(memory, size, file, line); } - char* allocMemoryLeakNode(size_t size) + char* allocMemoryLeakNode(size_t size) CPPUTEST_OVERRIDE { allocMemoryLeakNodeCalled++; return TestMemoryAllocator::alloc_memory(size, __FILE__, __LINE__); } - void freeMemoryLeakNode(char* memory) + void freeMemoryLeakNode(char* memory) CPPUTEST_OVERRIDE { freeMemoryLeakNodeCalled++; - TestMemoryAllocator::free_memory(memory, __FILE__, __LINE__); + TestMemoryAllocator::free_memory(memory, 0, __FILE__, __LINE__); } }; @@ -111,7 +111,7 @@ TEST_GROUP(MemoryLeakDetectorTest) MemoryLeakFailureForTest *reporter; AllocatorForMemoryLeakDetectionTest* testAllocator; - void setup() + void setup() CPPUTEST_OVERRIDE { reporter = new MemoryLeakFailureForTest; detector = new MemoryLeakDetector(reporter); @@ -120,7 +120,7 @@ TEST_GROUP(MemoryLeakDetectorTest) detector->startChecking(); reporter->message = new SimpleString(); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete reporter->message; delete detector; @@ -442,7 +442,7 @@ TEST(MemoryLeakDetectorTest, memoryCorruption) TEST(MemoryLeakDetectorTest, safelyDeleteNULL) { - detector->deallocMemory(defaultNewAllocator(), 0); + detector->deallocMemory(defaultNewAllocator(), NULLPTR); STRCMP_EQUAL("", reporter->message->asCharString()); } @@ -478,6 +478,49 @@ TEST(MemoryLeakDetectorTest, periodChecking) detector->deallocMemory(defaultMallocAllocator(), mem); } +TEST(MemoryLeakDetectorTest, defaultAllocationStageIsZero) +{ + LONGS_EQUAL(0, detector->getCurrentAllocationStage()); +} + +TEST(MemoryLeakDetectorTest, canFreeNoAllocations) +{ + detector->deallocAllMemoryInCurrentAllocationStage(); + LONGS_EQUAL(0, detector->getCurrentAllocationStage()); +} + +TEST(MemoryLeakDetectorTest, increaseAllocationStage) +{ + detector->increaseAllocationStage(); + LONGS_EQUAL(1, detector->getCurrentAllocationStage()); +} + +TEST(MemoryLeakDetectorTest, decreaseAllocationStage) +{ + detector->increaseAllocationStage(); + detector->decreaseAllocationStage(); + LONGS_EQUAL(0, detector->getCurrentAllocationStage()); +} + +TEST(MemoryLeakDetectorTest, freeAllMemoryInCurrentAllocationStage) +{ + detector->increaseAllocationStage(); + detector->allocMemory(defaultMallocAllocator(), 2); + detector->allocMemory(defaultMallocAllocator(), 2); + detector->deallocAllMemoryInCurrentAllocationStage(); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); +} + +TEST(MemoryLeakDetectorTest, freeOnlyTheMemoryInTheAllocationStage) +{ + char* mem = detector->allocMemory(defaultMallocAllocator(), 2); + detector->increaseAllocationStage(); + detector->allocMemory(defaultMallocAllocator(), 2); + detector->deallocAllMemoryInCurrentAllocationStage(); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); + detector->deallocMemory(defaultMallocAllocator(), mem); +} + TEST(MemoryLeakDetectorTest, allocateWithANullAllocatorCausesNoProblems) { char* mem = detector->allocMemory(NullUnknownAllocator::defaultAllocator(), 2); @@ -496,7 +539,7 @@ TEST(MemoryLeakDetectorTest, invalidateMemory) TEST(MemoryLeakDetectorTest, invalidateMemoryNULLShouldWork) { - detector->invalidateMemory(NULL); + detector->invalidateMemory(NULLPTR); } TEST_GROUP(MemoryLeakDetectorListTest) @@ -514,7 +557,7 @@ TEST(MemoryLeakDetectorListTest, clearAllAccountingIsWorkingProperly) listForTesting.clearAllAccounting(mem_leak_period_enabled); - CHECK(NULL == listForTesting.getFirstLeak(mem_leak_period_enabled)); + POINTERS_EQUAL(NULLPTR, listForTesting.getFirstLeak(mem_leak_period_enabled)); CHECK(&node3 == listForTesting.getFirstLeak(mem_leak_period_disabled)); } @@ -635,15 +678,15 @@ TEST_GROUP(ReallocBugReported) TEST(ReallocBugReported, CanSafelyDoAReallocWithANewAllocator) { MemoryLeakDetector detector(&reporter); - char* mem = detector.allocMemory(getCurrentNewAllocator(), 5, "file", 1); - mem = detector.reallocMemory(getCurrentNewAllocator(), mem, 19, "file", 1); - detector.deallocMemory(getCurrentNewAllocator(), mem); + char* mem = detector.allocMemory(defaultNewAllocator(), 5, "file", 1); + mem = detector.reallocMemory(defaultNewAllocator(), mem, 19, "file", 1); + detector.deallocMemory(defaultNewAllocator(), mem); } TEST(ReallocBugReported, CanSafelyDoAReallocWithAMallocAllocator) { MemoryLeakDetector detector(&reporter); - char* mem = detector.allocMemory(getCurrentMallocAllocator(), 5, "file", 1, true); - mem = detector.reallocMemory(getCurrentMallocAllocator(), mem, 19, "file", 1, true); - detector.deallocMemory(getCurrentMallocAllocator(), mem, true); + char* mem = detector.allocMemory(defaultMallocAllocator(), 5, "file", 1, true); + mem = detector.reallocMemory(defaultMallocAllocator(), mem, 19, "file", 1, true); + detector.deallocMemory(defaultMallocAllocator(), mem, true); } diff --git a/tests/MemoryLeakWarningTest.cpp b/tests/CppUTest/MemoryLeakWarningTest.cpp similarity index 69% rename from tests/MemoryLeakWarningTest.cpp rename to tests/CppUTest/MemoryLeakWarningTest.cpp index 556f5091d..d4a6ea6fc 100644 --- a/tests/MemoryLeakWarningTest.cpp +++ b/tests/CppUTest/MemoryLeakWarningTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,34 +34,17 @@ #include "CppUTest/TestTestingFixture.h" #include "CppUTest/TestHarness_c.h" #include "CppUTest/SimpleMutex.h" - -static char* leak1; -static long* leak2; - -class DummyReporter: public MemoryLeakFailure -{ -public: - virtual ~DummyReporter() - { - } - virtual void fail(char* /*fail_string*/) - { - } -}; - -static MemoryLeakDetector* detector; -static MemoryLeakWarningPlugin* memPlugin; -static DummyReporter dummy; -static TestMemoryAllocator* allocator; +#include "DummyMemoryLeakDetector.h" TEST_GROUP(MemoryLeakWarningLocalDetectorTest) { + DummyMemoryLeakFailure dummy; }; TEST(MemoryLeakWarningLocalDetectorTest, localDetectorReturnsNewGlobalWhenNoneWasSet) { - MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", NULL); - CHECK(0 != memoryLeakWarningPlugin.getMemoryLeakDetector()); + MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", NULLPTR); + CHECK(NULLPTR != memoryLeakWarningPlugin.getMemoryLeakDetector()); } TEST(MemoryLeakWarningLocalDetectorTest, localDetectorIsTheOneSpecifiedInConstructor) @@ -74,29 +57,37 @@ TEST(MemoryLeakWarningLocalDetectorTest, localDetectorIsTheOneSpecifiedInConstru TEST(MemoryLeakWarningLocalDetectorTest, localDetectorIsGlobalDetector) { MemoryLeakDetector* globalDetector = MemoryLeakWarningPlugin::getGlobalDetector(); - MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", NULL); + MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", NULLPTR); MemoryLeakDetector* localDetector = memoryLeakWarningPlugin.getMemoryLeakDetector(); POINTERS_EQUAL(globalDetector, localDetector); } +static char* leak1; +static long* leak2; + +static MemoryLeakDetector* detector; +static MemoryLeakWarningPlugin* memPlugin; +static TestMemoryAllocator* allocator; TEST_GROUP(MemoryLeakWarningTest) { + DummyMemoryLeakFailure dummy; TestTestingFixture* fixture; - void setup() + void setup() CPPUTEST_OVERRIDE { fixture = new TestTestingFixture(); detector = new MemoryLeakDetector(&dummy); allocator = new TestMemoryAllocator; memPlugin = new MemoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", detector); - fixture->registry_->installPlugin(memPlugin); + fixture->installPlugin(memPlugin); memPlugin->enable(); - leak1 = 0; - leak2 = 0; + leak1 = NULLPTR; + leak2 = NULLPTR; } - void teardown() + + void teardown() CPPUTEST_OVERRIDE { detector->deallocMemory(allocator, leak1); detector->deallocMemory(allocator, leak2); @@ -108,21 +99,59 @@ TEST_GROUP(MemoryLeakWarningTest) } }; -static void _testTwoLeaks() +static void testTwoLeaks_() { leak1 = detector->allocMemory(allocator, 10); leak2 = (long*) (void*) detector->allocMemory(allocator, 4); } +#if CPPUTEST_USE_MEM_LEAK_DETECTION + TEST(MemoryLeakWarningTest, TwoLeaks) { - fixture->setTestFunction(_testTwoLeaks); + fixture->setTestFunction(testTwoLeaks_); fixture->runAllTests(); + LONGS_EQUAL(1, fixture->getFailureCount()); - fixture->assertPrintContains("Total number of leaks: 2"); } -static void _testIgnore2() +#else + +TEST(MemoryLeakWarningTest, TwoLeaks) +{ + fixture->setTestFunction(testTwoLeaks_); + fixture->runAllTests(); + + LONGS_EQUAL(0, fixture->getFailureCount()); +} + +#endif + + +static void testLeakWarningWithPluginDisabled_() +{ + memPlugin->expectLeaksInTest(1); + leak1 = (char*) cpputest_malloc_location_with_leak_detection(10, __FILE__, __LINE__); +} + +TEST(MemoryLeakWarningTest, LeakWarningWithPluginDisabled) +{ + fixture->setTestFunction(testLeakWarningWithPluginDisabled_); + + MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); + + fixture->runAllTests(); + + LONGS_EQUAL(0, fixture->getFailureCount()); + fixture->assertPrintContains("Warning: Expected 1 leak(s), but leak detection was disabled"); + + cpputest_free_location_with_leak_detection(leak1, __FILE__, __LINE__); + leak1 = NULLPTR; + + MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); +} + +static void testIgnore2_() { memPlugin->expectLeaksInTest(2); leak1 = detector->allocMemory(allocator, 10); @@ -131,12 +160,12 @@ static void _testIgnore2() TEST(MemoryLeakWarningTest, Ignore2) { - fixture->setTestFunction(_testIgnore2); + fixture->setTestFunction(testIgnore2_); fixture->runAllTests(); LONGS_EQUAL(0, fixture->getFailureCount()); } -static void _failAndLeakMemory() +static void failAndLeakMemory_() { leak1 = detector->allocMemory(allocator, 10); FAIL(""); @@ -144,36 +173,11 @@ static void _failAndLeakMemory() TEST(MemoryLeakWarningTest, FailingTestDoesNotReportMemoryLeaks) { - fixture->setTestFunction(_failAndLeakMemory); + fixture->setTestFunction(failAndLeakMemory_); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); } -static bool memoryLeakDetectorWasDeleted = false; -static bool memoryLeakFailureWasDelete = false; - -class DummyMemoryLeakDetector : public MemoryLeakDetector -{ -public: - DummyMemoryLeakDetector(MemoryLeakFailure* reporter) : MemoryLeakDetector(reporter) {} - virtual ~DummyMemoryLeakDetector() - { - memoryLeakDetectorWasDeleted = true; - } -}; - -class DummyMemoryLeakFailure : public MemoryLeakFailure -{ - virtual ~DummyMemoryLeakFailure() - { - memoryLeakFailureWasDelete = true; - } - virtual void fail(char*) - { - } -}; - - static bool cpputestHasCrashed; TEST_GROUP(MemoryLeakWarningGlobalDetectorTest) @@ -184,20 +188,20 @@ TEST_GROUP(MemoryLeakWarningGlobalDetectorTest) DummyMemoryLeakDetector * dummyDetector; MemoryLeakFailure* dummyReporter; + GlobalMemoryAllocatorStash memoryAllocatorStash; + static void crashMethod() { cpputestHasCrashed = true; } - void setup() + void setup() CPPUTEST_OVERRIDE { + memoryAllocatorStash.save(); detector = MemoryLeakWarningPlugin::getGlobalDetector(); failureReporter = MemoryLeakWarningPlugin::getGlobalFailureReporter(); - memoryLeakDetectorWasDeleted = false; - memoryLeakFailureWasDelete = false; - - MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); + MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); dummyReporter = new DummyMemoryLeakFailure; dummyDetector = new DummyMemoryLeakDetector(dummyReporter); @@ -206,31 +210,32 @@ TEST_GROUP(MemoryLeakWarningGlobalDetectorTest) cpputestHasCrashed = false; } - void teardown() + void teardown() CPPUTEST_OVERRIDE { - MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); - if (!memoryLeakDetectorWasDeleted) delete dummyDetector; - if (!memoryLeakFailureWasDelete) delete dummyReporter; + MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); + + MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); + if (!DummyMemoryLeakDetector::wasDeleted()) delete dummyDetector; + if (!DummyMemoryLeakFailure::wasDeleted()) delete dummyReporter; MemoryLeakWarningPlugin::setGlobalDetector(detector, failureReporter); - MemoryLeakWarningPlugin::turnOnNewDeleteOverloads(); + + MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); UtestShell::resetCrashMethod(); - setCurrentMallocAllocatorToDefault(); - setCurrentNewAllocatorToDefault(); - setCurrentNewArrayAllocatorToDefault(); + memoryAllocatorStash.restore(); } }; TEST(MemoryLeakWarningGlobalDetectorTest, turnOffNewOverloadsCausesNoAdditionalLeaks) { - int storedAmountOfLeaks = detector->totalMemoryLeaks(mem_leak_period_all); + size_t storedAmountOfLeaks = detector->totalMemoryLeaks(mem_leak_period_all); char* arrayMemory = new char[100]; char* nonArrayMemory = new char; char* mallocMemory = (char*) cpputest_malloc_location_with_leak_detection(10, "file", 10); - char* reallocMemory = (char*) cpputest_realloc_location_with_leak_detection(NULL, 10, "file", 10); + char* reallocMemory = (char*) cpputest_realloc_location_with_leak_detection(NULLPTR, 10, "file", 10); LONGS_EQUAL(storedAmountOfLeaks, detector->totalMemoryLeaks(mem_leak_period_all)); @@ -246,8 +251,8 @@ TEST(MemoryLeakWarningGlobalDetectorTest, destroyGlobalDetector) MemoryLeakWarningPlugin::destroyGlobalDetector(); - CHECK(memoryLeakDetectorWasDeleted); - CHECK(memoryLeakFailureWasDelete); + CHECK(DummyMemoryLeakDetector::wasDeleted()); + CHECK(DummyMemoryLeakFailure::wasDeleted()); } TEST(MemoryLeakWarningGlobalDetectorTest, MemoryWarningPluginCanBeSetToDestroyTheGlobalDetector) @@ -258,67 +263,73 @@ TEST(MemoryLeakWarningGlobalDetectorTest, MemoryWarningPluginCanBeSetToDestroyTh delete plugin; - CHECK(memoryLeakDetectorWasDeleted); + CHECK(DummyMemoryLeakDetector::wasDeleted()); } -#ifndef CPPUTEST_MEM_LEAK_DETECTION_DISABLED +#if CPPUTEST_USE_MEM_LEAK_DETECTION TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorNew) { MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter); - MemoryLeakWarningPlugin::turnOnNewDeleteOverloads(); + MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); crash_on_allocation_number(1); char* memory = new char[100]; CHECK(cpputestHasCrashed); delete [] memory; + MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); } TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorNewArray) { MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter); - MemoryLeakWarningPlugin::turnOnNewDeleteOverloads(); + MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); crash_on_allocation_number(1); char* memory = new char; CHECK(cpputestHasCrashed); delete memory; + + MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); } TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorMalloc) { MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter); - MemoryLeakWarningPlugin::turnOnNewDeleteOverloads(); + MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); crash_on_allocation_number(1); char* memory = (char*) cpputest_malloc(10); CHECK(cpputestHasCrashed); cpputest_free(memory); + + MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); } TEST(MemoryLeakWarningGlobalDetectorTest, gettingTheGlobalDetectorDoesNotRestoreTheMemoryLeakOverloadsWhenTheyWereAlreadyOff) { - MemoryLeakWarningPlugin::setGlobalDetector(NULL, NULL); + MemoryLeakWarningPlugin::setGlobalDetector(NULLPTR, NULLPTR); MemoryLeakDetector* temporaryDetector = MemoryLeakWarningPlugin::getGlobalDetector(); MemoryLeakFailure* temporaryReporter = MemoryLeakWarningPlugin::getGlobalFailureReporter(); - MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); + MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); + bool areNewDeleteOverloaded = MemoryLeakWarningPlugin::areNewDeleteOverloaded(); - MemoryLeakWarningPlugin::turnOnNewDeleteOverloads(); + MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); CHECK(!areNewDeleteOverloaded); - MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); delete temporaryReporter; delete temporaryDetector; + MemoryLeakWarningPlugin::setGlobalDetector(NULLPTR, NULLPTR); } TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOn) { - MemoryLeakWarningPlugin::turnOnNewDeleteOverloads(); + MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); CHECK(MemoryLeakWarningPlugin::areNewDeleteOverloaded()); MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); @@ -329,10 +340,32 @@ TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOff) MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); bool areNewDeleteOverloaded = MemoryLeakWarningPlugin::areNewDeleteOverloaded(); - MemoryLeakWarningPlugin::turnOnNewDeleteOverloads(); + MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); CHECK(!areNewDeleteOverloaded); } +TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOnWithRestore) +{ + MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); + CHECK(MemoryLeakWarningPlugin::areNewDeleteOverloaded()); + MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); +} + +TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOffWithSaveDisable) +{ + MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); + CHECK(!MemoryLeakWarningPlugin::areNewDeleteOverloaded()); + MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); +} + +TEST(MemoryLeakWarningGlobalDetectorTest, threadSafeMemoryLeakDetectorOverloadsAreAlsoOverloaded) +{ + MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); + MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads(); + CHECK(MemoryLeakWarningPlugin::areNewDeleteOverloaded()); + MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); + MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); +} #endif @@ -341,7 +374,7 @@ TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOff) TEST(MemoryLeakWarningGlobalDetectorTest, turnOffNewOverloadsNoThrowCausesNoAdditionalLeaks) { #undef new - int storedAmountOfLeaks = detector->totalMemoryLeaks(mem_leak_period_all); + size_t storedAmountOfLeaks = detector->totalMemoryLeaks(mem_leak_period_all); char* nonMemoryNoThrow = new (std::nothrow) char; char* nonArrayMemoryNoThrow = new (std::nothrow) char[10]; @@ -349,15 +382,15 @@ TEST(MemoryLeakWarningGlobalDetectorTest, turnOffNewOverloadsNoThrowCausesNoAddi LONGS_EQUAL(storedAmountOfLeaks, detector->totalMemoryLeaks(mem_leak_period_all)); - delete nonMemoryNoThrow; - delete [] nonArrayMemoryNoThrow; - delete [] nonArrayMemoryThrow; + ::operator delete(nonMemoryNoThrow, std::nothrow); + ::operator delete[](nonArrayMemoryNoThrow, std::nothrow); + ::operator delete[](nonArrayMemoryThrow, std::nothrow); #ifdef CPPUTEST_USE_NEW_MACROS #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif } -#ifndef CPPUTEST_MEM_LEAK_DETECTION_DISABLED +#if CPPUTEST_USE_MEM_LEAK_DETECTION static int mutexLockCount = 0; static int mutexUnlockCount = 0; @@ -372,11 +405,9 @@ static void StubMutexUnlock(PlatformSpecificMutex) mutexUnlockCount++; } - - TEST_GROUP(MemoryLeakWarningThreadSafe) { - void setup() + void setup() CPPUTEST_OVERRIDE { UT_PTR_SET(PlatformSpecificMutexLock, StubMutexLock); UT_PTR_SET(PlatformSpecificMutexUnlock, StubMutexUnlock); @@ -385,14 +416,14 @@ TEST_GROUP(MemoryLeakWarningThreadSafe) mutexUnlockCount = 0; } - void teardown() + void teardown() CPPUTEST_OVERRIDE { } }; TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeMallocFreeReallocOverloadsDebug) { - int storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all); + size_t storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all); MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads(); @@ -414,12 +445,12 @@ TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeMallocFreeReallocOverloadsDebu CHECK_EQUAL(3, mutexLockCount); CHECK_EQUAL(3, mutexUnlockCount); - MemoryLeakWarningPlugin::turnOnNewDeleteOverloads(); + MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); } TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloadsDebug) { - int storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all); + size_t storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all); MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads(); @@ -437,7 +468,7 @@ TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloadsDebug) CHECK_EQUAL(4, mutexLockCount); CHECK_EQUAL(4, mutexUnlockCount); - MemoryLeakWarningPlugin::turnOnNewDeleteOverloads(); + MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); } #ifdef __clang__ @@ -455,7 +486,7 @@ TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloads) { #undef new - int storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all); + size_t storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all); MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads(); int *n = new int; @@ -476,7 +507,7 @@ TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloads) CHECK_EQUAL(8, mutexLockCount); CHECK_EQUAL(8, mutexUnlockCount); - MemoryLeakWarningPlugin::turnOnNewDeleteOverloads(); + MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); #ifdef CPPUTEST_USE_NEW_MACROS #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif diff --git a/tests/MemoryOperatorOverloadTest.cpp b/tests/CppUTest/MemoryOperatorOverloadTest.cpp similarity index 62% rename from tests/MemoryOperatorOverloadTest.cpp rename to tests/CppUTest/MemoryOperatorOverloadTest.cpp index 343f16988..df4b212d5 100644 --- a/tests/MemoryOperatorOverloadTest.cpp +++ b/tests/CppUTest/MemoryOperatorOverloadTest.cpp @@ -10,34 +10,20 @@ #include "CppUTest/TestHarness_c.h" #include "AllocationInCFile.h" + TEST_GROUP(BasicBehavior) { }; TEST(BasicBehavior, CanDeleteNullPointers) { - delete (char*) NULL; - delete [] (char*) NULL; -} - -#ifndef CPPUTEST_MEM_LEAK_DETECTION_DISABLED - -TEST(BasicBehavior, deleteArrayInvalidatesMemory) -{ - unsigned char* memory = new unsigned char[10]; - PlatformSpecificMemset(memory, 0xAB, 10); - delete [] memory; - CHECK(memory[5] != 0xCB); + delete (char*) NULLPTR; + delete [] (char*) NULLPTR; } -TEST(BasicBehavior, deleteInvalidatesMemory) -{ - unsigned char* memory = new unsigned char; - *memory = 0xAD; - delete memory; - CHECK(*memory != 0xAD); -} +#if CPPUTEST_USE_MEM_LEAK_DETECTION +#if __cplusplus >= 201402L TEST(BasicBehavior, DeleteWithSizeParameterWorks) { char* charMemory = new char; @@ -45,28 +31,7 @@ TEST(BasicBehavior, DeleteWithSizeParameterWorks) ::operator delete(charMemory, sizeof(char)); ::operator delete[](charArrayMemory, sizeof(char)* 10); } - - -static void deleteUnallocatedMemory() -{ - delete (char*) 0x1234678; - FAIL("Should never come here"); // LCOV_EXCL_LINE -} // LCOV_EXCL_LINE - -TEST(BasicBehavior, deleteWillNotThrowAnExceptionWhenDeletingUnallocatedMemoryButCanStillCauseTestFailures) -{ - /* - * Test failure might cause an exception. But according to C++ standard, you aren't allowed - * to throw exceptions in the delete function. If you do that, it will call std::terminate. - * Therefore, the delete will need to fail without exceptions. - */ - MemoryLeakFailure* defaultReporter = MemoryLeakWarningPlugin::getGlobalFailureReporter(); - TestTestingFixture fixture; - fixture.setTestFunction(deleteUnallocatedMemory); - fixture.runAllTests(); - LONGS_EQUAL(1, fixture.getFailureCount()); - POINTERS_EQUAL(defaultReporter, MemoryLeakWarningPlugin::getGlobalFailureReporter()); -} +#endif #endif @@ -88,49 +53,125 @@ TEST(BasicBehavior, bothMallocAndFreeAreOverloaded) #endif -#if CPPUTEST_USE_MEM_LEAK_DETECTION - -TEST(BasicBehavior, freeInvalidatesMemory) -{ - unsigned char* memory = (unsigned char*) cpputest_malloc(sizeof(unsigned char)); - *memory = 0xAD; - cpputest_free(memory); - CHECK(*memory != 0xAD); -} -#endif - TEST_GROUP(MemoryLeakOverridesToBeUsedInProductionCode) { MemoryLeakDetector* memLeakDetector; - void setup() + void setup() CPPUTEST_OVERRIDE { memLeakDetector = MemoryLeakWarningPlugin::getGlobalDetector(); } }; +#if CPPUTEST_USE_MEM_LEAK_DETECTION + +#ifdef CPPUTEST_USE_NEW_MACROS + #undef new +#endif +TEST(MemoryLeakOverridesToBeUsedInProductionCode, newDeleteOverloadsWithIntLineWorks) +{ + const int line = 42; + char* leak = new("TestFile.cpp", line) char; + + size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); + STRCMP_NOCASE_CONTAINS("Allocated at: TestFile.cpp and line: 42.", memLeakDetector->report(mem_leak_period_checking)); + + ::operator delete (leak, "TestFile.cpp", line); + + LONGS_EQUAL(memLeaks-1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); +} + +TEST(MemoryLeakOverridesToBeUsedInProductionCode, newDeleteOverloadsWithSizeTLineWorks) +{ + const size_t line = 42; + char* leak = new("TestFile.cpp", line) char; + + size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); + STRCMP_NOCASE_CONTAINS("Allocated at: TestFile.cpp and line: 42.", memLeakDetector->report(mem_leak_period_checking)); + + ::operator delete (leak, "TestFile.cpp", line); + + LONGS_EQUAL(memLeaks-1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); +} + +TEST(MemoryLeakOverridesToBeUsedInProductionCode, newDeleteArrayOverloadsWithIntLineWorks) +{ + const int line = 42; + char* leak = new("TestFile.cpp", line) char[10]; + + size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); + STRCMP_NOCASE_CONTAINS("Allocated at: TestFile.cpp and line: 42.", memLeakDetector->report(mem_leak_period_checking)); + + ::operator delete [] (leak, "TestFile.cpp", line); + + LONGS_EQUAL(memLeaks-1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); +} + +TEST(MemoryLeakOverridesToBeUsedInProductionCode, newDeleteArrayOverloadsWithSizeTLineWorks) +{ + const size_t line = 42; + char* leak = new("TestFile.cpp", line) char[10]; + + size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); + STRCMP_NOCASE_CONTAINS("Allocated at: TestFile.cpp and line: 42.", memLeakDetector->report(mem_leak_period_checking)); + + ::operator delete [] (leak, "TestFile.cpp", line); + + LONGS_EQUAL(memLeaks-1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); +} +#ifdef CPPUTEST_USE_NEW_MACROS + #include "CppUTest/MemoryLeakDetectorNewMacros.h" // redefine the 'new' macro +#endif +#endif + #ifdef CPPUTEST_USE_MALLOC_MACROS TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocOverrideIsUsed) { - int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); + size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); void* memory = malloc(10); LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); free (memory); } +#ifdef CPPUTEST_USE_STRDUP_MACROS + +TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrdupOverrideIsUsed) +{ + size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); + char* memory = strdup("0123456789"); + LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); + free (memory); +} + +TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrndupOverrideIsUsed) +{ + size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); + char* memory = strndup("0123456789", 10); + LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); + free (memory); +} +#endif + #endif TEST(MemoryLeakOverridesToBeUsedInProductionCode, UseNativeMallocByTemporarlySwitchingOffMalloc) { - int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); + size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); #ifdef CPPUTEST_USE_MALLOC_MACROS #undef malloc #undef free #endif + +#if CPPUTEST_USE_STD_C_LIB void* memory = malloc(10); LONGS_EQUAL(memLeaks, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); free (memory); +#else + void* memory = PlatformSpecificMalloc(10); + LONGS_EQUAL(memLeaks, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); + PlatformSpecificFree (memory); +#endif #ifdef CPPUTEST_USE_MALLOC_MACROS #include "CppUTest/MemoryLeakDetectorMallocMacros.h" @@ -214,6 +255,22 @@ TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocOverrideWorks) freeAllocation(leak); } +#ifdef CPPUTEST_USE_STRDUP_MACROS +TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrdupOverrideWorks) +{ + char* leak = strdupAllocation(); + STRCMP_NOCASE_CONTAINS("AllocationInCFile.c", memLeakDetector->report(mem_leak_period_checking)); + freeAllocation(leak); +} + +TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrndupOverrideWorks) +{ + char* leak = strndupAllocation(); + STRCMP_NOCASE_CONTAINS("AllocationInCFile.c", memLeakDetector->report(mem_leak_period_checking)); + freeAllocation(leak); +} +#endif + TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocWithButFreeWithoutLeakDetectionDoesntCrash) { char* leak = mallocAllocation(); @@ -250,33 +307,34 @@ TEST(MemoryLeakOverridesToBeUsedInProductionCode, MemoryOverridesAreDisabled) TEST_GROUP(OutOfMemoryTestsForOperatorNew) { TestMemoryAllocator* no_memory_allocator; - void setup() + GlobalMemoryAllocatorStash memoryAllocatorStash; + void setup() CPPUTEST_OVERRIDE { + memoryAllocatorStash.save(); no_memory_allocator = new NullUnknownAllocator; setCurrentNewAllocator(no_memory_allocator); setCurrentNewArrayAllocator(no_memory_allocator); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { - setCurrentNewAllocatorToDefault(); - setCurrentNewArrayAllocatorToDefault(); + memoryAllocatorStash.restore(); delete no_memory_allocator; } }; #if CPPUTEST_USE_MEM_LEAK_DETECTION -#if CPPUTEST_USE_STD_CPP_LIB +#if CPPUTEST_HAVE_EXCEPTIONS TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorThrowsAnExceptionWhenUsingStdCppNew) { - CHECK_THROWS(std::bad_alloc, new char); + CHECK_THROWS(CPPUTEST_BAD_ALLOC, new char); } TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorThrowsAnExceptionWhenUsingStdCppNew) { - CHECK_THROWS(std::bad_alloc, new char[10]); + CHECK_THROWS(CPPUTEST_BAD_ALLOC, new char[10]); } TEST_GROUP(TestForExceptionsInConstructor) @@ -297,19 +355,19 @@ TEST(TestForExceptionsInConstructor,ConstructorThrowsAnExceptionAllocatedAsArray TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNull) { - POINTERS_EQUAL(NULL, new char); + POINTERS_EQUAL(NULLPTR, new char); } TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNull) { - POINTERS_EQUAL(NULL, new char[10]); + POINTERS_EQUAL(NULLPTR, new char[10]); } #endif #undef new -#if CPPUTEST_USE_STD_CPP_LIB +#if CPPUTEST_HAVE_EXCEPTIONS /* @@ -335,40 +393,49 @@ TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNull) * We (Bas Vodde and Terry Yin) suspect that in a real product, you wouldn't be able to detect the optimization and it's breaking of Standard C++. Therefore, * for now, we keep this hack in the test to fool the optimizer and hope nobody will ever notice this 'optimizer behavior' in a real product. * + * Update 2020: The gcc compiler implemented the same optimization, but it seems to be slightly smarter and discovered that we assign to a static variable. + * Thus it still optimized away the call to operator new. Did another bug report, but it is unlikely to get fixed. You can find it at: + * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94671 + * + * Changed the variable to be external so it would definitively be a mistake to optimize the call. + * */ -static char* some_memory; +extern char* some_memory; +char* some_memory; TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorThrowsAnExceptionWhenUsingStdCppNewWithoutOverride) { - CHECK_THROWS(std::bad_alloc, some_memory = new char); + CHECK_THROWS(CPPUTEST_BAD_ALLOC, some_memory = new char); } TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorThrowsAnExceptionWhenUsingStdCppNewWithoutOverride) { - CHECK_THROWS(std::bad_alloc, some_memory = new char[10]); + CHECK_THROWS(CPPUTEST_BAD_ALLOC, some_memory = new char[10]); } +#if CPPUTEST_USE_STD_CPP_LIB TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNullWithoutOverride) { - POINTERS_EQUAL(NULL, new (std::nothrow) char); + POINTERS_EQUAL(NULLPTR, new (std::nothrow) char); } TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNullWithoutOverride) { - POINTERS_EQUAL(NULL, new (std::nothrow) char[10]); + POINTERS_EQUAL(NULLPTR, new (std::nothrow) char[10]); } +#endif #else TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNullWithoutOverride) { - POINTERS_EQUAL(NULL, new char); + POINTERS_EQUAL(NULLPTR, new char); } TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNullWithoutOverride) { - POINTERS_EQUAL(NULL, new char[10]); + POINTERS_EQUAL(NULLPTR, new char[10]); } #endif diff --git a/tests/PluginTest.cpp b/tests/CppUTest/PluginTest.cpp similarity index 91% rename from tests/PluginTest.cpp rename to tests/CppUTest/PluginTest.cpp index cf1dba5ab..c9b74fd07 100644 --- a/tests/PluginTest.cpp +++ b/tests/CppUTest/PluginTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -44,13 +44,13 @@ class DummyPlugin: public TestPlugin { } - virtual void preTestAction(UtestShell&, TestResult&) + virtual void preTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE { preAction++; preActionSequence = sequenceNumber++; } - virtual void postTestAction(UtestShell&, TestResult&) + virtual void postTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE { postAction++; postActionSequence = sequenceNumber++; @@ -70,7 +70,7 @@ class DummyPluginWhichAcceptsParameters: public DummyPlugin { } - virtual bool parseArguments(int ac, const char** av, int index) + virtual bool parseArguments(int ac, const char *const *av, int index) CPPUTEST_OVERRIDE { SimpleString argument (av[index]); if (argument == "-paccept") @@ -86,19 +86,20 @@ TEST_GROUP(PluginTest) DummyPluginWhichAcceptsParameters* secondPlugin; DummyPlugin* thirdPlugin; TestTestingFixture *genFixture; - TestRegistry *registry; - void setup() + TestRegistry* registry; + + void setup() CPPUTEST_OVERRIDE { firstPlugin = new DummyPlugin(GENERIC_PLUGIN); secondPlugin = new DummyPluginWhichAcceptsParameters(GENERIC_PLUGIN2); thirdPlugin = new DummyPlugin(GENERIC_PLUGIN3); genFixture = new TestTestingFixture; - registry = genFixture->registry_; + registry = genFixture->getRegistry(); registry->installPlugin(firstPlugin); sequenceNumber = 1; } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete firstPlugin; delete secondPlugin; @@ -126,7 +127,7 @@ TEST(PluginTest, InstallMultiplePlugins) registry->installPlugin(thirdPlugin); CHECK_EQUAL(firstPlugin, registry->getPluginByName(GENERIC_PLUGIN)); CHECK_EQUAL(thirdPlugin, registry->getPluginByName(GENERIC_PLUGIN3)); - CHECK_EQUAL(0, registry->getPluginByName("I do not exist")); + POINTERS_EQUAL(NULLPTR, registry->getPluginByName("I do not exist")); } TEST(PluginTest, ActionsAllRun) diff --git a/tests/PreprocessorTest.cpp b/tests/CppUTest/PreprocessorTest.cpp similarity index 96% rename from tests/PreprocessorTest.cpp rename to tests/CppUTest/PreprocessorTest.cpp index 3207972f6..d41c8055a 100644 --- a/tests/PreprocessorTest.cpp +++ b/tests/CppUTest/PreprocessorTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/tests/SetPluginTest.cpp b/tests/CppUTest/SetPluginTest.cpp similarity index 87% rename from tests/SetPluginTest.cpp rename to tests/CppUTest/SetPluginTest.cpp index c8042c23a..d55b91dfb 100644 --- a/tests/SetPluginTest.cpp +++ b/tests/CppUTest/SetPluginTest.cpp @@ -29,7 +29,7 @@ TEST_GROUP(SetPointerPluginTest) StringBufferTestOutput* output_; TestResult* result_; - void setup() + void setup() CPPUTEST_OVERRIDE { myRegistry_ = new TestRegistry(); plugin_ = new SetPointerPlugin("TestSetPlugin"); @@ -39,9 +39,9 @@ TEST_GROUP(SetPointerPluginTest) result_ = new TestResult(*output_); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { - myRegistry_->setCurrentRegistry(0); + myRegistry_->setCurrentRegistry(NULLPTR); delete myRegistry_; delete plugin_; delete output_; @@ -52,13 +52,13 @@ TEST_GROUP(SetPointerPluginTest) class FunctionPointerUtest : public Utest { public: - void setup() _override + void setup() CPPUTEST_OVERRIDE { UT_PTR_SET(fp1, stub_func1); UT_PTR_SET(fp2, stub_func2); UT_PTR_SET(fp2, stub_func2); } - void testBody() _override + void testBody() CPPUTEST_OVERRIDE { CHECK(fp1 == stub_func1); CHECK(fp2 == stub_func2); @@ -68,7 +68,7 @@ class FunctionPointerUtest : public Utest class FunctionPointerUtestShell: public UtestShell { public: - virtual Utest* createTest() + virtual Utest* createTest() CPPUTEST_OVERRIDE { return new FunctionPointerUtest(); } @@ -77,7 +77,6 @@ class FunctionPointerUtestShell: public UtestShell TEST(SetPointerPluginTest, installTwoFunctionPointer) { FunctionPointerUtestShell *tst = new FunctionPointerUtestShell(); - ; fp1 = orig_func1; fp2 = orig_func2; @@ -99,7 +98,7 @@ class MaxFunctionPointerUtest : public Utest { } - void setup() + void setup() CPPUTEST_OVERRIDE { for (int i = 0; i < numOfFpSets; ++i) { @@ -117,7 +116,7 @@ class MaxFunctionPointerUtestShell: public UtestShell { } - virtual Utest* createTest() + virtual Utest* createTest() CPPUTEST_OVERRIDE { return new MaxFunctionPointerUtest(numOfFpSets); } @@ -141,11 +140,11 @@ static double stub_double = 4.0; class SetDoublePointerUtest : public Utest { public: - void setup() + void setup() CPPUTEST_OVERRIDE { UT_PTR_SET(orig_double_ptr, &stub_double); } - void testBody() + void testBody() CPPUTEST_OVERRIDE { CHECK(orig_double_ptr == &stub_double); } @@ -154,7 +153,7 @@ class SetDoublePointerUtest : public Utest class SetDoublePointerUtestShell: public UtestShell { public: - Utest * createTest() + Utest * createTest() CPPUTEST_OVERRIDE { return new SetDoublePointerUtest(); } diff --git a/tests/SimpleMutexTest.cpp b/tests/CppUTest/SimpleMutexTest.cpp similarity index 95% rename from tests/SimpleMutexTest.cpp rename to tests/CppUTest/SimpleMutexTest.cpp index 9788ebe0b..19eeae935 100644 --- a/tests/SimpleMutexTest.cpp +++ b/tests/CppUTest/SimpleMutexTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -37,7 +37,7 @@ static int mutexDestroyCount = 0; static PlatformSpecificMutex StubMutexCreate(void) { mutexCreateCount++; - return 0; + return NULLPTR; } static void StubMutexLock(PlatformSpecificMutex) @@ -59,7 +59,7 @@ static void StubMutexDestroy(PlatformSpecificMutex) TEST_GROUP(SimpleMutexTest) { - void setup() + void setup() CPPUTEST_OVERRIDE { UT_PTR_SET(PlatformSpecificMutexCreate, StubMutexCreate); UT_PTR_SET(PlatformSpecificMutexLock, StubMutexLock); @@ -72,7 +72,7 @@ TEST_GROUP(SimpleMutexTest) mutexUnlockCount = 0; } - void teardown() + void teardown() CPPUTEST_OVERRIDE { } }; diff --git a/tests/CppUTest/SimpleStringCacheTest.cpp b/tests/CppUTest/SimpleStringCacheTest.cpp new file mode 100644 index 000000000..3fd98ab4f --- /dev/null +++ b/tests/CppUTest/SimpleStringCacheTest.cpp @@ -0,0 +1,389 @@ +/* + * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "CppUTest/TestHarness.h" +#include "CppUTest/SimpleStringInternalCache.h" +#include "CppUTest/TestTestingFixture.h" + +class TestFunctionWithCache : public ExecFunction +{ +public: + void (*testFunction)(SimpleStringInternalCache*, size_t); + SimpleStringInternalCache* parameter; + size_t allocationSize; + + void exec() CPPUTEST_OVERRIDE + { + testFunction(parameter, allocationSize); + } +}; + +TEST_GROUP(SimpleStringInternalCache) +{ + SimpleStringInternalCache cache; + MemoryAccountant accountant; + MemoryLeakAllocator* defaultAllocator; + AccountingTestMemoryAllocator* allocator; + + TestFunctionWithCache testFunction; + TestTestingFixture fixture; + + void setup() CPPUTEST_OVERRIDE + { + fixture.setTestFunction(&testFunction); + testFunction.parameter = &cache; + + defaultAllocator = new MemoryLeakAllocator(defaultMallocAllocator()); + allocator = new AccountingTestMemoryAllocator(accountant, defaultAllocator); + cache.setAllocator(defaultAllocator); + } + + void teardown() CPPUTEST_OVERRIDE + { + cache.clearAllIncludingCurrentlyUsedMemory(); + accountant.clear(); + delete allocator; + delete defaultAllocator; + } + + void createCacheForSize(size_t size, size_t amount) + { + for (size_t i = 0; i < amount; i++) { + char* memory = cache.alloc(size); + cache.dealloc(memory, size); + } + } +}; + +TEST(SimpleStringInternalCache, cacheHitWithOneEntry) +{ + createCacheForSize(10, 1); + cache.setAllocator(allocator); + + char* mem = cache.alloc(10); + mem[0] = 'B'; + mem[3] = 'A'; + mem[9] = 'S'; + + cache.setAllocator(allocator->originalAllocator()); + + LONGS_EQUAL(0, accountant.totalAllocationsOfSize(10)); + CHECK(!cache.hasFreeBlocksOfSize(10)); + + cache.setAllocator(allocator); +} + +TEST(SimpleStringInternalCache, cacheHitWithTwoEntries) +{ + createCacheForSize(10, 2); + cache.setAllocator(allocator); + + cache.alloc(10); + cache.alloc(10); + + cache.setAllocator(allocator->originalAllocator()); + + LONGS_EQUAL(0, accountant.totalAllocationsOfSize(10)); + CHECK(!cache.hasFreeBlocksOfSize(10)); + + cache.setAllocator(allocator); +} + +TEST(SimpleStringInternalCache, allocatingMoreThanCacheAvailable) +{ + createCacheForSize(10, 1); + cache.setAllocator(allocator); + + cache.alloc(10); + cache.alloc(10); + + cache.setAllocator(allocator->originalAllocator()); + + LONGS_EQUAL(1, accountant.totalAllocationsOfSize(32)); + CHECK(!cache.hasFreeBlocksOfSize(10)); + + cache.setAllocator(allocator); +} + + +TEST(SimpleStringInternalCache, allocationWillReuseTheAllocatedBlocks) +{ + cache.setAllocator(allocator); + + char* mem = cache.alloc(10); + cache.dealloc(mem, 10); + mem = cache.alloc(10); + cache.dealloc(mem, 10); + + LONGS_EQUAL(1, accountant.totalAllocationsOfSize(32)); +} + + +TEST(SimpleStringInternalCache, multipleDifferentSizeAllocationsAndDeallocations) +{ + cache.setAllocator(allocator); + + char* mem10 = cache.alloc(10); + char* mem11 = cache.alloc(11); + + char* mem100 = cache.alloc(100); + cache.dealloc(mem100, 100); + + char* mem101 = cache.alloc(101); + char* mem102 = cache.alloc(102); + char* mem103 = cache.alloc(103); + cache.dealloc(mem101, 102); + cache.dealloc(mem102, 103); + cache.dealloc(mem103, 104); + + cache.alloc(105); + cache.alloc(106); + cache.alloc(107); + + cache.dealloc(mem10, 10); + cache.dealloc(mem11, 11); + + LONGS_EQUAL(2, accountant.totalAllocationsOfSize(32)); + LONGS_EQUAL(3, accountant.totalAllocationsOfSize(128)); +} + +TEST(SimpleStringInternalCache, deallocOfCachedMemoryWillNotDealloc) +{ + cache.setAllocator(allocator); + + char* mem = cache.alloc(10); + cache.dealloc(mem, 10); + + LONGS_EQUAL(0, accountant.totalDeallocationsOfSize(32)); +} + +TEST(SimpleStringInternalCache, clearCacheWillRemoveAllCachedMemoryButNotAllUsedMemory) +{ + cache.setAllocator(allocator); + + char* mem = cache.alloc(10); + cache.dealloc(mem, 10); + + cache.alloc(60); + + cache.clearCache(); + + LONGS_EQUAL(1, accountant.totalDeallocationsOfSize(32)); + LONGS_EQUAL(0, accountant.totalDeallocationsOfSize(64)); +} + +TEST(SimpleStringInternalCache, clearAllIncludingCurrentlyUsedMemory) +{ + cache.setAllocator(allocator); + + cache.alloc(60); + + cache.clearAllIncludingCurrentlyUsedMemory(); + + LONGS_EQUAL(1, accountant.totalDeallocationsOfSize(64)); +} + + + +TEST(SimpleStringInternalCache, allocatingLargerStringThanCached) +{ + cache.setAllocator(allocator); + + char* mem = cache.alloc(1234); + cache.dealloc(mem, 1234); + + LONGS_EQUAL(1, accountant.totalAllocationsOfSize(1234)); + LONGS_EQUAL(1, accountant.totalDeallocationsOfSize(1234)); +} + +TEST(SimpleStringInternalCache, allocatingMultipleLargerStringThanCached) +{ + cache.setAllocator(allocator); + + char* mem = cache.alloc(1234); + char* mem2 = cache.alloc(1234); + char* mem3 = cache.alloc(1234); + + cache.dealloc(mem2, 1234); + cache.dealloc(mem, 1234); + cache.dealloc(mem3, 1234); + + LONGS_EQUAL(3, accountant.totalAllocationsOfSize(1234)); + LONGS_EQUAL(3, accountant.totalDeallocationsOfSize(1234)); +} + + +TEST(SimpleStringInternalCache, clearAllIncludingCurrentlyUsedMemoryAlsoReleasesLargeNonCachesMemory) +{ + cache.setAllocator(allocator); + + cache.alloc(1234); + cache.alloc(1234); + cache.alloc(1234); + + cache.clearAllIncludingCurrentlyUsedMemory(); + + LONGS_EQUAL(3, accountant.totalAllocationsOfSize(1234)); + LONGS_EQUAL(3, accountant.totalDeallocationsOfSize(1234)); +} + +static void deallocatingStringMemoryThatWasntAllocatedWithCache_(SimpleStringInternalCache* cache, size_t allocationSize) +{ + char* mem = defaultMallocAllocator()->alloc_memory(allocationSize, __FILE__, __LINE__); + mem[0] = 'B'; + mem[1] = 'a'; + mem[2] = 's'; + mem[3] = '\0'; + cache->dealloc(mem, allocationSize); + defaultMallocAllocator()->free_memory(mem, allocationSize, __FILE__, __LINE__); +} + +TEST(SimpleStringInternalCache, deallocatingMemoryThatWasntAllocatedWhileCacheWasInPlaceProducesWarning) +{ + testFunction.testFunction = deallocatingStringMemoryThatWasntAllocatedWithCache_; + testFunction.allocationSize = 123; + + cache.setAllocator(allocator); + fixture.runAllTests(); + + fixture.assertPrintContains("\nWARNING: Attempting to deallocate a String buffer that was allocated while not caching. Ignoring it!\n" + "This is likely due statics and will cause problems.\n" + "Only warning once to avoid recursive warnings.\n" + "String we are deallocating: \"Bas\"\n"); + +} + +static void deallocatingStringMemoryTwiceThatWasntAllocatedWithCache_(SimpleStringInternalCache* cache, size_t allocationSize) +{ + char* mem = defaultMallocAllocator()->alloc_memory(allocationSize, __FILE__, __LINE__); + mem[0] = '\0'; + cache->dealloc(mem, allocationSize); + cache->dealloc(mem, allocationSize); + defaultMallocAllocator()->free_memory(mem, allocationSize, __FILE__, __LINE__); +} + +TEST(SimpleStringInternalCache, deallocatingMemoryThatWasntAllocatedWhileCacheWasInPlaceProducesWarningButOnlyOnce) +{ + testFunction.testFunction = deallocatingStringMemoryTwiceThatWasntAllocatedWithCache_; + testFunction.allocationSize = 123; + + cache.setAllocator(allocator); + fixture.runAllTests(); + + LONGS_EQUAL(1, fixture.getOutput().count("WARNING")); +} + +TEST(SimpleStringInternalCache, deallocatingLargeMemoryThatWasntAllocatedWhileCacheWasInPlaceProducesWarning) +{ + testFunction.testFunction = deallocatingStringMemoryThatWasntAllocatedWithCache_; + testFunction.allocationSize = 12345; + + cache.setAllocator(allocator); + fixture.runAllTests(); + + fixture.assertPrintContains("\nWARNING: Attempting to deallocate a String buffer that was allocated while not caching. Ignoring it!\n" + "This is likely due statics and will cause problems.\n" + "Only warning once to avoid recursive warnings.\n" + "String we are deallocating: \"Bas\"\n"); + +} + +TEST(SimpleStringInternalCache, deallocatingLargeMemoryThatWasntAllocatedWhileCacheWasInPlaceProducesWarningButOnlyOnce) +{ + testFunction.testFunction = deallocatingStringMemoryTwiceThatWasntAllocatedWithCache_; + testFunction.allocationSize = 12345; + + cache.setAllocator(allocator); + fixture.runAllTests(); + + LONGS_EQUAL(1, fixture.getOutput().count("WARNING")); +} + +TEST_GROUP(SimpleStringCacheAllocator) +{ + SimpleStringCacheAllocator* allocator; + SimpleStringInternalCache cache; + MemoryAccountant accountant; + AccountingTestMemoryAllocator* accountingAllocator; + + void setup() CPPUTEST_OVERRIDE + { + accountingAllocator = new AccountingTestMemoryAllocator(accountant, defaultMallocAllocator()); + allocator = new SimpleStringCacheAllocator(cache, accountingAllocator); + } + + void teardown() CPPUTEST_OVERRIDE + { + cache.clearCache(); + delete allocator; + delete accountingAllocator; + } +}; + +TEST(SimpleStringCacheAllocator, allocationIsCached) +{ + char* mem = allocator->alloc_memory(10, __FILE__, __LINE__); + allocator->free_memory(mem, 10, __FILE__, __LINE__); + + size_t totalAllocations = accountant.totalAllocations(); + size_t totalDeallocations = accountant.totalDeallocations(); + + mem = allocator->alloc_memory(10, __FILE__, __LINE__); + allocator->free_memory(mem, 10, __FILE__, __LINE__); + + LONGS_EQUAL(totalAllocations, accountant.totalAllocations()); + LONGS_EQUAL(totalDeallocations, accountant.totalDeallocations()); +} + +TEST(SimpleStringCacheAllocator, originalAllocator) +{ + POINTERS_EQUAL(defaultMallocAllocator(), allocator->actualAllocator()); + STRCMP_EQUAL(defaultMallocAllocator()->alloc_name(), allocator->alloc_name()); + STRCMP_EQUAL(defaultMallocAllocator()->free_name(), allocator->free_name()); +} + +TEST(SimpleStringCacheAllocator, name) +{ + STRCMP_EQUAL("SimpleStringCacheAllocator", allocator->name()); +} + + + +TEST_GROUP(GlobalSimpleStringCache) +{ +}; + +TEST(GlobalSimpleStringCache, installsAndRemovedCache) +{ + TestMemoryAllocator* originalStringAllocator = SimpleString::getStringAllocator(); + { + GlobalSimpleStringCache cache; + STRCMP_EQUAL("SimpleStringCacheAllocator", SimpleString::getStringAllocator()->name()); + POINTERS_EQUAL(cache.getAllocator(), SimpleString::getStringAllocator()); + } + POINTERS_EQUAL(originalStringAllocator, SimpleString::getStringAllocator()); +} diff --git a/tests/SimpleStringTest.cpp b/tests/CppUTest/SimpleStringTest.cpp similarity index 73% rename from tests/SimpleStringTest.cpp rename to tests/CppUTest/SimpleStringTest.cpp index bd4997a38..7a4e7629e 100644 --- a/tests/SimpleStringTest.cpp +++ b/tests/CppUTest/SimpleStringTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,50 +30,158 @@ #include "CppUTest/PlatformSpecificFunctions.h" #include "CppUTest/TestMemoryAllocator.h" #include "CppUTest/MemoryLeakDetector.h" +#include "CppUTest/TestTestingFixture.h" class JustUseNewStringAllocator : public TestMemoryAllocator { public: - virtual ~JustUseNewStringAllocator() {} + virtual ~JustUseNewStringAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE {} - char* alloc_memory(size_t size, const char* file, int line) + char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE { - return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, (char*) file, line); + return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, file, line); } - void free_memory(char* str, const char* file, int line) + void free_memory(char* str, size_t, const char* file, size_t line) CPPUTEST_OVERRIDE { - MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewArrayAllocator(), str, (char*) file, line); + MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewArrayAllocator(), str, file, line); } }; +class GlobalSimpleStringMemoryAccountantExecFunction + : public ExecFunction +{ +public: + void (*testFunction_)(GlobalSimpleStringMemoryAccountant*); + GlobalSimpleStringMemoryAccountant* parameter_; + + virtual void exec() CPPUTEST_OVERRIDE + { + testFunction_(parameter_); + } +}; + +TEST_GROUP(GlobalSimpleStringMemoryAccountant) +{ + GlobalSimpleStringAllocatorStash stash; + GlobalSimpleStringMemoryAccountantExecFunction testFunction; + TestTestingFixture fixture; + GlobalSimpleStringMemoryAccountant accountant; + + void setup() CPPUTEST_OVERRIDE + { + stash.save(); + testFunction.parameter_ = &accountant; + fixture.setTestFunction(&testFunction); + } + + void teardown() CPPUTEST_OVERRIDE + { + stash.restore(); + } +}; + +TEST(GlobalSimpleStringMemoryAccountant, start) +{ + accountant.start(); + POINTERS_EQUAL(accountant.getAllocator(), SimpleString::getStringAllocator()); +} + +TEST(GlobalSimpleStringMemoryAccountant, startTwiceDoesNothing) +{ + accountant.start(); + TestMemoryAllocator* memoryAccountantAllocator = SimpleString::getStringAllocator(); + accountant.start(); + + POINTERS_EQUAL(memoryAccountantAllocator, SimpleString::getStringAllocator()); + + accountant.stop(); +} + +TEST(GlobalSimpleStringMemoryAccountant, stop) +{ + TestMemoryAllocator* originalAllocator = SimpleString::getStringAllocator(); + accountant.start(); + accountant.stop(); + POINTERS_EQUAL(originalAllocator, SimpleString::getStringAllocator()); +} + +static void stopAccountant_(GlobalSimpleStringMemoryAccountant* accountant) +{ + accountant->stop(); +} + +TEST(GlobalSimpleStringMemoryAccountant, stopWithoutStartWillFail) +{ + testFunction.testFunction_ = stopAccountant_; + fixture.runAllTests(); + fixture.assertPrintContains("Global SimpleString allocator stopped without starting"); +} + +static void changeAllocatorBetweenStartAndStop_(GlobalSimpleStringMemoryAccountant* accountant) +{ + TestMemoryAllocator* originalAllocator = SimpleString::getStringAllocator(); + accountant->start(); + SimpleString::setStringAllocator(originalAllocator); + accountant->stop(); +} + +TEST(GlobalSimpleStringMemoryAccountant, stopFailsWhenAllocatorWasChangedInBetween) +{ + testFunction.testFunction_ = changeAllocatorBetweenStartAndStop_; + fixture.runAllTests(); + fixture.assertPrintContains("GlobalStrimpleStringMemoryAccountant: allocator has changed between start and stop!"); +} + +TEST(GlobalSimpleStringMemoryAccountant, report) +{ + SimpleString str; + accountant.start(); + str += "More"; + accountant.stop(); + STRCMP_CONTAINS(" 1 0 1", accountant.report().asCharString()); +} + +TEST(GlobalSimpleStringMemoryAccountant, reportUseCaches) +{ + size_t caches[] = {32}; + accountant.useCacheSizes(caches, 1); + SimpleString str; + accountant.start(); + str += "More"; + accountant.stop(); + STRCMP_CONTAINS("32 1 1 1", accountant.report().asCharString()); +} + TEST_GROUP(SimpleString) { JustUseNewStringAllocator justNewForSimpleStringTestAllocator; - void setup() + GlobalSimpleStringAllocatorStash stash; + void setup() CPPUTEST_OVERRIDE { - SimpleString::setStringAllocator(&justNewForSimpleStringTestAllocator); + stash.save(); + SimpleString::setStringAllocator(&justNewForSimpleStringTestAllocator); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { - SimpleString::setStringAllocator(NULL); + stash.restore(); } }; TEST(SimpleString, defaultAllocatorIsNewArrayAllocator) { - SimpleString::setStringAllocator(NULL); - POINTERS_EQUAL(getCurrentNewArrayAllocator(), SimpleString::getStringAllocator()); + SimpleString::setStringAllocator(NULLPTR); + POINTERS_EQUAL(defaultNewArrayAllocator(), SimpleString::getStringAllocator()); } class MyOwnStringAllocator : public TestMemoryAllocator { public: MyOwnStringAllocator() : memoryWasAllocated(false) {} - virtual ~MyOwnStringAllocator() {} + virtual ~MyOwnStringAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE {} bool memoryWasAllocated; - char* alloc_memory(size_t size, const char* file, int line) + char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE { memoryWasAllocated = true; return TestMemoryAllocator::alloc_memory(size, file, line); @@ -86,7 +194,7 @@ TEST(SimpleString, allocatorForSimpleStringCanBeReplaced) SimpleString::setStringAllocator(&myOwnAllocator); SimpleString simpleString; CHECK(myOwnAllocator.memoryWasAllocated); - SimpleString::setStringAllocator(NULL); + SimpleString::setStringAllocator(NULLPTR); } TEST(SimpleString, CreateSequence) @@ -186,6 +294,14 @@ TEST(SimpleString, lowerCase) STRCMP_EQUAL("AbCdEfG1234", s1.asCharString()); } +TEST(SimpleString, printable) +{ + SimpleString s1("ABC\01\06\a\n\r\b\t\v\f\x0E\x1F\x7F""abc"); + SimpleString s2(s1.printable()); + STRCMP_EQUAL("ABC\\x01\\x06\\a\\n\\r\\b\\t\\v\\f\\x0E\\x1F\\x7Fabc", s2.asCharString()); + STRCMP_EQUAL("ABC\01\06\a\n\r\b\t\v\f\x0E\x1F\x7F""abc", s1.asCharString()); +} + TEST(SimpleString, Addition) { SimpleString s1("hello!"); @@ -424,39 +540,55 @@ TEST(SimpleString, copyInBufferNormal) { SimpleString str("Hello World"); size_t bufferSize = str.size()+1; - char* buffer = (char*) malloc(bufferSize); + char* buffer = (char*) PlatformSpecificMalloc(bufferSize); str.copyToBuffer(buffer, bufferSize); STRCMP_EQUAL(str.asCharString(), buffer); - free(buffer); + PlatformSpecificFree(buffer); } TEST(SimpleString, copyInBufferWithEmptyBuffer) { SimpleString str("Hello World"); - char* buffer= NULL; + char* buffer= NULLPTR; str.copyToBuffer(buffer, 0); - POINTERS_EQUAL(NULL, buffer); + POINTERS_EQUAL(NULLPTR, buffer); } TEST(SimpleString, copyInBufferWithBiggerBufferThanNeeded) { SimpleString str("Hello"); size_t bufferSize = 20; - char* buffer= (char*) malloc(bufferSize); + char* buffer= (char*) PlatformSpecificMalloc(bufferSize); str.copyToBuffer(buffer, bufferSize); STRCMP_EQUAL(str.asCharString(), buffer); - free(buffer); + PlatformSpecificFree(buffer); +} + +TEST(SimpleString, copyInBufferWithSmallerBufferThanNeeded) +{ + SimpleString str("Hello"); + size_t bufferSize = str.size(); + char* buffer= (char*) PlatformSpecificMalloc(bufferSize); + str.copyToBuffer(buffer, bufferSize); + STRNCMP_EQUAL(str.asCharString(), buffer, (bufferSize-1)); + LONGS_EQUAL(0, buffer[bufferSize-1]); + PlatformSpecificFree(buffer); } TEST(SimpleString, ContainsNull) { - SimpleString s(0); + SimpleString s(NULLPTR); STRCMP_EQUAL("", s.asCharString()); } TEST(SimpleString, NULLReportsNullString) { - STRCMP_EQUAL("(null)", StringFromOrNull((char*) NULL).asCharString()); + STRCMP_EQUAL("(null)", StringFromOrNull((char*) NULLPTR).asCharString()); +} + +TEST(SimpleString, NULLReportsNullStringPrintable) +{ + STRCMP_EQUAL("(null)", PrintableStringFromOrNull((char*) NULLPTR).asCharString()); } TEST(SimpleString, Booleans) @@ -508,7 +640,7 @@ TEST(SimpleString, UnsignedLongInts) CHECK(s == s2); } -#ifdef CPPUTEST_USE_LONG_LONG +#if CPPUTEST_USE_LONG_LONG TEST(SimpleString, LongLongInts) { @@ -561,6 +693,16 @@ TEST(SimpleString, Sizes) STRCMP_EQUAL("10", StringFrom((int) size).asCharString()); } +#if __cplusplus > 199711L && !defined __arm__ && CPPUTEST_USE_STD_CPP_LIB + +TEST(SimpleString, nullptr_type) +{ + SimpleString s(StringFrom(NULLPTR)); + STRCMP_EQUAL("(null)", s.asCharString()); +} + +#endif + TEST(SimpleString, HexStrings) { STRCMP_EQUAL("f3", HexStringFrom((signed char)-13).asCharString()); @@ -568,7 +710,7 @@ TEST(SimpleString, HexStrings) SimpleString h1 = HexStringFrom(0xffffL); STRCMP_EQUAL("ffff", h1.asCharString()); -#ifdef CPPUTEST_USE_LONG_LONG +#if CPPUTEST_USE_LONG_LONG SimpleString h15 = HexStringFrom(0xffffLL); STRCMP_EQUAL("ffff", h15.asCharString()); #endif @@ -591,17 +733,17 @@ TEST(SimpleString, StringFromFormatpointer) //this is not a great test. but %p is odd on mingw and even more odd on Solaris. SimpleString h1 = StringFromFormat("%p", (void*) 1); if (h1.size() == 3) - STRCMP_EQUAL("0x1", h1.asCharString()) + STRCMP_EQUAL("0x1", h1.asCharString()); else if (h1.size() == 8) - STRCMP_EQUAL("00000001", h1.asCharString()) + STRCMP_EQUAL("00000001", h1.asCharString()); else if (h1.size() == 9) - STRCMP_EQUAL("0000:0001", h1.asCharString()) + STRCMP_EQUAL("0000:0001", h1.asCharString()); else if (h1.size() == 16) - STRCMP_EQUAL("0000000000000001", h1.asCharString()) + STRCMP_EQUAL("0000000000000001", h1.asCharString()); else if (h1.size() == 1) - STRCMP_EQUAL("1", h1.asCharString()) + STRCMP_EQUAL("1", h1.asCharString()); else - FAIL("Off %p behavior") + FAIL("Off %p behavior"); } TEST(SimpleString, StringFromFormatLarge) @@ -704,9 +846,8 @@ TEST(SimpleString, CollectionWritingToEmptyString) } #ifdef CPPUTEST_64BIT -#ifndef CPPUTEST_64BIT_32BIT_LONGS -TEST(SimpleString, _64BitAddressPrintsCorrectly) +TEST(SimpleString, 64BitAddressPrintsCorrectly) { char* p = (char*) 0x0012345678901234; SimpleString expected("0x12345678901234"); @@ -714,21 +855,22 @@ TEST(SimpleString, _64BitAddressPrintsCorrectly) STRCMP_EQUAL(expected.asCharString(), actual.asCharString()); } +#ifndef CPPUTEST_64BIT_32BIT_LONGS + +TEST(SimpleString, BracketsFormattedHexStringFromForLongOnDifferentPlatform) +{ + long value = -1; + + STRCMP_EQUAL("(0xffffffffffffffff)", BracketsFormattedHexStringFrom(value).asCharString()); +} + #else -/* - * This test case should pass on 64 bit systems with 32 bit longs, - * but actually fails due to an implementation problem: Right now, - * the 64 bit pointers are casted to 32bit as the %p is causing - * different formats on different platforms. However, this will - * need to be fixed in the future. - */ -IGNORE_TEST(SimpleString, _64BitAddressPrintsCorrectly) +TEST(SimpleString, BracketsFormattedHexStringFromForLongOnDifferentPlatform) { - char* p = (char*) 0xffffffff; - SimpleString expected("0x123456789"); - SimpleString actual = StringFrom((void*)&p[0x2345678A]); - STRCMP_EQUAL(expected.asCharString(), actual.asCharString()); + long value = -1; + + STRCMP_EQUAL("(0xffffffff)", BracketsFormattedHexStringFrom(value).asCharString()); } #endif @@ -736,18 +878,33 @@ IGNORE_TEST(SimpleString, _64BitAddressPrintsCorrectly) /* * This test case cannot pass on 32 bit systems. */ -IGNORE_TEST(SimpleString, _64BitAddressPrintsCorrectly) +IGNORE_TEST(SimpleString, 64BitAddressPrintsCorrectly) { } +TEST(SimpleString, BracketsFormattedHexStringFromForLongOnDifferentPlatform) +{ + long value = -1; + + STRCMP_EQUAL("(0xffffffff)", BracketsFormattedHexStringFrom(value).asCharString()); +} #endif -TEST(SimpleString, BuildStringFromUnsignedInteger) +TEST(SimpleString, BuildStringFromUnsignedLongInteger) { unsigned long int i = 0xffffffff; SimpleString result = StringFrom(i); - const char* expected_string = "4294967295 (0xffffffff)"; + const char* expected_string = "4294967295"; + CHECK_EQUAL(expected_string, result); +} + +TEST(SimpleString, BuildStringFromUnsignedInteger) +{ + unsigned int i = 0xff; + + SimpleString result = StringFrom(i); + const char* expected_string = "255"; CHECK_EQUAL(expected_string, result); } @@ -772,7 +929,7 @@ TEST(SimpleString, unsigned_long) unsigned long i = 0xffffffffUL; SimpleString result = StringFrom(i); - const char* expected_string = "4294967295 (0xffffffff)"; + const char* expected_string = "4294967295"; CHECK_EQUAL(expected_string, result); } @@ -805,7 +962,7 @@ TEST(SimpleString, StrNCpy_zero_termination) TEST(SimpleString, StrNCpy_null_proof) { - POINTERS_EQUAL(NULL, SimpleString::StrNCpy(NULL, "woman", 6)); + POINTERS_EQUAL(NULLPTR, SimpleString::StrNCpy(NULLPTR, "woman", 6)); } TEST(SimpleString, StrNCpy_stops_at_end_of_string) @@ -882,9 +1039,9 @@ TEST(SimpleString, StrStr) char foobarfoo[] = "foobarfoo"; char barf[] = "barf"; CHECK(SimpleString::StrStr(foo, empty) == foo); - CHECK(SimpleString::StrStr(empty, foo) == 0); + CHECK(SimpleString::StrStr(empty, foo) == NULLPTR); CHECK(SimpleString::StrStr(foobarfoo, barf) == foobarfoo+3); - CHECK(SimpleString::StrStr(barf, foobarfoo) == 0); + CHECK(SimpleString::StrStr(barf, foobarfoo) == NULLPTR); CHECK(SimpleString::StrStr(foo, foo) == foo); } @@ -905,6 +1062,23 @@ TEST(SimpleString, AtoI) CHECK(32767 == SimpleString::AtoI(max_short_str)); } +TEST(SimpleString, AtoU) +{ + char max_short_str[] = "65535"; + CHECK(12345 == SimpleString::AtoU("012345")); + CHECK(6789 == SimpleString::AtoU("6789")); + CHECK(12345 == SimpleString::AtoU("12345/")); + CHECK(12345 == SimpleString::AtoU("12345:")); + CHECK(123 == SimpleString::AtoU("\t \r\n123")); + CHECK(123 == SimpleString::AtoU("123-foo")); + CHECK(65535 == SimpleString::AtoU(max_short_str)); + CHECK(0 == SimpleString::AtoU("foo")); + CHECK(0 == SimpleString::AtoU("-foo")); + CHECK(0 == SimpleString::AtoU("+1")); + CHECK(0 == SimpleString::AtoU("-1")); + CHECK(0 == SimpleString::AtoU("0")); +} + TEST(SimpleString, Binary) { const unsigned char value[] = { 0x00, 0x01, 0x2A, 0xFF }; @@ -913,7 +1087,7 @@ TEST(SimpleString, Binary) STRCMP_EQUAL(expectedString, StringFromBinary(value, sizeof(value)).asCharString()); STRCMP_EQUAL(expectedString, StringFromBinaryOrNull(value, sizeof(value)).asCharString()); STRCMP_EQUAL("", StringFromBinary(value, 0).asCharString()); - STRCMP_EQUAL("(null)", StringFromBinaryOrNull(NULL, 0).asCharString()); + STRCMP_EQUAL("(null)", StringFromBinaryOrNull(NULLPTR, 0).asCharString()); } TEST(SimpleString, BinaryWithSize) @@ -924,7 +1098,7 @@ TEST(SimpleString, BinaryWithSize) STRCMP_EQUAL(expectedString, StringFromBinaryWithSize(value, sizeof(value)).asCharString()); STRCMP_EQUAL(expectedString, StringFromBinaryWithSizeOrNull(value, sizeof(value)).asCharString()); STRCMP_EQUAL("Size = 0 | HexContents = ", StringFromBinaryWithSize(value, 0).asCharString()); - STRCMP_EQUAL("(null)", StringFromBinaryWithSizeOrNull(NULL, 0).asCharString()); + STRCMP_EQUAL("(null)", StringFromBinaryWithSizeOrNull(NULLPTR, 0).asCharString()); } TEST(SimpleString, BinaryWithSizeLargerThan128) @@ -944,7 +1118,7 @@ TEST(SimpleString, MemCmp) LONGS_EQUAL(0, SimpleString::MemCmp(smaller, smaller, sizeof(smaller))); CHECK(SimpleString::MemCmp(smaller, greater, sizeof(smaller)) < 0); CHECK(SimpleString::MemCmp(greater, smaller, sizeof(smaller)) > 0); - LONGS_EQUAL(0, SimpleString::MemCmp(NULL, NULL, 0)); + LONGS_EQUAL(0, SimpleString::MemCmp(NULLPTR, NULLPTR, 0)); } TEST(SimpleString, MemCmpFirstLastNotMatching) @@ -966,7 +1140,7 @@ TEST(SimpleString, MaskedBitsChar) STRCMP_EQUAL("xxxxxxxx xxxxxxx1", StringFromMaskedBits(0x01, 0x01, 1).asCharString()); STRCMP_EQUAL("xxxxxxxx 11xx11xx", StringFromMaskedBits(0xFF, 0xCC, 1).asCharString()); } -#else +#elif (CPPUTEST_CHAR_BIT == 8) TEST(SimpleString, MaskedBitsChar) { STRCMP_EQUAL("xxxxxxxx", StringFromMaskedBits(0x00, 0x00, 1).asCharString()); @@ -1028,3 +1202,76 @@ TEST(SimpleString, StringFromOrdinalNumberOthers) STRCMP_EQUAL("100th", StringFromOrdinalNumber(100).asCharString()); STRCMP_EQUAL("101st", StringFromOrdinalNumber(101).asCharString()); } + +TEST(SimpleString, BracketsFormattedHexStringFromForSignedChar) +{ + signed char value = 'c'; + + STRCMP_EQUAL("(0x63)", BracketsFormattedHexStringFrom(value).asCharString()); +} + + +TEST(SimpleString, BracketsFormattedHexStringFromForUnsignedInt) +{ + unsigned int value = 1; + + STRCMP_EQUAL("(0x1)", BracketsFormattedHexStringFrom(value).asCharString()); +} + +TEST(SimpleString, BracketsFormattedHexStringFromForUnsignedLong) +{ + unsigned long value = 1; + + STRCMP_EQUAL("(0x1)", BracketsFormattedHexStringFrom(value).asCharString()); +} + +#ifdef CPPUTEST_16BIT_INTS +TEST(SimpleString, BracketsFormattedHexStringFromForInt) +{ + int value = -1; + + STRCMP_EQUAL("(0xffff)", BracketsFormattedHexStringFrom(value).asCharString()); +} +#else +TEST(SimpleString, BracketsFormattedHexStringFromForInt) +{ + int value = -1; + STRCMP_EQUAL("(0xffffffff)", BracketsFormattedHexStringFrom(value).asCharString()); +} +#endif + +TEST(SimpleString, BracketsFormattedHexStringFromForLong) +{ + long value = 1; + + STRCMP_EQUAL("(0x1)", BracketsFormattedHexStringFrom(value).asCharString()); +} +#if CPPUTEST_USE_LONG_LONG + +TEST(SimpleString, BracketsFormattedHexStringFromForLongLong) +{ + cpputest_longlong value = 1; + + STRCMP_EQUAL("(0x1)", BracketsFormattedHexStringFrom(value).asCharString()); +} +TEST(SimpleString, BracketsFormattedHexStringFromForULongLong) +{ + cpputest_ulonglong value = 1; + + STRCMP_EQUAL("(0x1)", BracketsFormattedHexStringFrom(value).asCharString()); +} +#else +TEST(SimpleString, BracketsFormattedHexStringFromForLongLong) +{ + cpputest_longlong value; + + STRCMP_EQUAL("", BracketsFormattedHexStringFrom(value).asCharString()); +} +TEST(SimpleString, BracketsFormattedHexStringFromForULongLong) +{ + cpputest_ulonglong value; + + STRCMP_EQUAL("", BracketsFormattedHexStringFrom(value).asCharString()); +} + +#endif diff --git a/tests/TeamCityOutputTest.cpp b/tests/CppUTest/TeamCityOutputTest.cpp similarity index 65% rename from tests/TeamCityOutputTest.cpp rename to tests/CppUTest/TeamCityOutputTest.cpp index 140ff6519..36ee135f5 100644 --- a/tests/TeamCityOutputTest.cpp +++ b/tests/CppUTest/TeamCityOutputTest.cpp @@ -9,16 +9,16 @@ class TeamCityOutputToBuffer : public TeamCityTestOutput { } - virtual ~TeamCityOutputToBuffer() + virtual ~TeamCityOutputToBuffer() CPPUTEST_DESTRUCTOR_OVERRIDE { } - void printBuffer(const char* s) _override + void printBuffer(const char* s) CPPUTEST_OVERRIDE { output += s; } - void flush() _override + void flush() CPPUTEST_OVERRIDE { output = ""; } @@ -32,11 +32,11 @@ class TeamCityOutputToBuffer : public TeamCityTestOutput SimpleString output; }; -static long millisTime; +static unsigned long millisTime; extern "C" { - static long MockGetPlatformSpecificTimeInMillis() + static unsigned long MockGetPlatformSpecificTimeInMillis() { return millisTime; } @@ -51,7 +51,7 @@ TEST_GROUP(TeamCityOutputTest) TestFailure *f, *f2, *f3; TestResult* result; - void setup() + void setup() CPPUTEST_OVERRIDE { mock = new TeamCityOutputToBuffer(); tcout = mock; @@ -64,7 +64,7 @@ TEST_GROUP(TeamCityOutputTest) millisTime = 0; UT_PTR_SET(GetPlatformSpecificTimeInMillis, MockGetPlatformSpecificTimeInMillis); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete tcout; delete tst; @@ -160,6 +160,67 @@ TEST(TeamCityOutputTest, PrintFailureWithFailInDifferentFile) STRCMP_EQUAL(expected, mock->getOutput().asCharString()); } +TEST(TeamCityOutputTest, TestGroupEscaped_Start) +{ + tst->setGroupName("'[]\n\r"); + result->currentGroupStarted(tst); + const char* expected = + "##teamcity[testSuiteStarted name='|'|[|]|n|r']\n"; + STRCMP_EQUAL(expected, mock->getOutput().asCharString()); +} + +TEST(TeamCityOutputTest, TestGroupEscaped_End) +{ + tst->setGroupName("'[]\n\r"); + result->currentGroupStarted(tst); + result->currentGroupEnded(tst); + const char* expected = + "##teamcity[testSuiteStarted name='|'|[|]|n|r']\n" + "##teamcity[testSuiteFinished name='|'|[|]|n|r']\n"; + STRCMP_EQUAL(expected, mock->getOutput().asCharString()); +} + +TEST(TeamCityOutputTest, TestNameEscaped_Start) +{ + tst->setTestName("'[]\n\r"); + result->currentTestStarted(tst); + const char* expected = + "##teamcity[testStarted name='|'|[|]|n|r']\n"; + STRCMP_EQUAL(expected, mock->getOutput().asCharString()); +} + +TEST(TeamCityOutputTest, TestNameEscaped_End) +{ + tst->setTestName("'[]\n\r"); + result->currentTestStarted(tst); + result->currentTestEnded(tst); + const char* expected = + "##teamcity[testStarted name='|'|[|]|n|r']\n" + "##teamcity[testFinished name='|'|[|]|n|r' duration='0']\n"; + STRCMP_EQUAL(expected, mock->getOutput().asCharString()); +} + +TEST(TeamCityOutputTest, TestNameEscaped_Ignore) +{ + IgnoredUtestShell itst("group", "'[]\n\r", "file", 10); + result->currentTestStarted(&itst); + const char* expected = + "##teamcity[testStarted name='|'|[|]|n|r']\n" + "##teamcity[testIgnored name='|'|[|]|n|r']\n"; + STRCMP_EQUAL(expected, mock->getOutput().asCharString()); +} + +TEST(TeamCityOutputTest, TestNameEscaped_Fail) +{ + tst->setTestName("'[]\n\r"); + TestFailure fail(tst, "failfile", 20, "failure message"); + tcout->printFailure(fail); + const char* expected = + "##teamcity[testFailed name='|'|[|]|n|r' message='TEST failed (file:10): failfile:20' " + "details='failure message']\n"; + STRCMP_EQUAL(expected, mock->getOutput().asCharString()); +} + /* Todo: * -Detect when running in TeamCity and switch output to -o teamcity automatically */ diff --git a/tests/TestFailureNaNTest.cpp b/tests/CppUTest/TestFailureNaNTest.cpp similarity index 74% rename from tests/TestFailureNaNTest.cpp rename to tests/CppUTest/TestFailureNaNTest.cpp index e17e359a2..2f7e2a62f 100644 --- a/tests/TestFailureNaNTest.cpp +++ b/tests/CppUTest/TestFailureNaNTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -29,50 +29,36 @@ #include "CppUTest/TestOutput.h" #include "CppUTest/PlatformSpecificFunctions.h" +#if CPPUTEST_USE_STD_C_LIB +#include +#endif + +#if defined(NAN) && defined(INFINITY) + namespace { const int failLineNumber = 2; const char* failFileName = "fail.cpp"; } -static double zero = 0.0; -static double one = 1.0; -static double not_a_number = zero / zero; -static double infinity = one / zero; - -extern "C" { - static int IsNanForSystemsWithoutNan(double d) { return ((long)not_a_number == (long)d); } - static int IsInfForSystemsWithoutInf(double d) { return ((long)infinity == (long)d); } -} - TEST_GROUP(TestFailureNanAndInf) { UtestShell* test; - void setup() _override + void setup() CPPUTEST_OVERRIDE { test = new UtestShell("groupname", "testname", failFileName, failLineNumber-1); - if(PlatformSpecificIsNan(not_a_number) == false) - { - not_a_number = -1.0; - UT_PTR_SET(PlatformSpecificIsNan, IsNanForSystemsWithoutNan); - } - if(PlatformSpecificIsInf(infinity) == false) - { - infinity = -2.0; - UT_PTR_SET(PlatformSpecificIsInf, IsInfForSystemsWithoutInf); - } } - void teardown() _override + void teardown() CPPUTEST_OVERRIDE { delete test; } }; -#define FAILURE_EQUAL(a, b) STRCMP_EQUAL_LOCATION(a, b.getMessage().asCharString(), "", __FILE__, __LINE__) +#define FAILURE_EQUAL(a, b) STRCMP_EQUAL_LOCATION(a, (b).getMessage().asCharString(), "", __FILE__, __LINE__) TEST(TestFailureNanAndInf, DoublesEqualExpectedIsNaN) { - DoublesEqualFailure f(test, failFileName, failLineNumber, not_a_number, 2.0, 3.0, ""); + DoublesEqualFailure f(test, failFileName, failLineNumber, (double)NAN, 2.0, 3.0, ""); FAILURE_EQUAL("expected \n" "\tbut was <2> threshold used was <3>\n" "\tCannot make comparisons with Nan", f); @@ -80,7 +66,7 @@ TEST(TestFailureNanAndInf, DoublesEqualExpectedIsNaN) TEST(TestFailureNanAndInf, DoublesEqualActualIsNaN) { - DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, not_a_number, 3.0, ""); + DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, (double)NAN, 3.0, ""); FAILURE_EQUAL("expected <1>\n" "\tbut was threshold used was <3>\n" "\tCannot make comparisons with Nan", f); @@ -88,7 +74,7 @@ TEST(TestFailureNanAndInf, DoublesEqualActualIsNaN) TEST(TestFailureNanAndInf, DoublesEqualThresholdIsNaN) { - DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, 2.0, not_a_number, ""); + DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, 2.0, (double)NAN, ""); FAILURE_EQUAL("expected <1>\n" "\tbut was <2> threshold used was \n" "\tCannot make comparisons with Nan", f); @@ -96,22 +82,24 @@ TEST(TestFailureNanAndInf, DoublesEqualThresholdIsNaN) TEST(TestFailureNanAndInf, DoublesEqualExpectedIsInf) { - DoublesEqualFailure f(test, failFileName, failLineNumber, infinity, 2.0, 3.0, ""); + DoublesEqualFailure f(test, failFileName, failLineNumber, (double)INFINITY, 2.0, 3.0, ""); FAILURE_EQUAL("expected \n" "\tbut was <2> threshold used was <3>", f); } TEST(TestFailureNanAndInf, DoublesEqualActualIsInf) { - DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, infinity, 3.0, ""); + DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, (double)INFINITY, 3.0, ""); FAILURE_EQUAL("expected <1>\n" "\tbut was threshold used was <3>", f); } TEST(TestFailureNanAndInf, DoublesEqualThresholdIsInf) { - DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, not_a_number, infinity, ""); + DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, (double)NAN, (double)INFINITY, ""); FAILURE_EQUAL("expected <1>\n" "\tbut was threshold used was \n" "\tCannot make comparisons with Nan", f); } + +#endif diff --git a/tests/TestFailureTest.cpp b/tests/CppUTest/TestFailureTest.cpp similarity index 87% rename from tests/TestFailureTest.cpp rename to tests/CppUTest/TestFailureTest.cpp index 8635a2334..6a7cb1516 100644 --- a/tests/TestFailureTest.cpp +++ b/tests/CppUTest/TestFailureTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -38,16 +38,16 @@ TEST_GROUP(TestFailure) { UtestShell* test; - void setup() + void setup() CPPUTEST_OVERRIDE { test = new UtestShell("groupname", "testname", failFileName, failLineNumber-1); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete test; } }; -#define FAILURE_EQUAL(a, b) STRCMP_EQUAL_LOCATION(a, b.getMessage().asCharString(), "", __FILE__, __LINE__) +#define FAILURE_EQUAL(a, b) STRCMP_EQUAL_LOCATION(a, (b).getMessage().asCharString(), "", __FILE__, __LINE__) TEST(TestFailure, CreateFailure) { @@ -78,13 +78,13 @@ TEST(TestFailure, EqualsFailure) TEST(TestFailure, EqualsFailureWithNullAsActual) { - EqualsFailure f(test, failFileName, failLineNumber, "expected", NULL, ""); + EqualsFailure f(test, failFileName, failLineNumber, "expected", NULLPTR, ""); FAILURE_EQUAL("expected \n\tbut was <(null)>", f); } TEST(TestFailure, EqualsFailureWithNullAsExpected) { - EqualsFailure f(test, failFileName, failLineNumber, NULL, "actual", ""); + EqualsFailure f(test, failFileName, failLineNumber, NULLPTR, "actual", ""); FAILURE_EQUAL("expected <(null)>\n\tbut was ", f); } @@ -130,39 +130,45 @@ TEST(TestFailure, LongsEqualFailureWithText) { LongsEqualFailure f(test, failFileName, failLineNumber, 1, 2, "text"); FAILURE_EQUAL("Message: text\n" - "\texpected <1 0x1>\n\tbut was <2 0x2>", f); + "\texpected <1 (0x1)>\n\tbut was <2 (0x2)>", f); } TEST(TestFailure, LongsEqualFailure) { LongsEqualFailure f(test, failFileName, failLineNumber, 1, 2, ""); - FAILURE_EQUAL("expected <1 0x1>\n\tbut was <2 0x2>", f); + FAILURE_EQUAL("expected <1 (0x1)>\n\tbut was <2 (0x2)>", f); } TEST(TestFailure, LongLongsEqualFailure) { -#ifdef CPPUTEST_USE_LONG_LONG +#if CPPUTEST_USE_LONG_LONG LongLongsEqualFailure f(test, failFileName, failLineNumber, 1, 2, ""); - FAILURE_EQUAL("expected <1 0x1>\n\tbut was <2 0x2>", f); + FAILURE_EQUAL("expected <1 (0x1)>\n\tbut was <2 (0x2)>", f); #else cpputest_longlong dummy_longlong; LongLongsEqualFailure f(test, failFileName, failLineNumber, dummy_longlong, dummy_longlong, ""); - FAILURE_EQUAL("expected < 0x>\n\tbut was < 0x>", f); + FAILURE_EQUAL("expected < >\n\tbut was < >", f); #endif } TEST(TestFailure, UnsignedLongLongsEqualFailure) { -#ifdef CPPUTEST_USE_LONG_LONG +#if CPPUTEST_USE_LONG_LONG UnsignedLongLongsEqualFailure f(test, failFileName, failLineNumber, 1, 2, ""); - FAILURE_EQUAL("expected <1 (0x1) 0x1>\n\tbut was <2 (0x2) 0x2>", f); + FAILURE_EQUAL("expected <1 (0x1)>\n\tbut was <2 (0x2)>", f); #else cpputest_ulonglong dummy_ulonglong; UnsignedLongLongsEqualFailure f(test, failFileName, failLineNumber, dummy_ulonglong, dummy_ulonglong, ""); - FAILURE_EQUAL("expected < 0x>\n\tbut was < 0x>", f); + FAILURE_EQUAL("expected < >\n\tbut was < >", f); #endif } +TEST(TestFailure, SignedBytesEqualFailure) +{ + SignedBytesEqualFailure f(test, failFileName, failLineNumber, (signed char)-1, (signed char)2, ""); + FAILURE_EQUAL("expected <-1 (0xff)>\n\tbut was < 2 (0x2)>", f); +} + TEST(TestFailure, StringsEqualFailureWithText) { StringEqualFailure f(test, failFileName, failLineNumber, "abc", "abd", "text"); @@ -206,10 +212,10 @@ TEST(TestFailure, StringsEqualFailureWithNewLinesAndTabs) "StringWith\t\nDifferentString", "StringWith\t\ndifferentString", ""); - FAILURE_EQUAL("expected \n" - "\tbut was \n" - "\tdifference starts at position 12 at: \n" - "\t \t\n^", f); + FAILURE_EQUAL("expected \n" + "\tbut was \n" + "\tdifference starts at position 12 at: \n" + "\t ^", f); } TEST(TestFailure, StringsEqualFailureInTheMiddle) @@ -232,14 +238,14 @@ TEST(TestFailure, StringsEqualFailureAtTheBeginning) TEST(TestFailure, StringsEqualFailureWithNullAsActual) { - StringEqualFailure f(test, failFileName, failLineNumber, "abc", NULL, ""); + StringEqualFailure f(test, failFileName, failLineNumber, "abc", NULLPTR, ""); FAILURE_EQUAL("expected \n" "\tbut was <(null)>", f); } TEST(TestFailure, StringsEqualFailureWithNullAsExpected) { - StringEqualFailure f(test, failFileName, failLineNumber, NULL, "abd", ""); + StringEqualFailure f(test, failFileName, failLineNumber, NULLPTR, "abd", ""); FAILURE_EQUAL("expected <(null)>\n" "\tbut was ", f); } @@ -265,14 +271,14 @@ TEST(TestFailure, StringsEqualNoCaseFailure) TEST(TestFailure, StringsEqualNoCaseFailureWithActualAsNull) { - StringEqualNoCaseFailure f(test, failFileName, failLineNumber, "ABC", NULL, ""); + StringEqualNoCaseFailure f(test, failFileName, failLineNumber, "ABC", NULLPTR, ""); FAILURE_EQUAL("expected \n" "\tbut was <(null)>", f); } TEST(TestFailure, StringsEqualNoCaseFailureWithExpectedAsNull) { - StringEqualNoCaseFailure f(test, failFileName, failLineNumber, NULL, "abd", ""); + StringEqualNoCaseFailure f(test, failFileName, failLineNumber, NULLPTR, "abd", ""); FAILURE_EQUAL("expected <(null)>\n" "\tbut was ", f); } @@ -371,14 +377,14 @@ TEST(TestFailure, BinaryEqualLast) TEST(TestFailure, BinaryEqualActualNull) { const unsigned char expectedData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - BinaryEqualFailure f(test, failFileName, failLineNumber, expectedData, NULL, sizeof(expectedData), ""); + BinaryEqualFailure f(test, failFileName, failLineNumber, expectedData, NULLPTR, sizeof(expectedData), ""); FAILURE_EQUAL("expected <00 00 00 00 00 00 00>\n\tbut was <(null)>", f); } TEST(TestFailure, BinaryEqualExpectedNull) { const unsigned char actualData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; - BinaryEqualFailure f(test, failFileName, failLineNumber, NULL, actualData, sizeof(actualData), ""); + BinaryEqualFailure f(test, failFileName, failLineNumber, NULLPTR, actualData, sizeof(actualData), ""); FAILURE_EQUAL("expected <(null)>\n\tbut was <00 00 00 00 00 00 01>", f); } @@ -395,7 +401,7 @@ TEST(TestFailure, BitsEqualChar) BitsEqualFailure f(test, failFileName, failLineNumber, 0x01, 0x03, 0xFF, sizeof(char), ""); FAILURE_EQUAL("expected \n\tbut was ", f); } -#else +#elif (CPPUTEST_CHAR_BIT == 8) TEST(TestFailure, BitsEqualChar) { BitsEqualFailure f(test, failFileName, failLineNumber, 0x01, 0x03, 0xFF, sizeof(char), ""); @@ -420,3 +426,26 @@ TEST(TestFailure, FeatureUnsupported) FeatureUnsupportedFailure f(test, failFileName, failLineNumber, "SOME_FEATURE", ""); FAILURE_EQUAL("The feature \"SOME_FEATURE\" is not supported in this environment or with the feature set selected when building the library.", f); } + +#if CPPUTEST_HAVE_EXCEPTIONS +TEST(TestFailure, UnexpectedExceptionFailure_UnknownException) +{ + UnexpectedExceptionFailure f(test); + FAILURE_EQUAL("Unexpected exception of unknown type was thrown.", f); +} +#endif + +#if CPPUTEST_HAVE_EXCEPTIONS && CPPUTEST_USE_STD_CPP_LIB +TEST(TestFailure, UnexpectedExceptionFailure_StandardException) +{ + std::runtime_error e("Some error"); + UnexpectedExceptionFailure f(test, e); +#if CPPUTEST_HAVE_RTTI + STRCMP_CONTAINS("Unexpected exception of type '", f.getMessage().asCharString()); + STRCMP_CONTAINS("runtime_error", f.getMessage().asCharString()); + STRCMP_CONTAINS("' was thrown: Some error", f.getMessage().asCharString()); +#else + FAILURE_EQUAL("Unexpected exception of unknown type was thrown.", f); +#endif +} +#endif diff --git a/tests/TestFilterTest.cpp b/tests/CppUTest/TestFilterTest.cpp similarity index 94% rename from tests/TestFilterTest.cpp rename to tests/CppUTest/TestFilterTest.cpp index ba476d3d6..231a01a0a 100644 --- a/tests/TestFilterTest.cpp +++ b/tests/CppUTest/TestFilterTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -141,7 +141,7 @@ TEST(TestFilter, stringFromWithStrictInvertMatching) TEST(TestFilter, listOfFilters) { - TestFilter *listOfFilters = NULL; + TestFilter *listOfFilters = NULLPTR; TestFilter first("foo"); TestFilter secnd("bar"); listOfFilters = first.add(listOfFilters); @@ -150,7 +150,7 @@ TEST(TestFilter, listOfFilters) STRCMP_EQUAL("TestFilter: \"bar\"", StringFrom(*current).asCharString()); current = current->getNext(); STRCMP_EQUAL("TestFilter: \"foo\"", StringFrom(*current).asCharString()); - POINTERS_EQUAL(NULL, current->getNext()); + POINTERS_EQUAL(NULLPTR, current->getNext()); } TEST(TestFilter, constructors) @@ -158,9 +158,9 @@ TEST(TestFilter, constructors) TestFilter filter1; TestFilter filter2(SimpleString("a")); TestFilter filter3("a"); - CHECK(filter1.getNext() == NULL); - CHECK(filter2.getNext() == NULL); - CHECK(filter3.getNext() == NULL); + CHECK(filter1.getNext() == NULLPTR); + CHECK(filter2.getNext() == NULLPTR); + CHECK(filter3.getNext() == NULLPTR); CHECK(filter2.match("ab")); CHECK(filter3.match("ab")); } diff --git a/tests/CppUTest/TestHarness_cTest.cpp b/tests/CppUTest/TestHarness_cTest.cpp new file mode 100644 index 000000000..fadc66f1d --- /dev/null +++ b/tests/CppUTest/TestHarness_cTest.cpp @@ -0,0 +1,884 @@ +/* + * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "CppUTest/TestHarness_c.h" + +#include "CppUTest/TestHarness.h" +#include "CppUTest/TestRegistry.h" +#include "CppUTest/TestOutput.h" +#include "CppUTest/TestTestingFixture.h" +#include "CppUTest/PlatformSpecificFunctions.h" + + +extern "C" int setup_teardown_was_called_in_test_group_in_C; +extern "C" int test_was_called_in_test_group_in_C; +int setup_teardown_was_called_in_test_group_in_C = 0; +int test_was_called_in_test_group_in_C = 0; + +TEST_GROUP_C_WRAPPER(TestGroupInC) +{ + TEST_GROUP_C_SETUP_WRAPPER(TestGroupInC) + TEST_GROUP_C_TEARDOWN_WRAPPER(TestGroupInC) +}; + +TEST_C_WRAPPER(TestGroupInC, checkThatTheTestHasRun) +IGNORE_TEST_C_WRAPPER(TestGroupInC, ignoreMacroForCFile) + +/* + * This test is a bit strange. They use the fact that you can do -r2 for repeating the same run. + * When you do so, the same statics will be shared and therefore we can test whether the setup/teardown is run + * correctly. + */ + +TEST(TestGroupInC, setupHasBeenCalled) +{ + test_was_called_in_test_group_in_C++; + /* Increased in setup, decreased in teardown. So at this point it must be 1 also on a multiple run */ + LONGS_EQUAL(1, setup_teardown_was_called_in_test_group_in_C); +} + +static bool hasDestructorOfTheDestructorCheckedBeenCalled; + +class HasTheDestructorBeenCalledChecker +{ +public: + HasTheDestructorBeenCalledChecker(){} + ~HasTheDestructorBeenCalledChecker() { hasDestructorOfTheDestructorCheckedBeenCalled = true; } +}; + +TEST_GROUP(TestHarness_c) +{ + TestTestingFixture* fixture; + TEST_SETUP() + { + hasDestructorOfTheDestructorCheckedBeenCalled = false; + fixture = new TestTestingFixture(); + } + TEST_TEARDOWN() + { + delete fixture; + } +}; + +static void failBoolMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_BOOL(1, 0); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkBool) +{ + CHECK_EQUAL_C_BOOL(1, 1); + CHECK_EQUAL_C_BOOL(1, 2); + fixture->setTestFunction(failBoolMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected \n\tbut was "); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failBoolTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_BOOL_TEXT(1, 0, "BoolTestText"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkBoolText) +{ + CHECK_EQUAL_C_BOOL_TEXT(1, 1, "Text"); + CHECK_EQUAL_C_BOOL_TEXT(1, 2, "Text"); + fixture->setTestFunction(failBoolTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected \n\tbut was "); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: BoolTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failIntMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_INT(1, 2); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkInt) +{ + CHECK_EQUAL_C_INT(2, 2); + fixture->setTestFunction(failIntMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failIntTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_INT_TEXT(1, 2, "IntTestText"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkIntText) +{ + CHECK_EQUAL_C_INT_TEXT(2, 2, "Text"); + fixture->setTestFunction(failIntTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: IntTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failUnsignedIntMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_UINT(1, 2); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkUnsignedInt) +{ + CHECK_EQUAL_C_UINT(2, 2); + fixture->setTestFunction(failUnsignedIntMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failUnsignedIntTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_UINT_TEXT(1, 2, "UnsignedIntTestText"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkUnsignedIntText) +{ + CHECK_EQUAL_C_UINT_TEXT(2, 2, "Text"); + fixture->setTestFunction(failUnsignedIntTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: UnsignedIntTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failLongIntMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_LONG(1, 2); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkLongInt) +{ + CHECK_EQUAL_C_LONG(2, 2); + fixture->setTestFunction(failLongIntMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failLongIntTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_LONG_TEXT(1, 2, "LongIntTestText"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkLongIntText) +{ + CHECK_EQUAL_C_LONG_TEXT(2, 2, "Text"); + fixture->setTestFunction(failLongIntTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: LongIntTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failUnsignedLongIntMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_ULONG(1, 2); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkUnsignedLongInt) +{ + CHECK_EQUAL_C_ULONG(2, 2); + fixture->setTestFunction(failUnsignedLongIntMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failUnsignedLongIntTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_ULONG_TEXT(1, 2, "UnsignedLongIntTestText"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkUnsignedLongIntText) +{ + CHECK_EQUAL_C_ULONG_TEXT(2, 2, "Text"); + fixture->setTestFunction(failUnsignedLongIntTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: UnsignedLongIntTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +#if CPPUTEST_USE_LONG_LONG + +static void failLongLongIntMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_LONGLONG(1, 2); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkLongLongInt) +{ + CHECK_EQUAL_C_LONGLONG(2, 2); + fixture->setTestFunction(failLongLongIntMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failLongLongIntTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_LONGLONG_TEXT(1, 2, "LongLongTestText"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkLongLongIntText) +{ + CHECK_EQUAL_C_LONGLONG_TEXT(2, 2, "Text"); + fixture->setTestFunction(failLongLongIntTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: LongLongTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failUnsignedLongLongIntMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_ULONGLONG(1, 2); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkUnsignedLongLongInt) +{ + CHECK_EQUAL_C_ULONGLONG(2, 2); + fixture->setTestFunction(failUnsignedLongLongIntMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failUnsignedLongLongIntTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_ULONGLONG_TEXT(1, 2, "UnsignedLongLongTestText"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkUnsignedLongLongIntText) +{ + CHECK_EQUAL_C_ULONGLONG_TEXT(2, 2, "Text"); + fixture->setTestFunction(failUnsignedLongLongIntTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: UnsignedLongLongTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +#else + +static void failLongLongIntMethod_() +{ + cpputest_longlong dummy_longlong; + CHECK_EQUAL_C_LONGLONG(dummy_longlong, dummy_longlong); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkLongLongInt) +{ + fixture->setTestFunction(failLongLongIntMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("is not supported"); + fixture->assertPrintContains("arness_c"); +} + +static void failLongLongIntTextMethod_() +{ + cpputest_longlong dummy_longlong; + CHECK_EQUAL_C_LONGLONG_TEXT(dummy_longlong, dummy_longlong, "Text"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkLongLongIntText) +{ + fixture->setTestFunction(failLongLongIntTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("is not supported"); + fixture->assertPrintContains("arness_c"); +} + +static void failUnsignedLongLongIntMethod_() +{ + cpputest_ulonglong dummy_ulonglong; + CHECK_EQUAL_C_ULONGLONG(dummy_ulonglong, dummy_ulonglong); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkUnsignedLongLongInt) +{ + fixture->setTestFunction(failUnsignedLongLongIntMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("is not supported"); + fixture->assertPrintContains("arness_c"); +} + +static void failUnsignedLongLongIntTextMethod_() +{ + cpputest_ulonglong dummy_ulonglong; + CHECK_EQUAL_C_ULONGLONG_TEXT(dummy_ulonglong, dummy_ulonglong, "Text"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkUnsignedLongLongIntText) +{ + fixture->setTestFunction(failUnsignedLongLongIntTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("is not supported"); + fixture->assertPrintContains("arness_c"); +} + +#endif + +static void failRealMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_REAL(1.0, 2.0, 0.5); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkReal) +{ + CHECK_EQUAL_C_REAL(1.0, 1.1, 0.5); + fixture->setTestFunction(failRealMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1>\n\tbut was <2>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failRealTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_REAL_TEXT(1.0, 2.0, 0.5, "RealTestText"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkRealText) +{ + CHECK_EQUAL_C_REAL_TEXT(1.0, 1.1, 0.5, "Text"); + fixture->setTestFunction(failRealTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <1>\n\tbut was <2>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: RealTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failCharMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_CHAR('a', 'c'); +} + +TEST(TestHarness_c, checkChar) +{ + CHECK_EQUAL_C_CHAR('a', 'a'); + fixture->setTestFunction(failCharMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected \n\tbut was "); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failCharTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_CHAR_TEXT('a', 'c', "CharTestText"); +} + +TEST(TestHarness_c, checkCharText) +{ + CHECK_EQUAL_C_CHAR_TEXT('a', 'a', "Text"); + fixture->setTestFunction(failCharTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected \n\tbut was "); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: CharTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failUnsignedByteMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_UBYTE(254, 253); +} + +TEST(TestHarness_c, checkUnsignedByte) +{ + CHECK_EQUAL_C_UBYTE(254, 254); + fixture->setTestFunction(failUnsignedByteMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <254>\n\tbut was <253>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failUnsignedByteTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_UBYTE_TEXT(254, 253, "UnsignedByteTestText"); +} + +TEST(TestHarness_c, checkUnsignedByteText) +{ + CHECK_EQUAL_C_UBYTE_TEXT(254, 254, "Text"); + fixture->setTestFunction(failUnsignedByteTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <254>\n\tbut was <253>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: UnsignedByteTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failSignedByteMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_SBYTE(-3, -5); +} + +TEST(TestHarness_c, checkSignedByte) +{ + CHECK_EQUAL_C_SBYTE(-3, -3); + fixture->setTestFunction(failSignedByteMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <-3>\n\tbut was <-5>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failSignedByteTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_SBYTE_TEXT(-3, -5, "SignedByteTestText"); +} + +TEST(TestHarness_c, checkSignedByteText) +{ + CHECK_EQUAL_C_SBYTE_TEXT(-3, -3, "Text"); + fixture->setTestFunction(failSignedByteTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <-3>\n\tbut was <-5>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: SignedByteTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failStringMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_STRING("Hello", "Hello World"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkString) +{ + CHECK_EQUAL_C_STRING("Hello", "Hello"); + fixture->setTestFunction(failStringMethod_); + fixture->runAllTests(); + + StringEqualFailure failure(UtestShell::getCurrent(), "file", 1, "Hello", "Hello World", ""); + fixture->assertPrintContains(failure.getMessage()); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failStringTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_STRING_TEXT("Hello", "Hello World", "StringTestText"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkStringText) +{ + CHECK_EQUAL_C_STRING_TEXT("Hello", "Hello", "Text"); + fixture->setTestFunction(failStringTextMethod_); + fixture->runAllTests(); + + StringEqualFailure failure(UtestShell::getCurrent(), "file", 1, "Hello", "Hello World", ""); + fixture->assertPrintContains(failure.getMessage()); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: StringTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failPointerMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_POINTER(NULLPTR, (void *)0x1); +} + +TEST(TestHarness_c, checkPointer) +{ + CHECK_EQUAL_C_POINTER(NULLPTR, NULLPTR); + fixture->setTestFunction(failPointerMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <0x0>\n\tbut was <0x1>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failPointerTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_POINTER_TEXT(NULLPTR, (void *)0x1, "PointerTestText"); +} + +TEST(TestHarness_c, checkPointerText) +{ + CHECK_EQUAL_C_POINTER_TEXT(NULLPTR, NULLPTR, "Text"); + fixture->setTestFunction(failPointerTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <0x0>\n\tbut was <0x1>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: PointerTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failMemcmpMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; + unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 }; + + CHECK_EQUAL_C_MEMCMP(expectedData, actualData, sizeof(expectedData)); +} + +TEST(TestHarness_c, checkMemcmp) +{ + CHECK_EQUAL_C_MEMCMP("TEST", "TEST", 5); + fixture->setTestFunction(failMemcmpMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <00 01 02 03>\n\tbut was <00 01 03 03>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failMemcmpTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; + unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 }; + + CHECK_EQUAL_C_MEMCMP_TEXT(expectedData, actualData, sizeof(expectedData), "MemcmpTestText"); +} + +TEST(TestHarness_c, checkMemcmpText) +{ + CHECK_EQUAL_C_MEMCMP_TEXT("TEST", "TEST", 5, "Text"); + fixture->setTestFunction(failMemcmpTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <00 01 02 03>\n\tbut was <00 01 03 03>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: MemcmpTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failBitsMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_BITS(0x0001, (unsigned short)0x0003, 0xFFFF); +} + +TEST(TestHarness_c, checkBits) +{ + CHECK_EQUAL_C_BITS(0xABCD, (unsigned short)0xABCD, 0xFFFF); + fixture->setTestFunction(failBitsMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <00000000 00000001>\n\tbut was <00000000 00000011>"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failBitsTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_BITS_TEXT(0x0001, (unsigned short)0x0003, 0xFFFF, "BitsTestText"); +} + +TEST(TestHarness_c, checkBitsText) +{ + CHECK_EQUAL_C_BITS_TEXT(0xABCD, (unsigned short)0xABCD, 0xFFFF, "Text"); + fixture->setTestFunction(failBitsTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("expected <00000000 00000001>\n\tbut was <00000000 00000011>"); + fixture->assertPrintContains("arness_c"); + fixture->assertPrintContains("Message: BitsTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + FAIL_TEXT_C("Booo"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkFailText) +{ + fixture->setTestFunction(failTextMethod_); + fixture->runAllTests(); + fixture->assertPrintContains("Booo"); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void failMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + FAIL_C(); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkFail) +{ + fixture->setTestFunction(failMethod_); + fixture->runAllTests(); + LONGS_EQUAL(1, fixture->getFailureCount()); + fixture->assertPrintContains("arness_c"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static bool cpputestHasCrashed; + +static void crashMethod() +{ + cpputestHasCrashed = true; +} + +TEST(TestHarness_c, doesNotCrashIfNotSetToCrash) +{ + cpputestHasCrashed = false; + UtestShell::setCrashMethod(crashMethod); + fixture->setTestFunction(failMethod_); + + fixture->runAllTests(); + + CHECK_FALSE(cpputestHasCrashed); + LONGS_EQUAL(1, fixture->getFailureCount()); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); + + UtestShell::resetCrashMethod(); +} + +TEST(TestHarness_c, doesCrashIfSetToCrash) +{ + cpputestHasCrashed = false; + UtestShell::setCrashOnFail(); + UtestShell::setCrashMethod(crashMethod); + fixture->setTestFunction(failMethod_); + + fixture->runAllTests(); + + CHECK(cpputestHasCrashed); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); + + UtestShell::restoreDefaultTestTerminator(); + UtestShell::resetCrashMethod(); +} + +static void CheckMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_C(false); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkCheck) +{ + CHECK_C(true); + fixture->setTestFunction(CheckMethod_); + fixture->runAllTests(); + LONGS_EQUAL(1, fixture->getFailureCount()); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +static void CheckTextMethod_() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_C_TEXT(false, "CheckTestText"); +} // LCOV_EXCL_LINE + +TEST(TestHarness_c, checkCheckText) +{ + CHECK_C_TEXT(true, "Text"); + fixture->setTestFunction(CheckTextMethod_); + fixture->runAllTests(); + LONGS_EQUAL(1, fixture->getFailureCount()); + fixture->assertPrintContains("Message: CheckTestText"); + CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); +} + +#if CPPUTEST_USE_MEM_LEAK_DETECTION + +TEST(TestHarness_c, cpputest_malloc_out_of_memory) +{ + cpputest_malloc_set_out_of_memory(); + CHECK(NULLPTR == cpputest_malloc(100)); + + cpputest_malloc_set_not_out_of_memory(); + void * mem = cpputest_malloc(100); + CHECK(NULLPTR != mem); + cpputest_free(mem); +} + +TEST(TestHarness_c, cpputest_malloc_out_of_memory_after_n_mallocs) +{ + cpputest_malloc_set_out_of_memory_countdown(3); + void * m1 = cpputest_malloc(10); + void * m2 = cpputest_malloc(11); + void * m3 = cpputest_malloc(12); + CHECK(m1 != NULLPTR); + CHECK(m2 != NULLPTR); + CHECK(m3 == NULLPTR); + cpputest_malloc_set_not_out_of_memory(); + cpputest_free(m1); + cpputest_free(m2); +} + +TEST(TestHarness_c, cpputest_malloc_out_of_memory_after_0_mallocs) +{ + cpputest_malloc_set_out_of_memory_countdown(0); + void * m1 = cpputest_malloc(10); + CHECK(m1 == NULLPTR); + cpputest_malloc_set_not_out_of_memory(); +} + +TEST(TestHarness_c, count_mallocs) +{ + cpputest_malloc_count_reset(); + void * m1 = cpputest_malloc(10); + void * m2 = cpputest_malloc(11); + void * m3 = cpputest_malloc(12); + cpputest_free(m1); + cpputest_free(m2); + cpputest_free(m3); + LONGS_EQUAL(3, cpputest_malloc_get_count()); +} + +#ifdef CPPUTEST_USE_STRDUP_MACROS + +TEST(TestHarness_c, cpputest_strdup) +{ + char * mem = cpputest_strdup("0123456789"); + CHECK(NULLPTR != mem); + STRCMP_EQUAL("0123456789", mem); + cpputest_free(mem); +} + +TEST(TestHarness_c, cpputest_strndup) +{ + char * mem = cpputest_strndup("0123456789", 3); + CHECK(NULLPTR != mem); + STRCMP_EQUAL("012", mem); + cpputest_free(mem); +} + +#endif + +TEST(TestHarness_c, cpputest_calloc) +{ + void * mem = cpputest_calloc(10, 10); + CHECK(NULLPTR != mem); + cpputest_free(mem); +} + +TEST(TestHarness_c, cpputest_realloc_larger) +{ + const char* number_string = "123456789"; + + char* mem1 = (char*) cpputest_malloc(10); + + SimpleString::StrNCpy(mem1, number_string, 10); + + CHECK(mem1 != NULLPTR); + + char* mem2 = (char*) cpputest_realloc(mem1, 1000); + + CHECK(mem2 != NULLPTR); + STRCMP_EQUAL(number_string, mem2); + + cpputest_free(mem2); +} + +#include "CppUTest/MemoryLeakDetector.h" + +TEST(TestHarness_c, macros) +{ +#if CPPUTEST_USE_MALLOC_MACROS + MemoryLeakDetector* memLeakDetector = MemoryLeakWarningPlugin::getGlobalDetector(); + size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); +#endif + void* mem1 = malloc(10); + void* mem2 = calloc(10, 20); + void* mem3 = realloc(mem2, 100); +#if CPPUTEST_USE_MALLOC_MACROS + LONGS_EQUAL(memLeaks + 2, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); +#endif + free(mem1); + free(mem3); +#if CPPUTEST_USE_MALLOC_MACROS + LONGS_EQUAL(memLeaks, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); +#endif + +} + +TEST(TestHarness_c, callocInitializedToZero) +{ + char* mem = (char*) calloc(20, sizeof(char)); + for (int i = 0; i < 20; i++) + CHECK(mem[i] == 0); + free(mem); +} + +TEST(TestHarness_c, callocShouldReturnNULLWhenOutOfMemory) +{ + cpputest_malloc_set_out_of_memory_countdown(0); + void * m = cpputest_calloc(1, 1); + CHECK(m == NULLPTR); + cpputest_malloc_set_not_out_of_memory(); +} +#endif diff --git a/tests/TestHarness_cTestCFile.c b/tests/CppUTest/TestHarness_cTestCFile.c similarity index 88% rename from tests/TestHarness_cTestCFile.c rename to tests/CppUTest/TestHarness_cTestCFile.c index efcd37046..bfc7d767f 100644 --- a/tests/TestHarness_cTestCFile.c +++ b/tests/CppUTest/TestHarness_cTestCFile.c @@ -29,3 +29,8 @@ TEST_C(TestGroupInC, checkThatTheTestHasRun) { test_was_called_in_test_group_in_C++; } + +IGNORE_TEST_C(TestGroupInC, ignoreMacroForCFile) +{ + test_was_called_in_test_group_in_C++; +} diff --git a/tests/TestInstallerTest.cpp b/tests/CppUTest/TestInstallerTest.cpp similarity index 92% rename from tests/TestInstallerTest.cpp rename to tests/CppUTest/TestInstallerTest.cpp index ea60037f2..da59f322d 100644 --- a/tests/TestInstallerTest.cpp +++ b/tests/CppUTest/TestInstallerTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -42,15 +42,15 @@ TEST_GROUP(TestInstaller) TestInstaller* testInstaller; TestRegistry* myRegistry; TestInstallerTestUtestShell shell; - void setup() + void setup() CPPUTEST_OVERRIDE { myRegistry = new TestRegistry(); myRegistry->setCurrentRegistry(myRegistry); testInstaller = new TestInstaller(shell, "TestInstaller", "test", __FILE__, __LINE__); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { - myRegistry->setCurrentRegistry(0); + myRegistry->setCurrentRegistry(NULLPTR); testInstaller->unDo(); delete testInstaller; delete myRegistry; @@ -60,4 +60,3 @@ TEST_GROUP(TestInstaller) TEST(TestInstaller, Create) { } - diff --git a/tests/CppUTest/TestMemoryAllocatorTest.cpp b/tests/CppUTest/TestMemoryAllocatorTest.cpp new file mode 100644 index 000000000..1f2e86618 --- /dev/null +++ b/tests/CppUTest/TestMemoryAllocatorTest.cpp @@ -0,0 +1,765 @@ +/* + * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "CppUTest/TestHarness.h" +#include "CppUTest/TestMemoryAllocator.h" +#include "CppUTest/PlatformSpecificFunctions.h" +#include "CppUTest/TestTestingFixture.h" +#include "CppUTest/MemoryLeakDetector.h" + +TEST_GROUP(TestMemoryAllocatorTest) +{ + TestMemoryAllocator* allocator; + GlobalMemoryAllocatorStash memoryAllocatorStash; + + void setup() CPPUTEST_OVERRIDE + { + allocator = NULLPTR; + memoryAllocatorStash.save(); + } + + void teardown() CPPUTEST_OVERRIDE + { + memoryAllocatorStash.restore(); + delete allocator; + } +}; + +TEST(TestMemoryAllocatorTest, SetCurrentNewAllocator) +{ + allocator = new TestMemoryAllocator("new allocator for test"); + setCurrentNewAllocator(allocator); + POINTERS_EQUAL(allocator, getCurrentNewAllocator()); +} + +TEST(TestMemoryAllocatorTest, SetCurrentNewAllocatorToDefault) +{ + TestMemoryAllocator* originalAllocator = getCurrentNewAllocator(); + + setCurrentNewAllocatorToDefault(); + POINTERS_EQUAL(defaultNewAllocator(), getCurrentNewAllocator()); + + setCurrentNewAllocator(originalAllocator); +} + +TEST(TestMemoryAllocatorTest, SetCurrentNewArrayAllocator) +{ + allocator = new TestMemoryAllocator("new array allocator for test"); + setCurrentNewArrayAllocator(allocator); + POINTERS_EQUAL(allocator, getCurrentNewArrayAllocator()); + setCurrentNewArrayAllocatorToDefault(); + POINTERS_EQUAL(defaultNewArrayAllocator(), getCurrentNewArrayAllocator()); +} + +TEST(TestMemoryAllocatorTest, SetCurrentMallocAllocator) +{ + allocator = new TestMemoryAllocator("malloc_allocator"); + setCurrentMallocAllocator(allocator); + POINTERS_EQUAL(allocator, getCurrentMallocAllocator()); + setCurrentMallocAllocatorToDefault(); + POINTERS_EQUAL(defaultMallocAllocator(), getCurrentMallocAllocator()); +} + +TEST(TestMemoryAllocatorTest, MemoryAllocation) +{ + allocator = new TestMemoryAllocator(); + allocator->free_memory(allocator->alloc_memory(100, "file", 1), 100, "file", 1); +} + +TEST(TestMemoryAllocatorTest, MallocNames) +{ + STRCMP_EQUAL("Standard Malloc Allocator", defaultMallocAllocator()->name()); + STRCMP_EQUAL("malloc", defaultMallocAllocator()->alloc_name()); + STRCMP_EQUAL("free", defaultMallocAllocator()->free_name()); +} + +TEST(TestMemoryAllocatorTest, NewNames) +{ + STRCMP_EQUAL("Standard New Allocator", defaultNewAllocator()->name()); + STRCMP_EQUAL("new", defaultNewAllocator()->alloc_name()); + STRCMP_EQUAL("delete", defaultNewAllocator()->free_name()); +} + +TEST(TestMemoryAllocatorTest, NewArrayNames) +{ + STRCMP_EQUAL("Standard New [] Allocator", defaultNewArrayAllocator()->name()); + STRCMP_EQUAL("new []", defaultNewArrayAllocator()->alloc_name()); + STRCMP_EQUAL("delete []", defaultNewArrayAllocator()->free_name()); +} + +TEST(TestMemoryAllocatorTest, NullUnknownAllocation) +{ + allocator = new NullUnknownAllocator; + allocator->free_memory(allocator->alloc_memory(100, "file", 1), 100, "file", 1); +} + +TEST(TestMemoryAllocatorTest, NullUnknownNames) +{ + allocator = new NullUnknownAllocator; + STRCMP_EQUAL("Null Allocator", allocator->name()); + STRCMP_EQUAL("unknown", allocator->alloc_name()); + STRCMP_EQUAL("unknown", allocator->free_name()); +} + +#if (! CPPUTEST_SANITIZE_ADDRESS) + +#define MAX_SIZE_FOR_ALLOC ((size_t) -1 > (unsigned short)-1) ? (size_t)(-97) : (size_t)(-1) + +static void failTryingToAllocateTooMuchMemory(void) +{ + TestMemoryAllocator allocator; + allocator.alloc_memory(MAX_SIZE_FOR_ALLOC, "file", 1); +} // LCOV_EXCL_LINE + +TEST(TestMemoryAllocatorTest, TryingToAllocateTooMuchFailsTest) +{ + TestTestingFixture fixture; + fixture.setTestFunction(&failTryingToAllocateTooMuchMemory); + fixture.runAllTests(); + fixture.assertPrintContains("malloc returned null pointer"); +} + +#endif + +TEST_GROUP(MemoryLeakAllocator) +{ + MemoryLeakAllocator* allocator; + + void setup() CPPUTEST_OVERRIDE + { + allocator = new MemoryLeakAllocator(defaultMallocAllocator()); + } + + void teardown() CPPUTEST_OVERRIDE + { + delete allocator; + } +}; + +TEST(MemoryLeakAllocator, allocMemory) +{ + char* memory = allocator->alloc_memory(10, __FILE__, __LINE__); + memory[0] = 'B'; + MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(allocator->actualAllocator(), memory); + + /* No leaks or crashes */ +} + +TEST(MemoryLeakAllocator, freeMemory) +{ + char* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(allocator->actualAllocator(), 10); + allocator->free_memory(memory, 10, __FILE__, __LINE__); + + /* No leaks or crashes */ +} + +TEST(MemoryLeakAllocator, originalAllocator) +{ + POINTERS_EQUAL(defaultMallocAllocator(), allocator->actualAllocator()); + STRCMP_EQUAL(defaultMallocAllocator()->alloc_name(), allocator->alloc_name()); + STRCMP_EQUAL(defaultMallocAllocator()->free_name(), allocator->free_name()); +} + +TEST(MemoryLeakAllocator, name) +{ + STRCMP_EQUAL("MemoryLeakAllocator", allocator->name()); +} + +#if CPPUTEST_USE_MEM_LEAK_DETECTION +#if CPPUTEST_USE_MALLOC_MACROS + +class FailableMemoryAllocatorExecFunction : public ExecFunction +{ +public: + FailableMemoryAllocator* allocator_; + void (*testFunction_)(FailableMemoryAllocator*); + + void exec() CPPUTEST_OVERRIDE + { + testFunction_(allocator_); + } + + FailableMemoryAllocatorExecFunction() : allocator_(NULLPTR), testFunction_(NULLPTR) {} + virtual ~FailableMemoryAllocatorExecFunction() CPPUTEST_DESTRUCTOR_OVERRIDE {} +}; + +TEST_GROUP(FailableMemoryAllocator) +{ + FailableMemoryAllocator *failableMallocAllocator; + FailableMemoryAllocatorExecFunction testFunction; + TestTestingFixture fixture; + GlobalMemoryAllocatorStash stash; + + void setup() CPPUTEST_OVERRIDE + { + stash.save(); + testFunction.allocator_ = failableMallocAllocator = new FailableMemoryAllocator("Failable Malloc Allocator", "malloc", "free"); + fixture.setTestFunction(&testFunction); + setCurrentMallocAllocator(failableMallocAllocator); + } + void teardown() CPPUTEST_OVERRIDE + { + failableMallocAllocator->checkAllFailedAllocsWereDone(); + failableMallocAllocator->clearFailedAllocs(); + delete failableMallocAllocator; + stash.restore(); + } +}; + +TEST(FailableMemoryAllocator, MallocWorksNormallyIfNotAskedToFail) +{ + int *memory = (int*)malloc(sizeof(int)); + CHECK(memory != NULLPTR); + free(memory); +} + +TEST(FailableMemoryAllocator, FailFirstMalloc) +{ + failableMallocAllocator->failAllocNumber(1); + POINTERS_EQUAL(NULLPTR, (int*)malloc(sizeof(int))); +} + +TEST(FailableMemoryAllocator, FailSecondAndFourthMalloc) +{ + failableMallocAllocator->failAllocNumber(2); + failableMallocAllocator->failAllocNumber(4); + int *memory1 = (int*)malloc(sizeof(int)); + int *memory2 = (int*)malloc(sizeof(int)); + int *memory3 = (int*)malloc(sizeof(int)); + int *memory4 = (int*)malloc(sizeof(int)); + + CHECK(NULLPTR != memory1); + POINTERS_EQUAL(NULLPTR, memory2); + CHECK(NULLPTR != memory3); + POINTERS_EQUAL(NULLPTR, memory4); + + free(memory1); + free(memory3); +} + +static void failingAllocIsNeverDone_(FailableMemoryAllocator* failableMallocAllocator) +{ + failableMallocAllocator->failAllocNumber(1); + failableMallocAllocator->failAllocNumber(2); + failableMallocAllocator->failAllocNumber(3); + malloc(sizeof(int)); + malloc(sizeof(int)); + failableMallocAllocator->checkAllFailedAllocsWereDone(); +} + +TEST(FailableMemoryAllocator, CheckAllFailingAllocsWereDone) +{ + testFunction.testFunction_ = failingAllocIsNeverDone_; + + fixture.runAllTests(); + + LONGS_EQUAL(1, fixture.getFailureCount()); + fixture.assertPrintContains("Expected allocation number 3 was never done"); + failableMallocAllocator->clearFailedAllocs(); +} + +TEST(FailableMemoryAllocator, FailFirstAllocationAtGivenLine) +{ + failableMallocAllocator->failNthAllocAt(1, __FILE__, __LINE__ + 2); + + POINTERS_EQUAL(NULLPTR, malloc(sizeof(int))); +} + +TEST(FailableMemoryAllocator, FailThirdAllocationAtGivenLine) +{ + int *memory[10] = { NULLPTR }; + int allocation; + failableMallocAllocator->failNthAllocAt(3, __FILE__, __LINE__ + 4); + + for (allocation = 1; allocation <= 10; allocation++) + { + memory[allocation - 1] = (int *)malloc(sizeof(int)); + if (memory[allocation - 1] == NULLPTR) + break; + free(memory[allocation -1]); + } + + LONGS_EQUAL(3, allocation); +} + +static void failingLocationAllocIsNeverDone_(FailableMemoryAllocator* failableMallocAllocator) +{ + failableMallocAllocator->failNthAllocAt(1, "TestMemoryAllocatorTest.cpp", __LINE__); + failableMallocAllocator->checkAllFailedAllocsWereDone(); +} + +TEST(FailableMemoryAllocator, CheckAllFailingLocationAllocsWereDone) +{ + testFunction.testFunction_ = failingLocationAllocIsNeverDone_; + + fixture.runAllTests(); + + LONGS_EQUAL(1, fixture.getFailureCount()); + fixture.assertPrintContains("Expected failing alloc at TestMemoryAllocatorTest.cpp:"); + fixture.assertPrintContains("was never done"); + + failableMallocAllocator->clearFailedAllocs(); +} + +#endif +#endif + +class MemoryAccountantExecFunction + : public ExecFunction +{ +public: + virtual ~MemoryAccountantExecFunction() CPPUTEST_DESTRUCTOR_OVERRIDE + { + } + + void (*testFunction_)(MemoryAccountant*); + MemoryAccountant* parameter_; + + virtual void exec() CPPUTEST_OVERRIDE + { + testFunction_(parameter_); + } +}; + +TEST_GROUP(TestMemoryAccountant) +{ + MemoryAccountant accountant; + TestTestingFixture fixture; + MemoryAccountantExecFunction testFunction; + + void setup() CPPUTEST_OVERRIDE + { + testFunction.parameter_ = &accountant; + fixture.setTestFunction(&testFunction); + } + + void teardown() CPPUTEST_OVERRIDE + { + accountant.clear(); + } +}; + +TEST(TestMemoryAccountant, totalAllocsIsZero) +{ + LONGS_EQUAL(0, accountant.totalAllocations()); + LONGS_EQUAL(0, accountant.totalDeallocations()); +} + +TEST(TestMemoryAccountant, countAllocationsPerSize) +{ + accountant.alloc(4); + LONGS_EQUAL(1, accountant.totalAllocationsOfSize(4)); + LONGS_EQUAL(0, accountant.totalAllocationsOfSize(10)); + LONGS_EQUAL(1, accountant.totalAllocations()); + LONGS_EQUAL(0, accountant.maximumAllocationAtATimeOfSize(10)); +} + +TEST(TestMemoryAccountant, countAllocationsPerSizeMultipleAllocations) +{ + accountant.alloc(4); + accountant.alloc(4); + accountant.alloc(8); + LONGS_EQUAL(2, accountant.totalAllocationsOfSize(4)); + LONGS_EQUAL(1, accountant.totalAllocationsOfSize(8)); + LONGS_EQUAL(0, accountant.totalAllocationsOfSize(10)); + LONGS_EQUAL(3, accountant.totalAllocations()); +} + +TEST(TestMemoryAccountant, countAllocationsPerSizeMultipleAllocationsOutOfOrder) +{ + accountant.alloc(4); + accountant.alloc(8); + accountant.alloc(4); + accountant.alloc(5); + accountant.alloc(2); + accountant.alloc(4); + accountant.alloc(10); + + LONGS_EQUAL(3, accountant.totalAllocationsOfSize(4)); + LONGS_EQUAL(1, accountant.totalAllocationsOfSize(8)); + LONGS_EQUAL(1, accountant.totalAllocationsOfSize(10)); + LONGS_EQUAL(7, accountant.totalAllocations()); +} + +TEST(TestMemoryAccountant, countDeallocationsPerSizeMultipleAllocations) +{ + accountant.dealloc(8); + accountant.dealloc(4); + accountant.dealloc(8); + LONGS_EQUAL(1, accountant.totalDeallocationsOfSize(4)); + LONGS_EQUAL(2, accountant.totalDeallocationsOfSize(8)); + LONGS_EQUAL(0, accountant.totalDeallocationsOfSize(20)); + LONGS_EQUAL(3, accountant.totalDeallocations()); +} + +TEST(TestMemoryAccountant, countMaximumAllocationsAtATime) +{ + accountant.alloc(4); + accountant.alloc(4); + accountant.dealloc(4); + accountant.dealloc(4); + accountant.alloc(4); + LONGS_EQUAL(2, accountant.maximumAllocationAtATimeOfSize(4)); +} + +TEST(TestMemoryAccountant, reportNoAllocations) +{ + STRCMP_EQUAL("CppUTest Memory Accountant has not noticed any allocations or deallocations. Sorry\n", accountant.report().asCharString()); +} + +TEST(TestMemoryAccountant, reportAllocations) +{ + accountant.dealloc(8); + accountant.dealloc(8); + accountant.dealloc(8); + + accountant.alloc(4); + accountant.dealloc(4); + accountant.alloc(4); + STRCMP_EQUAL("CppUTest Memory Accountant report:\n" + "Allocation size # allocations # deallocations max # allocations at one time\n" + " 4 2 1 1\n" + " 8 0 3 0\n" + " Thank you for your business\n" + , accountant.report().asCharString()); +} + +TEST(TestMemoryAccountant, reportAllocationsWithSizeZero) +{ + accountant.dealloc(0); + + accountant.dealloc(4); + accountant.dealloc(4); + accountant.alloc(4); + + STRCMP_EQUAL("CppUTest Memory Accountant report:\n" + "Allocation size # allocations # deallocations max # allocations at one time\n" + "other 0 1 0\n" + " 4 1 2 1\n" + " Thank you for your business\n" + , accountant.report().asCharString()); +} + + +static void failUseCacheSizesAfterAllocation_(MemoryAccountant* accountant) +{ + size_t cacheSizes[] = {0}; + + accountant->alloc(4); + accountant->useCacheSizes(cacheSizes, 1); +} + +TEST(TestMemoryAccountant, withCacheSizesFailsWhenAlreadyAllocatedMemory) +{ + testFunction.testFunction_ = failUseCacheSizesAfterAllocation_; + + fixture.runAllTests(); + + fixture.assertPrintContains("MemoryAccountant: Cannot set cache sizes as allocations already occured!"); +} + +TEST(TestMemoryAccountant, reportWithCacheSizesEmpty) +{ + size_t cacheSizes[] = {0}; + + accountant.useCacheSizes(cacheSizes, 0); + accountant.alloc(4); + + STRCMP_EQUAL("CppUTest Memory Accountant report (with cache sizes):\n" + "Cache size # allocations # deallocations max # allocations at one time\n" + "other 1 0 1\n" + " Thank you for your business\n" + , accountant.report().asCharString()); +} + + +TEST(TestMemoryAccountant, reportWithCacheSizes) +{ + size_t cacheSizes[] = {4}; + + accountant.useCacheSizes(cacheSizes, 1); + accountant.dealloc(8); + accountant.dealloc(12); + accountant.dealloc(20); + + accountant.alloc(4); + accountant.dealloc(4); + accountant.alloc(4); + STRCMP_EQUAL("CppUTest Memory Accountant report (with cache sizes):\n" + "Cache size # allocations # deallocations max # allocations at one time\n" + " 4 2 1 1\n" + "other 0 3 0\n" + " Thank you for your business\n" + , accountant.report().asCharString()); +} + +TEST(TestMemoryAccountant, reportWithCacheSizesMultipleCaches) +{ + size_t cacheSizes[] = {4, 10, 20}; + + accountant.useCacheSizes(cacheSizes, 3); + accountant.alloc(8); + accountant.alloc(12); + accountant.alloc(20); + + accountant.alloc(4); + accountant.dealloc(4); + accountant.alloc(4); + STRCMP_EQUAL("CppUTest Memory Accountant report (with cache sizes):\n" + "Cache size # allocations # deallocations max # allocations at one time\n" + " 4 2 1 1\n" + " 10 1 0 1\n" + " 20 2 0 2\n" + "other 0 0 0\n" + " Thank you for your business\n" + , accountant.report().asCharString()); +} + + +TEST_GROUP(AccountingTestMemoryAllocator) +{ + MemoryAccountant accountant; + AccountingTestMemoryAllocator *allocator; + + void setup() CPPUTEST_OVERRIDE + { + allocator = new AccountingTestMemoryAllocator(accountant, getCurrentMallocAllocator()); + } + + void teardown() CPPUTEST_OVERRIDE + { + accountant.clear(); + delete allocator; + } +}; + +TEST(AccountingTestMemoryAllocator, canAllocateAndAccountMemory) +{ + char* memory = allocator->alloc_memory(10, __FILE__, __LINE__); + allocator->free_memory(memory, 10, __FILE__, __LINE__); + + LONGS_EQUAL(1, accountant.totalAllocationsOfSize(10)); + LONGS_EQUAL(1, accountant.totalDeallocationsOfSize(10)); +} + +TEST(AccountingTestMemoryAllocator, canAllocateAndAccountMemoryMultipleAllocations) +{ + char* memory1 = allocator->alloc_memory(10, __FILE__, __LINE__); + char* memory2 = allocator->alloc_memory(8, __FILE__, __LINE__); + char* memory3 = allocator->alloc_memory(12, __FILE__, __LINE__); + + allocator->free_memory(memory1, 10, __FILE__, __LINE__); + allocator->free_memory(memory3, 12, __FILE__, __LINE__); + + char* memory4 = allocator->alloc_memory(15, __FILE__, __LINE__); + char* memory5 = allocator->alloc_memory(20, __FILE__, __LINE__); + + allocator->free_memory(memory2, 8, __FILE__, __LINE__); + allocator->free_memory(memory4, 15, __FILE__, __LINE__); + allocator->free_memory(memory5, 20, __FILE__, __LINE__); + + char* memory6 = allocator->alloc_memory(1, __FILE__, __LINE__); + char* memory7 = allocator->alloc_memory(100, __FILE__, __LINE__); + + allocator->free_memory(memory6, 1, __FILE__, __LINE__); + allocator->free_memory(memory7, 100, __FILE__, __LINE__); + + LONGS_EQUAL(7, accountant.totalAllocations()); + LONGS_EQUAL(7, accountant.totalDeallocations()); +} + +TEST(AccountingTestMemoryAllocator, useOriginalAllocatorWhenDeallocatingMemoryNotAllocatedByAllocator) +{ + char* memory = getCurrentMallocAllocator()->alloc_memory(10, __FILE__, __LINE__); + allocator->free_memory(memory, 10, __FILE__, __LINE__); + + LONGS_EQUAL(0, accountant.totalAllocations()); + LONGS_EQUAL(1, accountant.totalDeallocations()); +} + +TEST(AccountingTestMemoryAllocator, allocatorForwardsAllocAndFreeName) +{ + STRCMP_EQUAL("malloc", allocator->alloc_name()); + STRCMP_EQUAL("free", allocator->free_name()); +} + + +class GlobalMemoryAccountantExecFunction + : public ExecFunction +{ +public: + void (*testFunction_)(GlobalMemoryAccountant*); + GlobalMemoryAccountant* parameter_; + + virtual void exec() CPPUTEST_OVERRIDE + { + testFunction_(parameter_); + } +}; + +TEST_GROUP(GlobalMemoryAccountant) +{ + GlobalMemoryAccountant accountant; + TestTestingFixture fixture; + GlobalMemoryAccountantExecFunction testFunction; + GlobalMemoryAllocatorStash stash; + + void setup() CPPUTEST_OVERRIDE + { + testFunction.parameter_ = &accountant; + fixture.setTestFunction(&testFunction); + stash.save(); + } + + void teardown() CPPUTEST_OVERRIDE + { + stash.restore(); + } +}; + +TEST(GlobalMemoryAccountant, start) +{ + accountant.start(); + + POINTERS_EQUAL(accountant.getMallocAllocator(), getCurrentMallocAllocator()); + POINTERS_EQUAL(accountant.getNewAllocator(), getCurrentNewAllocator()); + POINTERS_EQUAL(accountant.getNewArrayAllocator(), getCurrentNewArrayAllocator()); + + accountant.stop(); +} + +TEST(GlobalMemoryAccountant, stop) +{ + TestMemoryAllocator* originalMallocAllocator = getCurrentMallocAllocator(); + TestMemoryAllocator* originalNewAllocator = getCurrentNewAllocator(); + TestMemoryAllocator* originalNewArrayAllocator = getCurrentNewArrayAllocator(); + + accountant.start(); + accountant.stop(); + + POINTERS_EQUAL(originalMallocAllocator, getCurrentMallocAllocator()); + POINTERS_EQUAL(originalNewAllocator, getCurrentNewAllocator()); + POINTERS_EQUAL(originalNewArrayAllocator, getCurrentNewArrayAllocator()); +} + +#if CPPUTEST_USE_MEM_LEAK_DETECTION + +TEST(GlobalMemoryAccountant, report) +{ + accountant.start(); + char* memory = new char[185]; + delete [] memory; + accountant.stop(); + + /* Allocation includes memory leak info */ + STRCMP_CONTAINS("1 1 1", accountant.report().asCharString()); +} + +TEST(GlobalMemoryAccountant, reportWithCacheSizes) +{ + size_t cacheSizes[] = {512}; + accountant.useCacheSizes(cacheSizes, 1); + accountant.start(); + char* memory = new char[185]; + delete [] memory; + accountant.stop(); + + /* Allocation includes memory leak info */ + STRCMP_CONTAINS("512 1 1 1", accountant.report().asCharString()); +} + + +#endif + +static void failStopWithoutStartingWillFail_(GlobalMemoryAccountant* accountant) +{ + accountant->stop(); +} + +TEST(GlobalMemoryAccountant, StopCantBeCalledWithoutStarting) +{ + testFunction.testFunction_ = failStopWithoutStartingWillFail_; + fixture.runAllTests(); + fixture.assertPrintContains("GlobalMemoryAccount: Stop called without starting"); +} + +static void failStartingTwiceWillFail_(GlobalMemoryAccountant* accountant) +{ + accountant->start(); + accountant->start(); +} + +TEST(GlobalMemoryAccountant, startTwiceWillFail) +{ + testFunction.testFunction_ = failStartingTwiceWillFail_; + fixture.runAllTests(); + accountant.stop(); + + fixture.assertPrintContains("Global allocator start called twice!"); +} + +static void failChangeMallocMemoryAllocator_(GlobalMemoryAccountant* accountant) +{ + accountant->start(); + setCurrentMallocAllocator(defaultMallocAllocator()); + accountant->stop(); +} + +TEST(GlobalMemoryAccountant, checkWhetherMallocAllocatorIsNotChanged) +{ + testFunction.testFunction_ = failChangeMallocMemoryAllocator_; + fixture.runAllTests(); + fixture.assertPrintContains("GlobalMemoryAccountant: Malloc memory allocator has been changed while accounting for memory"); +} + +static void failChangeNewMemoryAllocator_(GlobalMemoryAccountant* accountant) +{ + accountant->start(); + setCurrentNewAllocator(defaultNewAllocator()); + accountant->stop(); +} + +TEST(GlobalMemoryAccountant, checkWhetherNewAllocatorIsNotChanged) +{ + testFunction.testFunction_ = failChangeNewMemoryAllocator_; + fixture.runAllTests(); + fixture.assertPrintContains("GlobalMemoryAccountant: New memory allocator has been changed while accounting for memory"); +} + +static void failChangeNewArrayMemoryAllocator_(GlobalMemoryAccountant* accountant) +{ + accountant->start(); + setCurrentNewArrayAllocator(defaultNewArrayAllocator()); + accountant->stop(); +} + +TEST(GlobalMemoryAccountant, checkWhetherNewArrayAllocatorIsNotChanged) +{ + testFunction.testFunction_ = failChangeNewArrayMemoryAllocator_; + fixture.runAllTests(); + fixture.assertPrintContains("GlobalMemoryAccountant: New Array memory allocator has been changed while accounting for memory"); +} diff --git a/tests/TestOutputTest.cpp b/tests/CppUTest/TestOutputTest.cpp similarity index 76% rename from tests/TestOutputTest.cpp rename to tests/CppUTest/TestOutputTest.cpp index 5a9786c47..bde55df4f 100644 --- a/tests/TestOutputTest.cpp +++ b/tests/CppUTest/TestOutputTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,11 +30,11 @@ #include "CppUTest/TestResult.h" #include "CppUTest/PlatformSpecificFunctions.h" -static long millisTime; +static unsigned long millisTime; extern "C" { - static long MockGetPlatformSpecificTimeInMillis() + static unsigned long MockGetPlatformSpecificTimeInMillis() { return millisTime; } @@ -51,7 +51,7 @@ TEST_GROUP(TestOutput) TestFailure *f3; TestResult* result; - void setup() + void setup() CPPUTEST_OVERRIDE { mock = new StringBufferTestOutput(); printer = mock; @@ -66,7 +66,7 @@ TEST_GROUP(TestOutput) TestOutput::setWorkingEnvironment(TestOutput::eclipse); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { TestOutput::setWorkingEnvironment(TestOutput::detectEnvironment); delete printer; @@ -76,6 +76,12 @@ TEST_GROUP(TestOutput) delete f3; delete result; } + + void runOneTest() + { + result->countTest(); + result->countRun(); + } }; TEST(TestOutput, PrintConstCharStar) @@ -87,10 +93,19 @@ TEST(TestOutput, PrintConstCharStar) TEST(TestOutput, PrintLong) { - printer->print(1234); + long number = 1234; + printer->print(number); STRCMP_EQUAL("1234", mock->getOutput().asCharString()); } +TEST(TestOutput, PrintSize) +{ + size_t ten = 10; + printer->print(ten); + STRCMP_EQUAL("10", mock->getOutput().asCharString()); +} + + TEST(TestOutput, PrintDouble) { printer->printDouble(12.34); @@ -117,6 +132,24 @@ TEST(TestOutput, PrintTestALot) STRCMP_EQUAL("..................................................\n..........", mock->getOutput().asCharString()); } +TEST(TestOutput, PrintTestALotAndSimulateRepeatRun) +{ + for (int i = 0; i < 60; ++i) { + runOneTest(); + printer->printCurrentTestEnded(*result); + } + + printer->printTestsEnded(*result); + + for (int i = 0; i < 60; ++i) { + runOneTest(); + printer->printCurrentTestEnded(*result); + } + STRCMP_EQUAL("..................................................\n.........." \ + "\nOK (60 tests, 60 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)\n\n" \ + "..................................................\n..........", mock->getOutput().asCharString()); +} + TEST(TestOutput, SetProgressIndicator) { printer->setProgressIndicator("."); @@ -131,14 +164,14 @@ TEST(TestOutput, SetProgressIndicator) TEST(TestOutput, PrintTestVerboseStarted) { - mock->verbose(); + mock->verbose(TestOutput::level_verbose); printer->printCurrentTestStarted(*tst); STRCMP_EQUAL("TEST(group, test)", mock->getOutput().asCharString()); } TEST(TestOutput, PrintTestVerboseEnded) { - mock->verbose(); + mock->verbose(TestOutput::level_verbose); result->currentTestStarted(tst); millisTime = 5; result->currentTestEnded(tst); @@ -148,17 +181,21 @@ TEST(TestOutput, PrintTestVerboseEnded) TEST(TestOutput, printColorWithSuccess) { mock->color(); + runOneTest(); printer->printTestsEnded(*result); - STRCMP_EQUAL("\n\033[32;1mOK (0 tests, 0 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)\033[m\n\n", mock->getOutput().asCharString()); + STRCMP_EQUAL("\n\033[32;1mOK (1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)\033[m\n\n", + mock->getOutput().asCharString()); } TEST(TestOutput, printColorWithFailures) { mock->color(); + runOneTest(); result->addFailure(*f); printer->flush(); printer->printTestsEnded(*result); - STRCMP_EQUAL("\n\033[31;1mErrors (1 failures, 0 tests, 0 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)\033[m\n\n", mock->getOutput().asCharString()); + STRCMP_EQUAL("\n\033[31;1mErrors (1 failures, 1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)" + "\033[m\n\n", mock->getOutput().asCharString()); } TEST(TestOutput, PrintTestRun) @@ -234,42 +271,53 @@ TEST(TestOutput, printTestsEndedWithFailures) STRCMP_EQUAL("\nErrors (1 failures, 0 tests, 0 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)\n\n", mock->getOutput().asCharString()); } +TEST(TestOutput, printTestsEndedWithNoTestsRunOrIgnored) +{ + result->countTest(); + printer->flush(); + printer->printTestsEnded(*result); + STRCMP_EQUAL("\nErrors (ran nothing, 1 tests, 0 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)\n" + "Note: test run failed because no tests were run or ignored. Assuming something went wrong. " + "This often happens because of linking errors or typos in test filter.\n\n", + mock->getOutput().asCharString()); +} + class CompositeTestOutputTestStringBufferTestOutput : public StringBufferTestOutput { public: - virtual void printTestsStarted() + virtual void printTestsStarted() CPPUTEST_OVERRIDE { output += "Test Start\n"; } - virtual void printTestsEnded(const TestResult& result) + virtual void printTestsEnded(const TestResult& result) CPPUTEST_OVERRIDE { - output += StringFromFormat("Test End %d\n", result.getTestCount()); + output += StringFromFormat("Test End %d\n", (int) result.getTestCount()); } - void printCurrentGroupStarted(const UtestShell& test) + void printCurrentGroupStarted(const UtestShell& test) CPPUTEST_OVERRIDE { output += StringFromFormat("Group %s Start\n", test.getGroup().asCharString()); } - void printCurrentGroupEnded(const TestResult& res) + void printCurrentGroupEnded(const TestResult& res) CPPUTEST_OVERRIDE { - output += StringFromFormat("Group End %d\n", res.getTestCount()); + output += StringFromFormat("Group End %d\n", (int) res.getTestCount()); } - virtual void printCurrentTestStarted(const UtestShell&) + virtual void printCurrentTestStarted(const UtestShell&) CPPUTEST_OVERRIDE { output += "s"; } - void flush() + void flush() CPPUTEST_OVERRIDE { output += "flush"; } virtual bool isVerbose() { - return verbose_; + return verbose_ == level_verbose || verbose_ == level_veryVerbose; } virtual bool isColor() @@ -291,7 +339,7 @@ TEST_GROUP(CompositeTestOutput) TestResult* result; UtestShell* test; - void setup() + void setup() CPPUTEST_OVERRIDE { output1 = new CompositeTestOutputTestStringBufferTestOutput; output2 = new CompositeTestOutputTestStringBufferTestOutput; @@ -301,7 +349,7 @@ TEST_GROUP(CompositeTestOutput) test = new UtestShell("Group", "Name", "file", 10); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete test; delete result; @@ -348,11 +396,20 @@ TEST(CompositeTestOutput, printChar) TEST(CompositeTestOutput, printLong) { - compositeOutput.print(10); + long ten = 10; + compositeOutput.print(ten); STRCMP_EQUAL("10", output1->getOutput().asCharString()); STRCMP_EQUAL("10", output2->getOutput().asCharString()); } +TEST(CompositeTestOutput, PrintSize) +{ + size_t ten = 10; + compositeOutput.print(ten); + STRCMP_EQUAL("10", output1->getOutput().asCharString()); + STRCMP_EQUAL("10", output2->getOutput().asCharString()); +} + TEST(CompositeTestOutput, printDouble) { compositeOutput.printDouble(1.01); @@ -362,7 +419,7 @@ TEST(CompositeTestOutput, printDouble) TEST(CompositeTestOutput, verbose) { - compositeOutput.verbose(); + compositeOutput.verbose(TestOutput::level_verbose); CHECK(output1->isVerbose()); CHECK(output2->isVerbose()); } @@ -414,3 +471,10 @@ TEST(CompositeTestOutput, deletePreviousInstanceWhenSettingNew) // CHECK NO MEMORY LEAKS } +TEST(CompositeTestOutput, printVeryVerbose) +{ + compositeOutput.verbose(TestOutput::level_veryVerbose); + compositeOutput.printVeryVerbose("very-verbose"); + STRCMP_EQUAL("very-verbose", output1->getOutput().asCharString()); + STRCMP_EQUAL("very-verbose", output2->getOutput().asCharString()); +} diff --git a/tests/TestRegistryTest.cpp b/tests/CppUTest/TestRegistryTest.cpp similarity index 72% rename from tests/TestRegistryTest.cpp rename to tests/CppUTest/TestRegistryTest.cpp index 6f544af8a..45d3eb309 100644 --- a/tests/TestRegistryTest.cpp +++ b/tests/CppUTest/TestRegistryTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -28,6 +28,7 @@ #include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" #include "CppUTest/TestOutput.h" +#include "CppUTest/PlatformSpecificFunctions.h" namespace { @@ -41,7 +42,7 @@ class MockTest: public UtestShell UtestShell(group, "Name", "File", testLineNumber), hasRun_(false) { } - virtual void runOneTest(TestPlugin*, TestResult&) + virtual void runOneTest(TestPlugin*, TestResult&) CPPUTEST_OVERRIDE { hasRun_ = true; } @@ -66,7 +67,7 @@ class MockTestResult: public TestResult resetCount(); } - virtual ~MockTestResult() + virtual ~MockTestResult() CPPUTEST_DESTRUCTOR_OVERRIDE { } @@ -80,27 +81,27 @@ class MockTestResult: public TestResult countCurrentGroupEnded = 0; } - virtual void testsStarted() + virtual void testsStarted() CPPUTEST_OVERRIDE { countTestsStarted++; } - virtual void testsEnded() + virtual void testsEnded() CPPUTEST_OVERRIDE { countTestsEnded++; } - virtual void currentTestStarted(UtestShell* /*test*/) + virtual void currentTestStarted(UtestShell* /*test*/) CPPUTEST_OVERRIDE { countCurrentTestStarted++; } - virtual void currentTestEnded(UtestShell* /*test*/) + virtual void currentTestEnded(UtestShell* /*test*/) CPPUTEST_OVERRIDE { countCurrentTestEnded++; } - virtual void currentGroupStarted(UtestShell* /*test*/) + virtual void currentGroupStarted(UtestShell* /*test*/) CPPUTEST_OVERRIDE { countCurrentGroupStarted++; } - virtual void currentGroupEnded(UtestShell* /*test*/) + virtual void currentGroupEnded(UtestShell* /*test*/) CPPUTEST_OVERRIDE { countCurrentGroupEnded++; } @@ -117,7 +118,7 @@ TEST_GROUP(TestRegistry) MockTest* test4; TestResult *result; MockTestResult *mockResult; - void setup() + void setup() CPPUTEST_OVERRIDE { output = new StringBufferTestOutput(); mockResult = new MockTestResult(*output); @@ -130,9 +131,9 @@ TEST_GROUP(TestRegistry) myRegistry->setCurrentRegistry(myRegistry); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { - myRegistry->setCurrentRegistry(0); + myRegistry->setCurrentRegistry(NULLPTR); delete myRegistry; delete test1; delete test2; @@ -236,7 +237,7 @@ TEST(TestRegistry, reallyUndoLastTest) TEST(TestRegistry, findTestWithNameDoesntExist) { - CHECK(myRegistry->findTestWithName("ThisTestDoesntExists") == NULL); + CHECK(myRegistry->findTestWithName("ThisTestDoesntExists") == NULLPTR); } TEST(TestRegistry, findTestWithName) @@ -245,12 +246,12 @@ TEST(TestRegistry, findTestWithName) test2->setTestName("SomeOtherTest"); myRegistry->addTest(test1); myRegistry->addTest(test2); - CHECK(myRegistry->findTestWithName("NameOfATestThatDoesExist")); + CHECK(myRegistry->findTestWithName("NameOfATestThatDoesExist") != NULLPTR); } TEST(TestRegistry, findTestWithGroupDoesntExist) { - CHECK(myRegistry->findTestWithGroup("ThisTestGroupDoesntExists") == NULL); + CHECK(myRegistry->findTestWithGroup("ThisTestGroupDoesntExists") == NULLPTR); } TEST(TestRegistry, findTestWithGroup) @@ -259,7 +260,7 @@ TEST(TestRegistry, findTestWithGroup) test2->setGroupName("SomeOtherGroup"); myRegistry->addTest(test1); myRegistry->addTest(test2); - CHECK(myRegistry->findTestWithGroup("GroupOfATestThatDoesExist")); + CHECK(myRegistry->findTestWithGroup("GroupOfATestThatDoesExist") != NULLPTR); } TEST(TestRegistry, nameFilterWorks) @@ -311,9 +312,9 @@ class MyTestPluginDummy: public TestPlugin { public: MyTestPluginDummy(const SimpleString& name) : TestPlugin(name) {} - virtual ~MyTestPluginDummy() {} - virtual void runAllPreTestAction(UtestShell&, TestResult&) _override {} - virtual void runAllPostTestAction(UtestShell&, TestResult&) _override {} + virtual ~MyTestPluginDummy() CPPUTEST_DESTRUCTOR_OVERRIDE {} + virtual void runAllPreTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE {} + virtual void runAllPostTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE {} }; TEST(TestRegistry, ResetPluginsWorks) @@ -359,3 +360,91 @@ TEST(TestRegistry, listTestGroupAndCaseNames_shouldListBackwardsGroupATestaAfter SimpleString s = output->getOutput(); STRCMP_EQUAL("GROUP_A.test_aa GROUP_B.test_b GROUP_A.test_a", s.asCharString()); } + +TEST(TestRegistry, listTestLocations_shouldListBackwardsGroupATestaAfterGroupAtestaa) +{ + test1->setGroupName("GROUP_A"); + test1->setTestName("test_a"); + test1->setFileName("cpptest_simple/my_tests/testa.cpp"); + test1->setLineNumber(100); + myRegistry->addTest(test1); + test2->setGroupName("GROUP_B"); + test2->setTestName("test_b"); + test2->setFileName("cpptest_simple/my tests/testb.cpp"); + test2->setLineNumber(200); + myRegistry->addTest(test2); + test3->setGroupName("GROUP_A"); + test3->setTestName("test_aa"); + test3->setFileName("cpptest_simple/my_tests/testaa.cpp"); + test3->setLineNumber(300); + myRegistry->addTest(test3); + + myRegistry->listTestLocations(*result); + SimpleString s = output->getOutput(); + STRCMP_EQUAL("GROUP_A.test_aa.cpptest_simple/my_tests/testaa.cpp.300\nGROUP_B.test_b.cpptest_simple/my tests/testb.cpp.200\nGROUP_A.test_a.cpptest_simple/my_tests/testa.cpp.100\n", s.asCharString()); +} + +TEST(TestRegistry, shuffleEmptyListIsNoOp) +{ + CHECK_TRUE(myRegistry->getFirstTest() == NULLPTR); + myRegistry->shuffleTests(0); + CHECK_TRUE(myRegistry->getFirstTest() == NULLPTR); +} + +TEST(TestRegistry, shuffleSingleTestIsNoOp) +{ + myRegistry->addTest(test1); + myRegistry->shuffleTests(0); + CHECK_TRUE(myRegistry->getFirstTest() == test1); +} + +static int getZero() +{ + return 0; +} + +IGNORE_TEST(TestRegistry, shuffleTestList) +{ + UT_PTR_SET(PlatformSpecificRand, getZero); + myRegistry->addTest(test3); + myRegistry->addTest(test2); + myRegistry->addTest(test1); + + UtestShell* first_before = myRegistry->getFirstTest(); + UtestShell* second_before = first_before->getNext(); + UtestShell* third_before = second_before->getNext(); + + CHECK_TRUE(first_before == test1); + CHECK_TRUE(second_before == test2); + CHECK_TRUE(third_before == test3); + CHECK_TRUE(third_before->getNext() == NULLPTR); + + // shuffle always with element at index 0: [1] 2 [3] --> [3] [2] 1 --> 2 3 1 + myRegistry->shuffleTests(0); + + UtestShell* first_after = myRegistry->getFirstTest(); + UtestShell* second_after = first_after->getNext(); + UtestShell* third_after = second_after->getNext(); + + CHECK_TRUE(first_after == test2); + CHECK_TRUE(second_after == test3); + CHECK_TRUE(third_after == test1); + CHECK_TRUE(third_after->getNext() == NULLPTR); +} + +TEST(TestRegistry, reverseTests) +{ + myRegistry->addTest(test1); + myRegistry->addTest(test2); + + myRegistry->reverseTests(); + + CHECK(test1 == myRegistry->getFirstTest()); +} + +TEST(TestRegistry, reverseZeroTests) +{ + myRegistry->reverseTests(); + + CHECK(NULLPTR == myRegistry->getFirstTest()); +} diff --git a/tests/TestResultTest.cpp b/tests/CppUTest/TestResultTest.cpp similarity index 71% rename from tests/TestResultTest.cpp rename to tests/CppUTest/TestResultTest.cpp index 88107dd4c..a2bd497ba 100644 --- a/tests/TestResultTest.cpp +++ b/tests/CppUTest/TestResultTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -31,7 +31,7 @@ extern "C" { - static long MockGetPlatformSpecificTimeInMillis() + static unsigned long MockGetPlatformSpecificTimeInMillis() { return 10; } @@ -45,14 +45,14 @@ TEST_GROUP(TestResult) TestResult* res; - void setup() + void setup() CPPUTEST_OVERRIDE { mock = new StringBufferTestOutput(); printer = mock; res = new TestResult(*printer); UT_PTR_SET(GetPlatformSpecificTimeInMillis, MockGetPlatformSpecificTimeInMillis); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete printer; delete res; @@ -64,3 +64,36 @@ TEST(TestResult, TestEndedWillPrintResultsAndExecutionTime) res->testsEnded(); CHECK(mock->getOutput().contains("10 ms")); } + +TEST(TestResult, ResultIsOkIfTestIsRunWithNoFailures) +{ + res->countTest(); + res->countRun(); + CHECK_FALSE(res->isFailure()); +} + +TEST(TestResult, ResultIsOkIfTestIsIgnored) +{ + res->countTest(); + res->countIgnored(); + CHECK_FALSE(res->isFailure()); +} + +TEST(TestResult, ResultIsNotOkIfFailures) +{ + res->countTest(); + res->countRun(); + res->addFailure(TestFailure(UtestShell::getCurrent(), StringFrom("dummy message"))); + CHECK_TRUE(res->isFailure()); +} + +TEST(TestResult, ResultIsNotOkIfNoTestsAtAll) +{ + CHECK_TRUE(res->isFailure()); +} + +TEST(TestResult, ResultIsNotOkIfNoTestsRunOrIgnored) +{ + res->countTest(); + CHECK_TRUE(res->isFailure()); +} diff --git a/tests/TestUTestMacro.cpp b/tests/CppUTest/TestUTestMacro.cpp old mode 100755 new mode 100644 similarity index 51% rename from tests/TestUTestMacro.cpp rename to tests/CppUTest/TestUTestMacro.cpp index 04b7347ee..ecc07a619 --- a/tests/TestUTestMacro.cpp +++ b/tests/CppUTest/TestUTestMacro.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -31,12 +31,24 @@ #define CHECK_TEST_FAILS_PROPER_WITH_TEXT(text) fixture.checkTestFailsWithProperTestLocation(text, __FILE__, __LINE__) +// Mainly this is for Visual C++, but we'll define it for any system that has the same behavior +// of a 32-bit long on a 64-bit system +#if defined(CPPUTEST_64BIT) && defined(CPPUTEST_64BIT_32BIT_LONGS) +// Forcing the value to be unsigned long long means that there's no sign-extension to perform +#define to_void_pointer(x) ((void *)x##ULL) +#define to_func_pointer(x) ((void (*)())x##ULL) +#else +// Probably not needed, but let's guarantee that the value is an unsigned long +#define to_void_pointer(x) ((void *)x##UL) +#define to_func_pointer(x) ((void (*)())x##UL) +#endif + TEST_GROUP(UnitTestMacros) { TestTestingFixture fixture; }; -static void _failingTestMethodWithFAIL() +static void failingTestMethodWithFAIL_() { FAIL("This test fails"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -44,23 +56,23 @@ static void _failingTestMethodWithFAIL() TEST(UnitTestMacros, FAILMakesTheTestFailPrintsTheRightResultAndStopsExecuting) { - fixture.runTestWithMethod(_failingTestMethodWithFAIL); + fixture.runTestWithMethod(failingTestMethodWithFAIL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("This test fails"); } TEST(UnitTestMacros, FAILWillPrintTheFileThatItFailed) { - fixture.runTestWithMethod(_failingTestMethodWithFAIL); + fixture.runTestWithMethod(failingTestMethodWithFAIL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT(__FILE__); } TEST(UnitTestMacros, FAILBehavesAsAProperMacro) { - if (false) FAIL("") - else CHECK(true) + if (false) FAIL(""); + else CHECK(true); - if (true) CHECK(true) - else FAIL("") + if (true) CHECK(true); + else FAIL(""); } IGNORE_TEST(UnitTestMacros, FAILworksInAnIgnoredTest) @@ -68,7 +80,7 @@ IGNORE_TEST(UnitTestMacros, FAILworksInAnIgnoredTest) FAIL("die!"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _UNSIGNED_LONGS_EQUALTestMethod() +static void UNSIGNED_LONGS_EQUALTestMethod_() { UNSIGNED_LONGS_EQUAL(1, 1); UNSIGNED_LONGS_EQUAL(1, 0); @@ -76,15 +88,15 @@ static void _UNSIGNED_LONGS_EQUALTestMethod() TEST(UnitTestMacros, TestUNSIGNED_LONGS_EQUAL) { - fixture.runTestWithMethod(_UNSIGNED_LONGS_EQUALTestMethod); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1) 0x1>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0) 0x0>"); + fixture.runTestWithMethod(UNSIGNED_LONGS_EQUALTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); } TEST(UnitTestMacros, UNSIGNED_LONGS_EQUALBehavesAsProperMacro) { - if (false) UNSIGNED_LONGS_EQUAL(1, 0) - else UNSIGNED_LONGS_EQUAL(1, 1) + if (false) UNSIGNED_LONGS_EQUAL(1, 0); + else UNSIGNED_LONGS_EQUAL(1, 1); } IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGS_EQUALWorksInAnIgnoredTest) @@ -92,23 +104,23 @@ IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGS_EQUALWorksInAnIgnoredTest) UNSIGNED_LONGS_EQUAL(1, 0); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _UNSIGNED_LONGS_EQUAL_TEXTTestMethod() +static void UNSIGNED_LONGS_EQUAL_TEXTTestMethod_() { UNSIGNED_LONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestUNSIGNED_LONGS_EQUAL_TEXT) { - fixture.runTestWithMethod(_UNSIGNED_LONGS_EQUAL_TEXTTestMethod); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1) 0x1>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0) 0x0>"); + fixture.runTestWithMethod(UNSIGNED_LONGS_EQUAL_TEXTTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, UNSIGNED_LONGS_EQUAL_TEXTBehavesAsProperMacro) { - if (false) UNSIGNED_LONGS_EQUAL_TEXT(1, 0, "Failed because it failed") - else UNSIGNED_LONGS_EQUAL_TEXT(1, 1, "Failed because it failed") + if (false) UNSIGNED_LONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); + else UNSIGNED_LONGS_EQUAL_TEXT(1, 1, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGS_EQUAL_TEXTWorksInAnIgnoredTest) @@ -116,9 +128,9 @@ IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGS_EQUAL_TEXTWorksInAnIgnoredTest) UNSIGNED_LONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -#ifdef CPPUTEST_USE_LONG_LONG +#if CPPUTEST_USE_LONG_LONG -static void _LONGLONGS_EQUALTestMethod() +static void LONGLONGS_EQUALTestMethod_() { LONGLONGS_EQUAL(1, 1); LONGLONGS_EQUAL(1, 0); @@ -126,15 +138,15 @@ static void _LONGLONGS_EQUALTestMethod() TEST(UnitTestMacros, TestLONGLONGS_EQUAL) { - fixture.runTestWithMethod(_LONGLONGS_EQUALTestMethod); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 0x1>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 0x0>"); + fixture.runTestWithMethod(LONGLONGS_EQUALTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); } TEST(UnitTestMacros, LONGLONGS_EQUALBehavesAsProperMacro) { - if (false) LONGLONGS_EQUAL(1, 0) - else LONGLONGS_EQUAL(1, 1) + if (false) LONGLONGS_EQUAL(1, 0); + else LONGLONGS_EQUAL(1, 1); } IGNORE_TEST(UnitTestMacros, LONGLONGS_EQUALWorksInAnIgnoredTest) @@ -142,23 +154,23 @@ IGNORE_TEST(UnitTestMacros, LONGLONGS_EQUALWorksInAnIgnoredTest) LONGLONGS_EQUAL(1, 0); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _LONGLONGS_EQUAL_TEXTTestMethod() +static void LONGLONGS_EQUAL_TEXTTestMethod_() { LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestLONGLONGS_EQUAL_TEXT) { - fixture.runTestWithMethod(_LONGLONGS_EQUAL_TEXTTestMethod); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 0x1>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 0x0>"); + fixture.runTestWithMethod(LONGLONGS_EQUAL_TEXTTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, LONGLONGS_EQUAL_TEXTBehavesAsProperMacro) { - if (false) LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed") - else LONGLONGS_EQUAL_TEXT(1, 1, "Failed because it failed") + if (false) LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); + else LONGLONGS_EQUAL_TEXT(1, 1, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, LONGLONGS_EQUAL_TEXTWorksInAnIgnoredTest) @@ -166,7 +178,7 @@ IGNORE_TEST(UnitTestMacros, LONGLONGS_EQUAL_TEXTWorksInAnIgnoredTest) LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _UNSIGNED_LONGLONGS_EQUALTestMethod() +static void UNSIGNED_LONGLONGS_EQUALTestMethod_() { UNSIGNED_LONGLONGS_EQUAL(1, 1); UNSIGNED_LONGLONGS_EQUAL(1, 0); @@ -174,15 +186,15 @@ static void _UNSIGNED_LONGLONGS_EQUALTestMethod() TEST(UnitTestMacros, TestUNSIGNED_LONGLONGS_EQUAL) { - fixture.runTestWithMethod(_UNSIGNED_LONGLONGS_EQUALTestMethod); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1) 0x1>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0) 0x0>"); + fixture.runTestWithMethod(UNSIGNED_LONGLONGS_EQUALTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); } TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUALBehavesAsProperMacro) { - if (false) UNSIGNED_LONGLONGS_EQUAL(1, 0) - else UNSIGNED_LONGLONGS_EQUAL(1, 1) + if (false) UNSIGNED_LONGLONGS_EQUAL(1, 0); + else UNSIGNED_LONGLONGS_EQUAL(1, 1); } IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUALWorksInAnIgnoredTest) @@ -190,23 +202,23 @@ IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUALWorksInAnIgnoredTest) UNSIGNED_LONGLONGS_EQUAL(1, 0); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _UNSIGNED_LONGLONGS_EQUAL_TEXTTestMethod() +static void UNSIGNED_LONGLONGS_EQUAL_TEXTTestMethod_() { UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestUNSIGNED_LONGLONGS_EQUAL_TEXT) { - fixture.runTestWithMethod(_UNSIGNED_LONGLONGS_EQUAL_TEXTTestMethod); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1) 0x1>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0) 0x0>"); + fixture.runTestWithMethod(UNSIGNED_LONGLONGS_EQUAL_TEXTTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUAL_TEXTBehavesAsProperMacro) { - if (false) UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed") - else UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 1, "Failed because it failed") + if (false) UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); + else UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 1, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUAL_TEXTWorksInAnIgnoredTest) @@ -214,33 +226,9 @@ IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUAL_TEXTWorksInAnIgnoredTest) UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -#else - -static void _LONGLONGS_EQUALFailsWithUnsupportedFeatureTestMethod() -{ - LONGLONGS_EQUAL(1, 1); -} // LCOV_EXCL_LINE - -static void _UNSIGNED_LONGLONGS_EQUALFailsWithUnsupportedFeatureTestMethod() -{ - UNSIGNED_LONGLONGS_EQUAL(1, 1); -} // LCOV_EXCL_LINE - -TEST(UnitTestMacros, LONGLONGS_EQUALFailsWithUnsupportedFeature) -{ - fixture.runTestWithMethod(_LONGLONGS_EQUALFailsWithUnsupportedFeatureTestMethod); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("\"CPPUTEST_USE_LONG_LONG\" is not supported"); -} - -TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUALFailsWithUnsupportedFeature) -{ - fixture.runTestWithMethod(_UNSIGNED_LONGLONGS_EQUALFailsWithUnsupportedFeatureTestMethod); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("\"CPPUTEST_USE_LONG_LONG\" is not supported"); -} - #endif /* CPPUTEST_USE_LONG_LONG */ -static void _failingTestMethodWithCHECK() +static void failingTestMethodWithCHECK_() { CHECK(false); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -248,14 +236,14 @@ static void _failingTestMethodWithCHECK() TEST(UnitTestMacros, FailureWithCHECK) { - fixture.runTestWithMethod(_failingTestMethodWithCHECK); + fixture.runTestWithMethod(failingTestMethodWithCHECK_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK(false) failed"); } TEST(UnitTestMacros, CHECKBehavesAsProperMacro) { - if (false) CHECK(false) - else CHECK(true) + if (false) CHECK(false); + else CHECK(true); } IGNORE_TEST(UnitTestMacros, CHECKWorksInAnIgnoredTest) @@ -263,7 +251,7 @@ IGNORE_TEST(UnitTestMacros, CHECKWorksInAnIgnoredTest) CHECK(false); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithCHECK_TEXT() +static void failingTestMethodWithCHECK_TEXT_() { CHECK_TEXT(false, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -271,15 +259,15 @@ static void _failingTestMethodWithCHECK_TEXT() TEST(UnitTestMacros, FailureWithCHECK_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithCHECK_TEXT); + fixture.runTestWithMethod(failingTestMethodWithCHECK_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK(false) failed"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, CHECK_TEXTBehavesAsProperMacro) { - if (false) CHECK_TEXT(false, "false") - else CHECK_TEXT(true, "true") + if (false) CHECK_TEXT(false, "false"); + else CHECK_TEXT(true, "true"); } IGNORE_TEST(UnitTestMacros, CHECK_TEXTWorksInAnIgnoredTest) @@ -287,7 +275,7 @@ IGNORE_TEST(UnitTestMacros, CHECK_TEXTWorksInAnIgnoredTest) CHECK_TEXT(false, "false"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithCHECK_TRUE() +static void failingTestMethodWithCHECK_TRUE_() { CHECK_TRUE(false); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -295,22 +283,22 @@ static void _failingTestMethodWithCHECK_TRUE() TEST(UnitTestMacros, FailureWithCHECK_TRUE) { - fixture.runTestWithMethod(_failingTestMethodWithCHECK_TRUE); + fixture.runTestWithMethod(failingTestMethodWithCHECK_TRUE_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_TRUE(false) failed"); } TEST(UnitTestMacros, CHECK_TRUEBehavesAsProperMacro) { - if (false) CHECK_TRUE(false) - else CHECK_TRUE(true) + if (false) CHECK_TRUE(false); + else CHECK_TRUE(true); } IGNORE_TEST(UnitTestMacros, CHECK_TRUEWorksInAnIgnoredTest) { - CHECK_TRUE(false) // LCOV_EXCL_LINE + CHECK_TRUE(false); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithCHECK_TRUE_TEXT() +static void failingTestMethodWithCHECK_TRUE_TEXT_() { CHECK_TRUE_TEXT(false, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -318,23 +306,23 @@ static void _failingTestMethodWithCHECK_TRUE_TEXT() TEST(UnitTestMacros, FailureWithCHECK_TRUE_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithCHECK_TRUE_TEXT); + fixture.runTestWithMethod(failingTestMethodWithCHECK_TRUE_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_TRUE(false) failed"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, CHECK_TRUE_TEXTBehavesAsProperMacro) { - if (false) CHECK_TRUE_TEXT(false, "Failed because it failed") - else CHECK_TRUE_TEXT(true, "Failed because it failed") + if (false) CHECK_TRUE_TEXT(false, "Failed because it failed"); + else CHECK_TRUE_TEXT(true, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, CHECK_TRUE_TEXTWorksInAnIgnoredTest) { - CHECK_TRUE_TEXT(false, "Failed because it failed") // LCOV_EXCL_LINE + CHECK_TRUE_TEXT(false, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithCHECK_FALSE() +static void failingTestMethodWithCHECK_FALSE_() { CHECK_FALSE(true); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -342,22 +330,22 @@ static void _failingTestMethodWithCHECK_FALSE() TEST(UnitTestMacros, FailureWithCHECK_FALSE) { - fixture.runTestWithMethod(_failingTestMethodWithCHECK_FALSE); + fixture.runTestWithMethod(failingTestMethodWithCHECK_FALSE_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_FALSE(true) failed"); } TEST(UnitTestMacros, CHECK_FALSEBehavesAsProperMacro) { - if (false) CHECK_FALSE(true) - else CHECK_FALSE(false) + if (false) CHECK_FALSE(true); + else CHECK_FALSE(false); } IGNORE_TEST(UnitTestMacros, CHECK_FALSEWorksInAnIgnoredTest) { - CHECK_FALSE(true) // LCOV_EXCL_LINE + CHECK_FALSE(true); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithCHECK_FALSE_TEXT() +static void failingTestMethodWithCHECK_FALSE_TEXT_() { CHECK_FALSE_TEXT(true, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -365,23 +353,23 @@ static void _failingTestMethodWithCHECK_FALSE_TEXT() TEST(UnitTestMacros, FailureWithCHECK_FALSE_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithCHECK_FALSE_TEXT); + fixture.runTestWithMethod(failingTestMethodWithCHECK_FALSE_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_FALSE(true)"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, CHECK_FALSE_TEXTBehavesAsProperMacro) { - if (false) CHECK_FALSE_TEXT(true, "Failed because it failed") - else CHECK_FALSE_TEXT(false, "Failed because it failed") + if (false) CHECK_FALSE_TEXT(true, "Failed because it failed"); + else CHECK_FALSE_TEXT(false, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, CHECK_FALSE_TEXTWorksInAnIgnoredTest) { - CHECK_FALSE_TEXT(true, "Failed because it failed") // LCOV_EXCL_LINE + CHECK_FALSE_TEXT(true, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithCHECK_EQUAL() +static void failingTestMethodWithCHECK_EQUAL_() { CHECK_EQUAL(1, 2); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -389,13 +377,62 @@ static void _failingTestMethodWithCHECK_EQUAL() TEST(UnitTestMacros, FailureWithCHECK_EQUAL) { - fixture.runTestWithMethod(_failingTestMethodWithCHECK_EQUAL); + fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <2>"); } +static void failingTestMethodWithCHECK_COMPARE_() +{ + double small = 0.5, big = 0.8; + CHECK_COMPARE(small, >=, big); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, FailureWithCHECK_COMPARE) +{ + fixture.runTestWithMethod(failingTestMethodWithCHECK_COMPARE_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_COMPARE(0.5 >= 0.8)"); +} + +TEST(UnitTestMacros, CHECK_COMPAREBehavesAsProperMacro) +{ + if (false) CHECK_COMPARE(1, >, 2); + else CHECK_COMPARE(1, <, 2); +} + +IGNORE_TEST(UnitTestMacros, CHECK_COMPAREWorksInAnIgnoredTest) +{ + CHECK_COMPARE(1, >, 2); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +static void failingTestMethodWithCHECK_COMPARE_TEXT_() +{ + double small = 0.5, big = 0.8; + CHECK_COMPARE_TEXT(small, >=, big, "small bigger than big"); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, FailureWithCHECK_COMPARE_TEXT) +{ + fixture.runTestWithMethod(failingTestMethodWithCHECK_COMPARE_TEXT_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_COMPARE(0.5 >= 0.8)"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("small bigger than big"); +} + +TEST(UnitTestMacros, CHECK_COMPARE_TEXTBehavesAsProperMacro) +{ + if (false) CHECK_COMPARE_TEXT(1, >, 2, "1 bigger than 2"); + else CHECK_COMPARE_TEXT(1, <, 2, "1 smaller than 2"); +} + +IGNORE_TEST(UnitTestMacros, CHECK_COMPARE_TEXTWorksInAnIgnoredTest) +{ + CHECK_COMPARE_TEXT(1, >, 2, "1 smaller than 2"); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + static int countInCountingMethod; -static int _countingMethod() +static int countingMethod_() { return countInCountingMethod++; } @@ -419,51 +456,51 @@ TEST(UnitTestMacros, UNSIGNED_LONGS_EQUAL_macroExpressionSafety) TEST(UnitTestMacros, passingCheckEqualWillNotBeEvaluatedMultipleTimesWithCHECK_EQUAL) { countInCountingMethod = 0; - CHECK_EQUAL(0, _countingMethod()); + CHECK_EQUAL(0, countingMethod_()); LONGS_EQUAL(1, countInCountingMethod); } -static void _failing_CHECK_EQUAL_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning() +static void failing_CHECK_EQUAL_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning_() { - CHECK_EQUAL(12345, _countingMethod()); + CHECK_EQUAL(12345, countingMethod_()); } // LCOV_EXCL_LINE TEST(UnitTestMacros, failing_CHECK_EQUAL_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning) { - fixture.runTestWithMethod(_failing_CHECK_EQUAL_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning); + fixture.runTestWithMethod(failing_CHECK_EQUAL_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("WARNING:\n\tThe \"Actual Parameter\" parameter is evaluated multiple times resulting in different values.\n\tThus the value in the error message is probably incorrect."); } -static void _failing_CHECK_EQUAL_WithExpectedBeingEvaluatesMultipleTimesWillGiveAWarning() +static void failing_CHECK_EQUAL_WithExpectedBeingEvaluatesMultipleTimesWillGiveAWarning_() { - CHECK_EQUAL(_countingMethod(), 12345); + CHECK_EQUAL(countingMethod_(), 12345); } // LCOV_EXCL_LINE TEST(UnitTestMacros, failing_CHECK_EQUAL_WithExpectedBeingEvaluatesMultipleTimesWillGiveAWarning) { - fixture.runTestWithMethod(_failing_CHECK_EQUAL_WithExpectedBeingEvaluatesMultipleTimesWillGiveAWarning); + fixture.runTestWithMethod(failing_CHECK_EQUAL_WithExpectedBeingEvaluatesMultipleTimesWillGiveAWarning_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("WARNING:\n\tThe \"Expected Parameter\" parameter is evaluated multiple times resulting in different values.\n\tThus the value in the error message is probably incorrect."); } TEST(UnitTestMacros, failing_CHECK_EQUAL_withParamatersThatDontChangeWillNotGiveAnyWarning) { - fixture.runTestWithMethod(_failingTestMethodWithCHECK_EQUAL); - CHECK( ! fixture.output_->getOutput().contains("WARNING")); + fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_); + fixture.assertPrintContainsNot("WARNING"); } TEST(UnitTestMacros, CHECK_EQUALBehavesAsProperMacro) { - if (false) CHECK_EQUAL(1, 2) - else CHECK_EQUAL(1, 1) + if (false) CHECK_EQUAL(1, 2); + else CHECK_EQUAL(1, 1); } IGNORE_TEST(UnitTestMacros, CHECK_EQUALWorksInAnIgnoredTest) { - CHECK_EQUAL(1, 2) // LCOV_EXCL_LINE + CHECK_EQUAL(1, 2); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithCHECK_EQUAL_TEXT() +static void failingTestMethodWithCHECK_EQUAL_TEXT_() { CHECK_EQUAL_TEXT(1, 2, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -471,7 +508,7 @@ static void _failingTestMethodWithCHECK_EQUAL_TEXT() TEST(UnitTestMacros, FailureWithCHECK_EQUAL_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithCHECK_EQUAL_TEXT); + fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <2>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); @@ -479,16 +516,91 @@ TEST(UnitTestMacros, FailureWithCHECK_EQUAL_TEXT) TEST(UnitTestMacros, CHECK_EQUAL_TEXTBehavesAsProperMacro) { - if (false) CHECK_EQUAL_TEXT(1, 2, "Failed because it failed") - else CHECK_EQUAL_TEXT(1, 1, "Failed because it failed") + if (false) CHECK_EQUAL_TEXT(1, 2, "Failed because it failed"); + else CHECK_EQUAL_TEXT(1, 1, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, CHECK_EQUAL_TEXTWorksInAnIgnoredTest) { - CHECK_EQUAL_TEXT(1, 2, "Failed because it failed") // LCOV_EXCL_LINE + CHECK_EQUAL_TEXT(1, 2, "Failed because it failed"); // LCOV_EXCL_LINE; +} // LCOV_EXCL_LINE + +static void failingTestMethodWithCHECK_EQUAL_ZERO_() +{ + CHECK_EQUAL_ZERO(1); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, FailureWithCHECK_EQUAL_ZERO) +{ + fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_ZERO_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <1>"); +} + +TEST(UnitTestMacros, passingCheckEqualWillNotBeEvaluatedMultipleTimesWithCHECK_EQUAL_ZERO) +{ + countInCountingMethod = 0; + CHECK_EQUAL_ZERO(countingMethod_()); + + LONGS_EQUAL(1, countInCountingMethod); +} + +static void failing_CHECK_EQUAL_ZERO_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning_() +{ + countInCountingMethod = 1; + CHECK_EQUAL_ZERO(countingMethod_()); +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, failing_CHECK_EQUAL_ZERO_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning) +{ + fixture.runTestWithMethod(failing_CHECK_EQUAL_ZERO_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("WARNING:\n\tThe \"Actual Parameter\" parameter is evaluated multiple times resulting in different values.\n\tThus the value in the error message is probably incorrect."); +} + +TEST(UnitTestMacros, failing_CHECK_EQUAL_ZERO_withParamatersThatDontChangeWillNotGiveAnyWarning) +{ + fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_ZERO_); + fixture.assertPrintContainsNot("WARNING"); +} + +IGNORE_TEST(UnitTestMacros, CHECK_EQUAL_ZERO_WorksInAnIgnoredTest) +{ + CHECK_EQUAL_ZERO(1); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, CHECK_EQUAL_ZERO_BehavesAsProperMacro) +{ + if (false) CHECK_EQUAL_ZERO(1); + else CHECK_EQUAL_ZERO(0); +} + +static void failingTestMethodWithCHECK_EQUAL_ZERO_TEXT_() +{ + CHECK_EQUAL_ZERO_TEXT(1, "Failed because it failed"); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, FailureWithCHECK_EQUAL_ZERO_TEXT) +{ + fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_ZERO_TEXT_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <1>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); +} + +TEST(UnitTestMacros, CHECK_EQUAL_ZERO_TEXTBehavesAsProperMacro) +{ + if (false) CHECK_EQUAL_ZERO_TEXT(1, "Failed because it failed"); + else CHECK_EQUAL_ZERO_TEXT(0, "Failed because it failed"); +} + +IGNORE_TEST(UnitTestMacros, CHECK_EQUAL_ZERO_TEXTWorksInAnIgnoredTest) +{ + CHECK_EQUAL_ZERO_TEXT(1, "Failed because it failed"); // LCOV_EXCL_LINE; } // LCOV_EXCL_LINE -static void _failingTestMethodWithLONGS_EQUAL() +static void failingTestMethodWithLONGS_EQUAL_() { LONGS_EQUAL(1, 0xff); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -496,23 +608,40 @@ static void _failingTestMethodWithLONGS_EQUAL() TEST(UnitTestMacros, FailureWithLONGS_EQUALS) { - fixture.runTestWithMethod(_failingTestMethodWithLONGS_EQUAL); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected < 1 0x01>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <255 0xff>"); + fixture.runTestWithMethod(failingTestMethodWithLONGS_EQUAL_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected < 1 (0x1)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <255 (0xff)>"); +} + +static void failingTestMethodWithLONGS_EQUALWithSymbolicParameters_() +{ +#define MONDAY 1 + int day_of_the_week = MONDAY+1; + LONGS_EQUAL(MONDAY, day_of_the_week); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, FailureWithLONGS_EQUALShowsSymbolicParameters) +{ + fixture.runTestWithMethod(failingTestMethodWithLONGS_EQUALWithSymbolicParameters_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("LONGS_EQUAL(MONDAY, day_of_the_week) failed"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <2 (0x2)>"); + CHECK_FALSE(fixture.getOutput().contains("Message: ")); } TEST(UnitTestMacros, LONGS_EQUALBehavesAsProperMacro) { - if (false) LONGS_EQUAL(1, 2) - else LONGS_EQUAL(10, 10) + if (false) LONGS_EQUAL(1, 2); + else LONGS_EQUAL(10, 10); } IGNORE_TEST(UnitTestMacros, LONGS_EQUALWorksInAnIgnoredTest) { - LONGS_EQUAL(11, 22) // LCOV_EXCL_LINE + LONGS_EQUAL(11, 22); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithLONGS_EQUAL_TEXT() +static void failingTestMethodWithLONGS_EQUAL_TEXT_() { LONGS_EQUAL_TEXT(1, 0xff, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -520,24 +649,24 @@ static void _failingTestMethodWithLONGS_EQUAL_TEXT() TEST(UnitTestMacros, FailureWithLONGS_EQUALS_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithLONGS_EQUAL_TEXT); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected < 1 0x01>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <255 0xff>"); + fixture.runTestWithMethod(failingTestMethodWithLONGS_EQUAL_TEXT_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected < 1 (0x1)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <255 (0xff)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, LONGS_EQUAL_TEXTBehavesAsProperMacro) { - if (false) LONGS_EQUAL_TEXT(1, 2, "Failed because it failed") - else LONGS_EQUAL_TEXT(10, 10, "Failed because it failed") + if (false) LONGS_EQUAL_TEXT(1, 2, "Failed because it failed"); + else LONGS_EQUAL_TEXT(10, 10, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, LONGS_EQUAL_TEXTWorksInAnIgnoredTest) { - LONGS_EQUAL_TEXT(11, 22, "Failed because it failed") // LCOV_EXCL_LINE + LONGS_EQUAL_TEXT(11, 22, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithBYTES_EQUAL() +static void failingTestMethodWithBYTES_EQUAL_() { BYTES_EQUAL('a', 'b'); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -545,23 +674,23 @@ static void _failingTestMethodWithBYTES_EQUAL() TEST(UnitTestMacros, FailureWithBYTES_EQUAL) { - fixture.runTestWithMethod(_failingTestMethodWithBYTES_EQUAL); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <97 0x61>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <98 0x62>"); + fixture.runTestWithMethod(failingTestMethodWithBYTES_EQUAL_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <97 (0x61)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <98 (0x62)>"); } TEST(UnitTestMacros, BYTES_EQUALBehavesAsProperMacro) { - if (false) BYTES_EQUAL('a', 'b') - else BYTES_EQUAL('c', 'c') + if (false) BYTES_EQUAL('a', 'b'); + else BYTES_EQUAL('c', 'c'); } IGNORE_TEST(UnitTestMacros, BYTES_EQUALWorksInAnIgnoredTest) { - BYTES_EQUAL('q', 'w') // LCOV_EXCL_LINE + BYTES_EQUAL('q', 'w'); // LCOV_EXCL_LINE; } // LCOV_EXCL_LINE -static void _failingTestMethodWithBYTES_EQUAL_TEXT() +static void failingTestMethodWithBYTES_EQUAL_TEXT_() { BYTES_EQUAL_TEXT('a', 'b', "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -569,24 +698,24 @@ static void _failingTestMethodWithBYTES_EQUAL_TEXT() TEST(UnitTestMacros, FailureWithBYTES_EQUAL_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithBYTES_EQUAL_TEXT); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <97 0x61>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <98 0x62>"); + fixture.runTestWithMethod(failingTestMethodWithBYTES_EQUAL_TEXT_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <97 (0x61)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <98 (0x62)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, BYTES_EQUAL_TEXTBehavesAsProperMacro) { - if (false) BYTES_EQUAL_TEXT('a', 'b', "Failed because it failed") - else BYTES_EQUAL_TEXT('c', 'c', "Failed because it failed") + if (false) BYTES_EQUAL_TEXT('a', 'b', "Failed because it failed"); + else BYTES_EQUAL_TEXT('c', 'c', "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, BYTES_EQUAL_TEXTWorksInAnIgnoredTest) { - BYTES_EQUAL_TEXT('q', 'w', "Failed because it failed") // LCOV_EXCL_LINE + BYTES_EQUAL_TEXT('q', 'w', "Failed because it failed"); // LCOV_EXCL_LINE; } // LCOV_EXCL_LINE -static void _failingTestMethodWithSIGNED_BYTES_EQUAL() +static void failingTestMethodWithSIGNED_BYTES_EQUAL_() { SIGNED_BYTES_EQUAL(-1, -2); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -594,28 +723,28 @@ static void _failingTestMethodWithSIGNED_BYTES_EQUAL() TEST(UnitTestMacros, FailureWithSIGNED_BYTES_EQUAL) { - fixture.runTestWithMethod(_failingTestMethodWithSIGNED_BYTES_EQUAL); + fixture.runTestWithMethod(failingTestMethodWithSIGNED_BYTES_EQUAL_); #if CPPUTEST_CHAR_BIT == 16 - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-1 0xffff>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-2 0xfffe>"); -#else - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-1 0xff>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-2 0xfe>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-1 (0xffff)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-2 (0xfffe)>"); +#elif CPPUTEST_CHAR_BIT == 8 + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-1 (0xff)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-2 (0xfe)>"); #endif } TEST(UnitTestMacros, CHARS_EQUALBehavesAsProperMacro) { - if (false) SIGNED_BYTES_EQUAL(-1, -2) - else SIGNED_BYTES_EQUAL(-3, -3) + if (false) SIGNED_BYTES_EQUAL(-1, -2); + else SIGNED_BYTES_EQUAL(-3, -3); } IGNORE_TEST(UnitTestMacros, CHARS_EQUALWorksInAnIgnoredTest) { - SIGNED_BYTES_EQUAL(-7, 19) // LCOV_EXCL_LINE + SIGNED_BYTES_EQUAL(-7, 19); // LCOV_EXCL_LINE; } // LCOV_EXCL_LINE -static void _failingTestMethodWithSIGNED_BYTES_EQUAL_TEXT() +static void failingTestMethodWithSIGNED_BYTES_EQUAL_TEXT_() { SIGNED_BYTES_EQUAL_TEXT(-127, -126, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -623,24 +752,24 @@ static void _failingTestMethodWithSIGNED_BYTES_EQUAL_TEXT() TEST(UnitTestMacros, FailureWithSIGNED_BYTES_EQUAL_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithSIGNED_BYTES_EQUAL_TEXT); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-127 0x81>"); - CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-126 0x82>"); + fixture.runTestWithMethod(failingTestMethodWithSIGNED_BYTES_EQUAL_TEXT_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-127 (0x81)>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-126 (0x82)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, CHARS_EQUAL_TEXTBehavesAsProperMacro) { - if (false) SIGNED_BYTES_EQUAL_TEXT(-1, -2, "Failed because it failed") - else SIGNED_BYTES_EQUAL_TEXT(-3, -3, "Failed because it failed") + if (false) SIGNED_BYTES_EQUAL_TEXT(-1, -2, "Failed because it failed"); + else SIGNED_BYTES_EQUAL_TEXT(-3, -3, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, SIGNED_BYTES_EQUAL_TEXTWorksInAnIgnoredTest) { - SIGNED_BYTES_EQUAL_TEXT(-7, 19, "Failed because it failed") // LCOV_EXCL_LINE + SIGNED_BYTES_EQUAL_TEXT(-7, 19, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithPOINTERS_EQUAL() +static void failingTestMethodWithPOINTERS_EQUAL_() { POINTERS_EQUAL((void*)0xa5a5, (void*)0xf0f0); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -648,23 +777,23 @@ static void _failingTestMethodWithPOINTERS_EQUAL() TEST(UnitTestMacros, FailureWithPOINTERS_EQUAL) { - fixture.runTestWithMethod(_failingTestMethodWithPOINTERS_EQUAL); + fixture.runTestWithMethod(failingTestMethodWithPOINTERS_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>"); } TEST(UnitTestMacros, POINTERS_EQUALBehavesAsProperMacro) { - if (false) POINTERS_EQUAL(0, (void*) 0xbeefbeef) - else POINTERS_EQUAL((void*)0xdeadbeef, (void*)0xdeadbeef) + if (false) POINTERS_EQUAL(NULLPTR, to_void_pointer(0xbeefbeef)); + else POINTERS_EQUAL(to_void_pointer(0xdeadbeef), to_void_pointer(0xdeadbeef)); } IGNORE_TEST(UnitTestMacros, POINTERS_EQUALWorksInAnIgnoredTest) { - POINTERS_EQUAL((void*) 0xbeef, (void*) 0xdead) // LCOV_EXCL_LINE + POINTERS_EQUAL((void*) 0xbeef, (void*) 0xdead); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithPOINTERS_EQUAL_TEXT() +static void failingTestMethodWithPOINTERS_EQUAL_TEXT_() { POINTERS_EQUAL_TEXT((void*)0xa5a5, (void*)0xf0f0, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -672,7 +801,7 @@ static void _failingTestMethodWithPOINTERS_EQUAL_TEXT() TEST(UnitTestMacros, FailureWithPOINTERS_EQUAL_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithPOINTERS_EQUAL_TEXT); + fixture.runTestWithMethod(failingTestMethodWithPOINTERS_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); @@ -680,17 +809,17 @@ TEST(UnitTestMacros, FailureWithPOINTERS_EQUAL_TEXT) TEST(UnitTestMacros, POINTERS_EQUAL_TEXTBehavesAsProperMacro) { - if (false) POINTERS_EQUAL_TEXT(0, (void*) 0xbeefbeef, "Failed because it failed") - else POINTERS_EQUAL_TEXT((void*)0xdeadbeef, (void*)0xdeadbeef, "Failed because it failed") + if (false) POINTERS_EQUAL_TEXT(NULLPTR, to_void_pointer(0xbeefbeef), "Failed because it failed"); + else POINTERS_EQUAL_TEXT(to_void_pointer(0xdeadbeef), to_void_pointer(0xdeadbeef), "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, POINTERS_EQUAL_TEXTWorksInAnIgnoredTest) { - POINTERS_EQUAL_TEXT((void*) 0xbeef, (void*) 0xdead, "Failed because it failed") // LCOV_EXCL_LINE + POINTERS_EQUAL_TEXT((void*) 0xbeef, (void*) 0xdead, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithFUNCTIONPOINTERS_EQUAL() +static void failingTestMethodWithFUNCTIONPOINTERS_EQUAL_() { FUNCTIONPOINTERS_EQUAL((void (*)())0xa5a5, (void (*)())0xf0f0); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -698,23 +827,23 @@ static void _failingTestMethodWithFUNCTIONPOINTERS_EQUAL() TEST(UnitTestMacros, FailureWithFUNCTIONPOINTERS_EQUAL) { - fixture.runTestWithMethod(_failingTestMethodWithFUNCTIONPOINTERS_EQUAL); + fixture.runTestWithMethod(failingTestMethodWithFUNCTIONPOINTERS_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>"); } TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUALBehavesAsProperMacro) { - if (false) FUNCTIONPOINTERS_EQUAL(0, (void (*)())0xbeefbeef) - else FUNCTIONPOINTERS_EQUAL((void (*)())0xdeadbeef, (void (*)())0xdeadbeef) + if (false) FUNCTIONPOINTERS_EQUAL(NULLPTR, to_func_pointer(0xbeefbeef)); + else FUNCTIONPOINTERS_EQUAL(to_func_pointer(0xdeadbeef), to_func_pointer(0xdeadbeef)); } IGNORE_TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUALWorksInAnIgnoredTest) { - FUNCTIONPOINTERS_EQUAL((void (*)())0xbeef, (void (*)())0xdead) // LCOV_EXCL_LINE + FUNCTIONPOINTERS_EQUAL((void (*)())0xbeef, (void (*)())0xdead); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithFUNCTIONPOINTERS_EQUAL_TEXT() +static void failingTestMethodWithFUNCTIONPOINTERS_EQUAL_TEXT_() { FUNCTIONPOINTERS_EQUAL_TEXT((void (*)())0xa5a5, (void (*)())0xf0f0, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -722,7 +851,7 @@ static void _failingTestMethodWithFUNCTIONPOINTERS_EQUAL_TEXT() TEST(UnitTestMacros, FailureWithFUNCTIONPOINTERS_EQUAL_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithFUNCTIONPOINTERS_EQUAL_TEXT); + fixture.runTestWithMethod(failingTestMethodWithFUNCTIONPOINTERS_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); @@ -730,19 +859,19 @@ TEST(UnitTestMacros, FailureWithFUNCTIONPOINTERS_EQUAL_TEXT) TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUAL_TEXTBehavesAsProperMacro) { - if (false) FUNCTIONPOINTERS_EQUAL_TEXT(0, (void (*)())0xbeefbeef, "Failed because it failed") - else FUNCTIONPOINTERS_EQUAL_TEXT((void (*)())0xdeadbeef, (void (*)())0xdeadbeef, "Failed because it failed") + if (false) FUNCTIONPOINTERS_EQUAL_TEXT(NULLPTR, to_func_pointer(0xbeefbeef), "Failed because it failed"); + else FUNCTIONPOINTERS_EQUAL_TEXT(to_func_pointer(0xdeadbeef), to_func_pointer(0xdeadbeef), "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUAL_TEXTWorksInAnIgnoredTest) { - FUNCTIONPOINTERS_EQUAL_TEXT((void (*)())0xbeef, (void (*)())0xdead, "Failed because it failed") // LCOV_EXCL_LINE + FUNCTIONPOINTERS_EQUAL_TEXT((void (*)())0xbeef, (void (*)())0xdead, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithDOUBLES_EQUAL() +static void failingTestMethodWithDOUBLES_EQUAL_() { DOUBLES_EQUAL(0.12, 44.1, 0.3); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -750,7 +879,7 @@ static void _failingTestMethodWithDOUBLES_EQUAL() TEST(UnitTestMacros, FailureWithDOUBLES_EQUAL) { - fixture.runTestWithMethod(_failingTestMethodWithDOUBLES_EQUAL); + fixture.runTestWithMethod(failingTestMethodWithDOUBLES_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0.12>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <44.1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("threshold used was <0.3>"); @@ -758,16 +887,16 @@ TEST(UnitTestMacros, FailureWithDOUBLES_EQUAL) TEST(UnitTestMacros, DOUBLES_EQUALBehavesAsProperMacro) { - if (false) DOUBLES_EQUAL(0.0, 1.1, 0.0005) - else DOUBLES_EQUAL(0.1, 0.2, 0.2) + if (false) DOUBLES_EQUAL(0.0, 1.1, 0.0005); + else DOUBLES_EQUAL(0.1, 0.2, 0.2); } IGNORE_TEST(UnitTestMacros, DOUBLES_EQUALWorksInAnIgnoredTest) { - DOUBLES_EQUAL(100.0, 0.0, 0.2) // LCOV_EXCL_LINE + DOUBLES_EQUAL(100.0, 0.0, 0.2); // LCOV_EXCL_LINE; } // LCOV_EXCL_LINE -static void _failingTestMethodWithDOUBLES_EQUAL_TEXT() +static void failingTestMethodWithDOUBLES_EQUAL_TEXT_() { DOUBLES_EQUAL_TEXT(0.12, 44.1, 0.3, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -775,7 +904,7 @@ static void _failingTestMethodWithDOUBLES_EQUAL_TEXT() TEST(UnitTestMacros, FailureWithDOUBLES_EQUAL_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithDOUBLES_EQUAL_TEXT); + fixture.runTestWithMethod(failingTestMethodWithDOUBLES_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0.12>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <44.1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("threshold used was <0.3>"); @@ -784,18 +913,18 @@ TEST(UnitTestMacros, FailureWithDOUBLES_EQUAL_TEXT) TEST(UnitTestMacros, DOUBLES_EQUAL_TEXTBehavesAsProperMacro) { - if (false) DOUBLES_EQUAL_TEXT(0.0, 1.1, 0.0005, "Failed because it failed") - else DOUBLES_EQUAL_TEXT(0.1, 0.2, 0.2, "Failed because it failed") + if (false) DOUBLES_EQUAL_TEXT(0.0, 1.1, 0.0005, "Failed because it failed"); + else DOUBLES_EQUAL_TEXT(0.1, 0.2, 0.2, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, DOUBLES_EQUAL_TEXTWorksInAnIgnoredTest) { - DOUBLES_EQUAL_TEXT(100.0, 0.0, 0.2, "Failed because it failed") // LCOV_EXCL_LINE + DOUBLES_EQUAL_TEXT(100.0, 0.0, 0.2, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static bool lineOfCodeExecutedAfterCheck = false; -static void _passingTestMethod() +static void passingTestMethod_() { CHECK(true); lineOfCodeExecutedAfterCheck = true; @@ -803,35 +932,35 @@ static void _passingTestMethod() TEST(UnitTestMacros, SuccessPrintsNothing) { - fixture.runTestWithMethod(_passingTestMethod); + fixture.runTestWithMethod(passingTestMethod_); LONGS_EQUAL(0, fixture.getFailureCount()); fixture.assertPrintContains(".\nOK (1 tests"); CHECK(lineOfCodeExecutedAfterCheck); } -static void _methodThatOnlyPrints() +static void methodThatOnlyPrints_() { UT_PRINT("Hello World!"); } TEST(UnitTestMacros, PrintPrintsWhateverPrintPrints) { - fixture.runTestWithMethod(_methodThatOnlyPrints); + fixture.runTestWithMethod(methodThatOnlyPrints_); LONGS_EQUAL(0, fixture.getFailureCount()); fixture.assertPrintContains("Hello World!"); fixture.assertPrintContains(__FILE__); } -static void _methodThatOnlyPrintsUsingSimpleStringFromFormat() +static void methodThatOnlyPrintsUsingSimpleStringFromFormat_() { UT_PRINT(StringFromFormat("Hello %s %d", "World!", 2009)); } TEST(UnitTestMacros, PrintPrintsSimpleStringsForExampleThoseReturnedByFromString) { - fixture.runTestWithMethod(_methodThatOnlyPrintsUsingSimpleStringFromFormat); + fixture.runTestWithMethod(methodThatOnlyPrintsUsingSimpleStringFromFormat_); fixture.assertPrintContains("Hello World! 2009"); } @@ -849,12 +978,14 @@ static int functionThatReturnsAValue() BYTES_EQUAL_TEXT(0xab, 0xab, "Shouldn't fail"); CHECK_EQUAL(100,100); CHECK_EQUAL_TEXT(100, 100, "Shouldn't fail"); + CHECK_EQUAL_ZERO(0); + CHECK_EQUAL_ZERO_TEXT(0, "Shouldn't fail"); STRCMP_EQUAL("THIS", "THIS"); STRCMP_EQUAL_TEXT("THIS", "THIS", "Shouldn't fail"); DOUBLES_EQUAL(1.0, 1.0, .01); DOUBLES_EQUAL_TEXT(1.0, 1.0, .01, "Shouldn't fail"); - POINTERS_EQUAL(0, 0); - POINTERS_EQUAL_TEXT(0, 0, "Shouldn't fail"); + POINTERS_EQUAL(NULLPTR, NULLPTR); + POINTERS_EQUAL_TEXT(NULLPTR, NULLPTR, "Shouldn't fail"); MEMCMP_EQUAL("THIS", "THIS", 5); MEMCMP_EQUAL_TEXT("THIS", "THIS", 5, "Shouldn't fail"); BITS_EQUAL(0x01, (unsigned char )0x01, 0xFF); @@ -871,8 +1002,8 @@ TEST(UnitTestMacros, allMacrosFromFunctionThatReturnsAValue) TEST(UnitTestMacros, MEMCMP_EQUALBehavesAsAProperMacro) { - if (false) MEMCMP_EQUAL("TEST", "test", 5) - else MEMCMP_EQUAL("TEST", "TEST", 5) + if (false) MEMCMP_EQUAL("TEST", "test", 5); + else MEMCMP_EQUAL("TEST", "TEST", 5); } IGNORE_TEST(UnitTestMacros, MEMCMP_EQUALWorksInAnIgnoredTest) @@ -880,7 +1011,7 @@ IGNORE_TEST(UnitTestMacros, MEMCMP_EQUALWorksInAnIgnoredTest) MEMCMP_EQUAL("TEST", "test", 5); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _MEMCMP_EQUALFailingTestMethodWithUnequalInput() +static void MEMCMP_EQUALFailingTestMethodWithUnequalInput_() { unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 }; @@ -891,49 +1022,61 @@ static void _MEMCMP_EQUALFailingTestMethodWithUnequalInput() TEST(UnitTestMacros, MEMCMP_EQUALFailureWithUnequalInput) { - fixture.runTestWithMethod(_MEMCMP_EQUALFailingTestMethodWithUnequalInput); + fixture.runTestWithMethod(MEMCMP_EQUALFailingTestMethodWithUnequalInput_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <00 01 02 03>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <00 01 03 03>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 2"); } -static void _MEMCMP_EQUALFailingTestMethodWithNullExpected() +static void MEMCMP_EQUALFailingTestMethodWithNullExpected_() { unsigned char actualData[] = { 0x00, 0x01, 0x02, 0x03 }; - MEMCMP_EQUAL(NULL, actualData, sizeof(actualData)); + MEMCMP_EQUAL(NULLPTR, actualData, sizeof(actualData)); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, MEMCMP_EQUALFailureWithNullExpected) { - fixture.runTestWithMethod(_MEMCMP_EQUALFailingTestMethodWithNullExpected); + fixture.runTestWithMethod(MEMCMP_EQUALFailingTestMethodWithNullExpected_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <00 01 02 03>"); } -static void _MEMCMP_EQUALFailingTestMethodWithNullActual() +static void MEMCMP_EQUALFailingTestMethodWithNullActual_() { unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; - MEMCMP_EQUAL(expectedData, NULL, sizeof(expectedData)); + MEMCMP_EQUAL(expectedData, NULLPTR, sizeof(expectedData)); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, MEMCMP_EQUALFailureWithNullActual) { - fixture.runTestWithMethod(_MEMCMP_EQUALFailingTestMethodWithNullActual); + fixture.runTestWithMethod(MEMCMP_EQUALFailingTestMethodWithNullActual_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <00 01 02 03>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>"); } TEST(UnitTestMacros, MEMCMP_EQUALNullExpectedNullActual) { - MEMCMP_EQUAL(NULL, NULL, 0); - MEMCMP_EQUAL(NULL, NULL, 1024); + MEMCMP_EQUAL(NULLPTR, NULLPTR, 0); + MEMCMP_EQUAL(NULLPTR, NULLPTR, 1024); } -static void _failingTestMethodWithMEMCMP_EQUAL_TEXT() +TEST(UnitTestMacros, MEMCMP_EQUALNullPointerIgnoredInExpectationWhenSize0) +{ + unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 }; + MEMCMP_EQUAL(NULLPTR, actualData, 0); +} + +TEST(UnitTestMacros, MEMCMP_EQUALNullPointerIgnoredInActualWhenSize0) +{ + unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; + MEMCMP_EQUAL(expectedData, NULLPTR, 0); +} + +static void failingTestMethodWithMEMCMP_EQUAL_TEXT_() { unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 }; @@ -944,7 +1087,7 @@ static void _failingTestMethodWithMEMCMP_EQUAL_TEXT() TEST(UnitTestMacros, FailureWithMEMCMP_EQUAL_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithMEMCMP_EQUAL_TEXT); + fixture.runTestWithMethod(failingTestMethodWithMEMCMP_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <00 01 02 03>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <00 01 03 03>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 2"); @@ -953,8 +1096,8 @@ TEST(UnitTestMacros, FailureWithMEMCMP_EQUAL_TEXT) TEST(UnitTestMacros, MEMCMP_EQUAL_TEXTBehavesAsAProperMacro) { - if (false) MEMCMP_EQUAL_TEXT("TEST", "test", 5, "Failed because it failed") - else MEMCMP_EQUAL_TEXT("TEST", "TEST", 5, "Failed because it failed") + if (false) MEMCMP_EQUAL_TEXT("TEST", "test", 5, "Failed because it failed"); + else MEMCMP_EQUAL_TEXT("TEST", "TEST", 5, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, MEMCMP_EQUAL_TEXTWorksInAnIgnoredTest) @@ -964,8 +1107,8 @@ IGNORE_TEST(UnitTestMacros, MEMCMP_EQUAL_TEXTWorksInAnIgnoredTest) TEST(UnitTestMacros, BITS_EQUALBehavesAsAProperMacro) { - if (false) BITS_EQUAL(0x00, 0xFF, 0xFF) - else BITS_EQUAL(0x00, 0x00, 0xFF) + if (false) BITS_EQUAL(0x00, 0xFF, 0xFF); + else BITS_EQUAL(0x00, 0x00, 0xFF); } IGNORE_TEST(UnitTestMacros, BITS_EQUALWorksInAnIgnoredTest) @@ -973,7 +1116,7 @@ IGNORE_TEST(UnitTestMacros, BITS_EQUALWorksInAnIgnoredTest) BITS_EQUAL(0x00, 0xFF, 0xFF); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _BITS_EQUALFailingTestMethodWithUnequalInput() +static void BITS_EQUALFailingTestMethodWithUnequalInput_() { BITS_EQUAL(0x00, 0xFF, 0xFF); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -981,7 +1124,7 @@ static void _BITS_EQUALFailingTestMethodWithUnequalInput() TEST(UnitTestMacros, BITS_EQUALFailureWithUnequalInput) { - fixture.runTestWithMethod(_BITS_EQUALFailingTestMethodWithUnequalInput); + fixture.runTestWithMethod(BITS_EQUALFailingTestMethodWithUnequalInput_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("00000000>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("11111111>"); } @@ -991,7 +1134,7 @@ TEST(UnitTestMacros, BITS_EQUALZeroMaskEqual) BITS_EQUAL(0x00, 0xFF, 0x00); } -static void _failingTestMethodWithBITS_EQUAL_TEXT() +static void failingTestMethodWithBITS_EQUAL_TEXT_() { BITS_EQUAL_TEXT(0x00, 0xFFFFFFFF, 0xFF, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -999,7 +1142,7 @@ static void _failingTestMethodWithBITS_EQUAL_TEXT() TEST(UnitTestMacros, FailureWithBITS_EQUAL_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithBITS_EQUAL_TEXT); + fixture.runTestWithMethod(failingTestMethodWithBITS_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); @@ -1007,8 +1150,8 @@ TEST(UnitTestMacros, FailureWithBITS_EQUAL_TEXT) TEST(UnitTestMacros, BITS_EQUAL_TEXTBehavesAsAProperMacro) { - if (false) BITS_EQUAL_TEXT(0x00, 0xFF, 0xFF, "Failed because it failed") - else BITS_EQUAL_TEXT(0x00, 0x00, 0xFF, "Failed because it failed") + if (false) BITS_EQUAL_TEXT(0x00, 0xFF, 0xFF, "Failed because it failed"); + else BITS_EQUAL_TEXT(0x00, 0x00, 0xFF, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, BITS_EQUAL_TEXTWorksInAnIgnoredTest) @@ -1016,8 +1159,167 @@ IGNORE_TEST(UnitTestMacros, BITS_EQUAL_TEXTWorksInAnIgnoredTest) BITS_EQUAL_TEXT(0x00, 0xFF, 0xFF, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -#if CPPUTEST_USE_STD_CPP_LIB -static void _failingTestMethod_NoThrowWithCHECK_THROWS() +#if defined(__cplusplus) && __cplusplus >= 201103L +enum class ScopedIntEnum { + A, B +}; + +static void ENUMS_EQUAL_INTWithScopedIntEnumTestMethod_() +{ + ENUMS_EQUAL_INT(ScopedIntEnum::B, ScopedIntEnum::B); + ENUMS_EQUAL_INT(ScopedIntEnum::B, ScopedIntEnum::A); +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, TestENUMS_EQUAL_INTWithScopedIntEnum) +{ + fixture.runTestWithMethod(ENUMS_EQUAL_INTWithScopedIntEnumTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); +} + +TEST(UnitTestMacros, ENUMS_EQUAL_INTWithScopedIntEnumBehavesAsProperMacro) +{ + if (false) ENUMS_EQUAL_INT(ScopedIntEnum::B, ScopedIntEnum::A); + else ENUMS_EQUAL_INT(ScopedIntEnum::B, ScopedIntEnum::B); +} + +IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_INTWithScopedIntEnumWorksInAnIgnoredTest) +{ + ENUMS_EQUAL_INT(ScopedIntEnum::B, ScopedIntEnum::A); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +static void ENUMS_EQUAL_INT_TEXTWithScopedIntEnumTestMethod_() +{ + ENUMS_EQUAL_INT_TEXT(ScopedIntEnum::B, ScopedIntEnum::A, "Failed because it failed"); +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, TestENUMS_EQUAL_INT_TEXTWithScopedIntEnum) +{ + fixture.runTestWithMethod(ENUMS_EQUAL_INT_TEXTWithScopedIntEnumTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); +} + +TEST(UnitTestMacros, ENUMS_EQUAL_INT_TEXTWithScopedIntEnumBehavesAsProperMacro) +{ + if (false) ENUMS_EQUAL_INT_TEXT(ScopedIntEnum::B, ScopedIntEnum::A, "Failed because it failed"); + else ENUMS_EQUAL_INT_TEXT(ScopedIntEnum::B, ScopedIntEnum::B, "Failed because it failed"); +} + +IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_EQUAL_INT_TEXTWithScopedIntEnumWorksInAnIgnoredTest) +{ + ENUMS_EQUAL_INT_TEXT(ScopedIntEnum::B, ScopedIntEnum::A, "Failed because it failed"); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +enum class ScopedLongEnum : long { + A, B +}; + +static void ENUMS_EQUAL_TYPEWithScopedLongEnumTestMethod_() +{ + ENUMS_EQUAL_TYPE(long, ScopedLongEnum::B, ScopedLongEnum::B); + ENUMS_EQUAL_TYPE(long, ScopedLongEnum::B, ScopedLongEnum::A); +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, TestENUMS_EQUAL_TYPEWithScopedLongEnum) +{ + fixture.runTestWithMethod(ENUMS_EQUAL_TYPEWithScopedLongEnumTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); +} + +TEST(UnitTestMacros, ENUMS_EQUAL_TYPEWithScopedLongEnumBehavesAsProperMacro) +{ + if (false) ENUMS_EQUAL_TYPE(long, ScopedLongEnum::B, ScopedLongEnum::A); + else ENUMS_EQUAL_TYPE(long, ScopedLongEnum::B, ScopedLongEnum::B); +} + +IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_TYPEWithScopedLongEnumWorksInAnIgnoredTest) +{ + ENUMS_EQUAL_TYPE(long, ScopedLongEnum::B, ScopedLongEnum::A); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +static void ENUMS_EQUAL_TYPE_TEXTWithScopedLongEnumTestMethod_() +{ + ENUMS_EQUAL_TYPE_TEXT(long, ScopedLongEnum::B, ScopedLongEnum::A, "Failed because it failed"); +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, TestENUMS_EQUAL_TYPE_TEXTWithScopedLongEnum) +{ + fixture.runTestWithMethod(ENUMS_EQUAL_TYPE_TEXTWithScopedLongEnumTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); +} + +TEST(UnitTestMacros, ENUMS_EQUAL_TYPE_TEXTWithScopedLongEnumBehavesAsProperMacro) +{ + if (false) ENUMS_EQUAL_TYPE_TEXT(long, ScopedLongEnum::B, ScopedLongEnum::A, "Failed because it failed"); + else ENUMS_EQUAL_TYPE_TEXT(long, ScopedLongEnum::B, ScopedLongEnum::B, "Failed because it failed"); +} + +IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_EQUAL_TYPE_TEXTWithScopedLongEnumWorksInAnIgnoredTest) +{ + ENUMS_EQUAL_TYPE_TEXT(long, ScopedLongEnum::B, ScopedLongEnum::A, "Failed because it failed"); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +#endif + +enum UnscopedEnum { + UNSCOPED_ENUM_A, UNSCOPED_ENUM_B +}; + +static void ENUMS_EQUAL_INTWithUnscopedEnumTestMethod_() +{ + ENUMS_EQUAL_INT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_B); + ENUMS_EQUAL_INT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A); +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, TestENUMS_EQUAL_INTWithUnscopedEnum) +{ + fixture.runTestWithMethod(ENUMS_EQUAL_INTWithUnscopedEnumTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); +} + +TEST(UnitTestMacros, ENUMS_EQUAL_INTWithUnscopedEnumBehavesAsProperMacro) +{ + if (false) ENUMS_EQUAL_INT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A); + else ENUMS_EQUAL_INT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_B); +} + +IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_INTWithUnscopedEnumWorksInAnIgnoredTest) +{ + ENUMS_EQUAL_INT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +static void ENUMS_EQUAL_INT_TEXTWithUnscopedEnumTestMethod_() +{ + ENUMS_EQUAL_INT_TEXT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A, "Failed because it failed"); +} // LCOV_EXCL_LINE + +TEST(UnitTestMacros, TestENUMS_EQUAL_INT_TEXTWithUnscopedEnum) +{ + fixture.runTestWithMethod(ENUMS_EQUAL_INT_TEXTWithUnscopedEnumTestMethod_); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); +} + +TEST(UnitTestMacros, ENUMS_EQUAL_INT_TEXTWithUnscopedEnumBehavesAsProperMacro) +{ + if (false) ENUMS_EQUAL_INT_TEXT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A, "Failed because it failed"); + else ENUMS_EQUAL_INT_TEXT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_B, "Failed because it failed"); +} + +IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_EQUAL_INT_TEXTWithUnscopedEnumWorksInAnIgnoredTest) +{ + ENUMS_EQUAL_INT_TEXT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A, "Failed because it failed"); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +#if CPPUTEST_HAVE_EXCEPTIONS +static void failingTestMethod_NoThrowWithCHECK_THROWS_() { CHECK_THROWS(int, (void) (1+2)); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -1025,13 +1327,13 @@ static void _failingTestMethod_NoThrowWithCHECK_THROWS() TEST(UnitTestMacros, FailureWithCHECK_THROWS_whenDoesntThrow) { - fixture.runTestWithMethod(_failingTestMethod_NoThrowWithCHECK_THROWS); + fixture.runTestWithMethod(failingTestMethod_NoThrowWithCHECK_THROWS_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected to throw int"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but threw nothing"); LONGS_EQUAL(1, fixture.getCheckCount()); } -static void _succeedingTestMethod_CorrectThrowWithCHECK_THROWS() +static void succeedingTestMethod_CorrectThrowWithCHECK_THROWS_() { CHECK_THROWS(int, throw 4); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -1039,11 +1341,11 @@ static void _succeedingTestMethod_CorrectThrowWithCHECK_THROWS() TEST(UnitTestMacros, SuccessWithCHECK_THROWS) { - fixture.runTestWithMethod(_succeedingTestMethod_CorrectThrowWithCHECK_THROWS); + fixture.runTestWithMethod(succeedingTestMethod_CorrectThrowWithCHECK_THROWS_); LONGS_EQUAL(1, fixture.getCheckCount()); } -static void _failingTestMethod_WrongThrowWithCHECK_THROWS() +static void failingTestMethod_WrongThrowWithCHECK_THROWS_() { CHECK_THROWS(int, throw 4.3); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -1051,7 +1353,7 @@ static void _failingTestMethod_WrongThrowWithCHECK_THROWS() TEST(UnitTestMacros, FailureWithCHECK_THROWS_whenWrongThrow) { - fixture.runTestWithMethod(_failingTestMethod_WrongThrowWithCHECK_THROWS); + fixture.runTestWithMethod(failingTestMethod_WrongThrowWithCHECK_THROWS_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected to throw int"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but threw a different type"); LONGS_EQUAL(1, fixture.getCheckCount()); diff --git a/tests/TestUTestStringMacro.cpp b/tests/CppUTest/TestUTestStringMacro.cpp old mode 100755 new mode 100644 similarity index 71% rename from tests/TestUTestStringMacro.cpp rename to tests/CppUTest/TestUTestStringMacro.cpp index 62ac79ddb..e51f18c67 --- a/tests/TestUTestStringMacro.cpp +++ b/tests/CppUTest/TestUTestStringMacro.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -36,128 +36,128 @@ TEST_GROUP(UnitTestStringMacros) TestTestingFixture fixture; }; -static void _STRCMP_EQUALWithActualIsNULLTestMethod() +static void STRCMP_EQUALWithActualIsNULLTestMethod_() { - STRCMP_EQUAL("ok", NULL); + STRCMP_EQUAL("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUALAndActualIsNULL) { - fixture.runTestWithMethod(_STRCMP_EQUALWithActualIsNULLTestMethod); + fixture.runTestWithMethod(STRCMP_EQUALWithActualIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>"); } -static void _STRCMP_EQUALWithExpectedIsNULLTestMethod() +static void STRCMP_EQUALWithExpectedIsNULLTestMethod_() { - STRCMP_EQUAL(NULL, "ok"); + STRCMP_EQUAL(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUALAndExpectedIsNULL) { - fixture.runTestWithMethod(_STRCMP_EQUALWithExpectedIsNULLTestMethod); + fixture.runTestWithMethod(STRCMP_EQUALWithExpectedIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>"); } -static void _STRCMP_CONTAINSWithActualIsNULLTestMethod() +static void STRCMP_CONTAINSWithActualIsNULLTestMethod_() { - STRCMP_CONTAINS("ok", NULL); + STRCMP_CONTAINS("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINSAndActualIsNULL) { - fixture.runTestWithMethod(_STRCMP_CONTAINSWithActualIsNULLTestMethod); + fixture.runTestWithMethod(STRCMP_CONTAINSWithActualIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain "); } -static void _STRCMP_CONTAINSWithExpectedIsNULLTestMethod() +static void STRCMP_CONTAINSWithExpectedIsNULLTestMethod_() { - STRCMP_CONTAINS(NULL, "ok"); + STRCMP_CONTAINS(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINSAndExpectedIsNULL) { - fixture.runTestWithMethod(_STRCMP_CONTAINSWithExpectedIsNULLTestMethod); + fixture.runTestWithMethod(STRCMP_CONTAINSWithExpectedIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <>"); } -static void _STRNCMP_EQUALWithActualIsNULLTestMethod() +static void STRNCMP_EQUALWithActualIsNULLTestMethod_() { - STRNCMP_EQUAL("ok", NULL, 2); + STRNCMP_EQUAL("ok", NULLPTR, 2); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUALAndActualIsNULL) { - fixture.runTestWithMethod(_STRNCMP_EQUALWithActualIsNULLTestMethod); + fixture.runTestWithMethod(STRNCMP_EQUALWithActualIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>"); } -static void _STRNCMP_EQUALWithExpectedIsNULLTestMethod() +static void STRNCMP_EQUALWithExpectedIsNULLTestMethod_() { - STRNCMP_EQUAL(NULL, "ok", 2); + STRNCMP_EQUAL(NULLPTR, "ok", 2); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUALAndExpectedIsNULL) { - fixture.runTestWithMethod(_STRNCMP_EQUALWithExpectedIsNULLTestMethod); + fixture.runTestWithMethod(STRNCMP_EQUALWithExpectedIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>"); } -static void _STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod() +static void STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod_() { - STRCMP_NOCASE_EQUAL("ok", NULL); + STRCMP_NOCASE_EQUAL("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndActualIsNULL) { - fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod); + fixture.runTestWithMethod(STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>"); } -static void _STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod() +static void STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod_() { - STRCMP_NOCASE_EQUAL(NULL, "ok"); + STRCMP_NOCASE_EQUAL(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndExpectedIsNULL) { - fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod); + fixture.runTestWithMethod(STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>"); } -static void _STRCMP_NOCASE_EQUALWithUnequalInputTestMethod() +static void STRCMP_NOCASE_EQUALWithUnequalInputTestMethod_() { STRCMP_NOCASE_EQUAL("no", "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndUnequalInput) { - fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithUnequalInputTestMethod); + fixture.runTestWithMethod(STRCMP_NOCASE_EQUALWithUnequalInputTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); } -static void _STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod() +static void STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod_() { - STRCMP_NOCASE_CONTAINS("ok", NULL); + STRCMP_NOCASE_CONTAINS("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINSAndActualIsNULL) { - fixture.runTestWithMethod(_STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod); + fixture.runTestWithMethod(STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain "); } -static void _STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod() +static void STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod_() { - STRCMP_NOCASE_CONTAINS(NULL, "ok"); + STRCMP_NOCASE_CONTAINS(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINSAndExpectedIsNULL) { - fixture.runTestWithMethod(_STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod); + fixture.runTestWithMethod(STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <>"); } -static void _failingTestMethodWithSTRCMP_EQUAL() +static void failingTestMethodWithSTRCMP_EQUAL_() { STRCMP_EQUAL("hello", "hell"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -165,23 +165,23 @@ static void _failingTestMethodWithSTRCMP_EQUAL() TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUAL) { - fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_EQUAL); + fixture.runTestWithMethod(failingTestMethodWithSTRCMP_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); } TEST(UnitTestStringMacros, STRCMP_EQUALBehavesAsProperMacro) { - if (false) STRCMP_EQUAL("1", "2") - else STRCMP_EQUAL("1", "1") + if (false) STRCMP_EQUAL("1", "2"); + else STRCMP_EQUAL("1", "1"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_EQUALWorksInAnIgnoredTest) { - STRCMP_EQUAL("Hello", "World") // LCOV_EXCL_LINE + STRCMP_EQUAL("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithSTRCMP_EQUAL_TEXT() +static void failingTestMethodWithSTRCMP_EQUAL_TEXT_() { STRCMP_EQUAL_TEXT("hello", "hell", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -189,7 +189,7 @@ static void _failingTestMethodWithSTRCMP_EQUAL_TEXT() TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUAL_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_EQUAL_TEXT); + fixture.runTestWithMethod(failingTestMethodWithSTRCMP_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); @@ -197,16 +197,16 @@ TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUAL_TEXT) TEST(UnitTestStringMacros, STRCMP_EQUAL_TEXTBehavesAsProperMacro) { - if (false) STRCMP_EQUAL_TEXT("1", "2", "Failed because it failed") - else STRCMP_EQUAL_TEXT("1", "1", "Failed because it failed") + if (false) STRCMP_EQUAL_TEXT("1", "2", "Failed because it failed"); + else STRCMP_EQUAL_TEXT("1", "1", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_EQUAL_TEXTWorksInAnIgnoredTest) { - STRCMP_EQUAL_TEXT("Hello", "World", "Failed because it failed") // LCOV_EXCL_LINE + STRCMP_EQUAL_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithSTRNCMP_EQUAL() +static void failingTestMethodWithSTRNCMP_EQUAL_() { STRNCMP_EQUAL("hello", "hallo", 5); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -214,23 +214,23 @@ static void _failingTestMethodWithSTRNCMP_EQUAL() TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUAL) { - fixture.runTestWithMethod(_failingTestMethodWithSTRNCMP_EQUAL); + fixture.runTestWithMethod(failingTestMethodWithSTRNCMP_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); } TEST(UnitTestStringMacros, STRNCMP_EQUALBehavesAsProperMacro) { - if (false) STRNCMP_EQUAL("1", "2", 1) - else STRNCMP_EQUAL("1", "1", 1) + if (false) STRNCMP_EQUAL("1", "2", 1); + else STRNCMP_EQUAL("1", "1", 1); } IGNORE_TEST(UnitTestStringMacros, STRNCMP_EQUALWorksInAnIgnoredTest) { - STRNCMP_EQUAL("Hello", "World", 3) // LCOV_EXCL_LINE + STRNCMP_EQUAL("Hello", "World", 3); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithSTRNCMP_EQUAL_TEXT() +static void failingTestMethodWithSTRNCMP_EQUAL_TEXT_() { STRNCMP_EQUAL_TEXT("hello", "hallo", 5, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -238,7 +238,7 @@ static void _failingTestMethodWithSTRNCMP_EQUAL_TEXT() TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUAL_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithSTRNCMP_EQUAL_TEXT); + fixture.runTestWithMethod(failingTestMethodWithSTRNCMP_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); @@ -246,16 +246,16 @@ TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUAL_TEXT) TEST(UnitTestStringMacros, STRNCMP_EQUAL_TEXTBehavesAsProperMacro) { - if (false) STRNCMP_EQUAL_TEXT("1", "2", 1, "Failed because it failed") - else STRNCMP_EQUAL_TEXT("1", "1", 1, "Failed because it failed") + if (false) STRNCMP_EQUAL_TEXT("1", "2", 1, "Failed because it failed"); + else STRNCMP_EQUAL_TEXT("1", "1", 1, "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRNCMP_EQUAL_TEXTWorksInAnIgnoredTest) { - STRNCMP_EQUAL_TEXT("Hello", "World", 3, "Failed because it failed") // LCOV_EXCL_LINE + STRNCMP_EQUAL_TEXT("Hello", "World", 3, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithSTRCMP_NOCASE_EQUAL() +static void failingTestMethodWithSTRCMP_NOCASE_EQUAL_() { STRCMP_NOCASE_EQUAL("hello", "Hell"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -263,23 +263,23 @@ static void _failingTestMethodWithSTRCMP_NOCASE_EQUAL() TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUAL) { - fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_EQUAL); + fixture.runTestWithMethod(failingTestMethodWithSTRCMP_NOCASE_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); } TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUALBehavesAsProperMacro) { - if (false) STRCMP_NOCASE_EQUAL("1", "2") - else STRCMP_NOCASE_EQUAL("1", "1") + if (false) STRCMP_NOCASE_EQUAL("1", "2"); + else STRCMP_NOCASE_EQUAL("1", "1"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUALWorksInAnIgnoredTest) { - STRCMP_NOCASE_EQUAL("Hello", "World") // LCOV_EXCL_LINE + STRCMP_NOCASE_EQUAL("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT() +static void failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT_() { STRCMP_NOCASE_EQUAL_TEXT("hello", "hell", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -287,7 +287,7 @@ static void _failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT() TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUAL_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT); + fixture.runTestWithMethod(failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); @@ -295,16 +295,16 @@ TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUAL_TEXT) TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUAL_TEXTBehavesAsProperMacro) { - if (false) STRCMP_NOCASE_EQUAL_TEXT("1", "2", "Failed because it failed") - else STRCMP_NOCASE_EQUAL_TEXT("1", "1", "Failed because it failed") + if (false) STRCMP_NOCASE_EQUAL_TEXT("1", "2", "Failed because it failed"); + else STRCMP_NOCASE_EQUAL_TEXT("1", "1", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUAL_TEXTWorksInAnIgnoredTest) { - STRCMP_NOCASE_EQUAL_TEXT("Hello", "World", "Failed because it failed") // LCOV_EXCL_LINE + STRCMP_NOCASE_EQUAL_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithSTRCMP_CONTAINS() +static void failingTestMethodWithSTRCMP_CONTAINS_() { STRCMP_CONTAINS("hello", "world"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -312,23 +312,23 @@ static void _failingTestMethodWithSTRCMP_CONTAINS() TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINS) { - fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_CONTAINS); + fixture.runTestWithMethod(failingTestMethodWithSTRCMP_CONTAINS_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain "); } TEST(UnitTestStringMacros, STRCMP_CONTAINSBehavesAsProperMacro) { - if (false) STRCMP_CONTAINS("1", "2") - else STRCMP_CONTAINS("1", "1") + if (false) STRCMP_CONTAINS("1", "2"); + else STRCMP_CONTAINS("1", "1"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_CONTAINSWorksInAnIgnoredTest) { - STRCMP_CONTAINS("Hello", "World") // LCOV_EXCL_LINE + STRCMP_CONTAINS("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithSTRCMP_CONTAINS_TEXT() +static void failingTestMethodWithSTRCMP_CONTAINS_TEXT_() { STRCMP_CONTAINS_TEXT("hello", "world", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -336,7 +336,7 @@ static void _failingTestMethodWithSTRCMP_CONTAINS_TEXT() TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINS_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_CONTAINS_TEXT); + fixture.runTestWithMethod(failingTestMethodWithSTRCMP_CONTAINS_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); @@ -344,16 +344,16 @@ TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINS_TEXT) TEST(UnitTestStringMacros, STRCMP_CONTAINS_TEXTBehavesAsProperMacro) { - if (false) STRCMP_CONTAINS_TEXT("1", "2", "Failed because it failed") - else STRCMP_CONTAINS_TEXT("1", "1", "Failed because it failed") + if (false) STRCMP_CONTAINS_TEXT("1", "2", "Failed because it failed"); + else STRCMP_CONTAINS_TEXT("1", "1", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_CONTAINS_TEXTWorksInAnIgnoredTest) { - STRCMP_CONTAINS_TEXT("Hello", "World", "Failed because it failed") // LCOV_EXCL_LINE + STRCMP_CONTAINS_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithSTRCMP_NOCASE_CONTAINS() +static void failingTestMethodWithSTRCMP_NOCASE_CONTAINS_() { STRCMP_NOCASE_CONTAINS("hello", "WORLD"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -361,23 +361,23 @@ static void _failingTestMethodWithSTRCMP_NOCASE_CONTAINS() TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINS) { - fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_CONTAINS); + fixture.runTestWithMethod(failingTestMethodWithSTRCMP_NOCASE_CONTAINS_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain "); } TEST(UnitTestStringMacros, STRCMP_NOCASE_CONTAINSBehavesAsProperMacro) { - if (false) STRCMP_NOCASE_CONTAINS("never", "executed") - else STRCMP_NOCASE_CONTAINS("hello", "HELLO WORLD") + if (false) STRCMP_NOCASE_CONTAINS("never", "executed"); + else STRCMP_NOCASE_CONTAINS("hello", "HELLO WORLD"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NO_CASE_CONTAINSWorksInAnIgnoredTest) { - STRCMP_NOCASE_CONTAINS("Hello", "World") // LCOV_EXCL_LINE + STRCMP_NOCASE_CONTAINS("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE -static void _failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT() +static void failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT_() { STRCMP_NOCASE_CONTAINS_TEXT("hello", "WORLD", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -385,7 +385,7 @@ static void _failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT() TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINS_TEXT) { - fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT); + fixture.runTestWithMethod(failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); @@ -393,13 +393,13 @@ TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINS_TEXT) TEST(UnitTestStringMacros, STRCMP_NOCASE_CONTAINS_TEXTBehavesAsProperMacro) { - if (false) STRCMP_NOCASE_CONTAINS_TEXT("never", "executed", "Failed because it failed") - else STRCMP_NOCASE_CONTAINS_TEXT("hello", "HELLO WORLD", "Failed because it failed") + if (false) STRCMP_NOCASE_CONTAINS_TEXT("never", "executed", "Failed because it failed"); + else STRCMP_NOCASE_CONTAINS_TEXT("hello", "HELLO WORLD", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NO_CASE_CONTAINS_TEXTWorksInAnIgnoredTest) { - STRCMP_NOCASE_CONTAINS_TEXT("Hello", "World", "Failed because it failed") // LCOV_EXCL_LINE + STRCMP_NOCASE_CONTAINS_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, NFirstCharsComparison) @@ -410,7 +410,7 @@ TEST(UnitTestStringMacros, NFirstCharsComparison) STRNCMP_EQUAL("Hello World!", "Hello", 5); } -static void _compareNFirstCharsWithUpperAndLowercase() +static void compareNFirstCharsWithUpperAndLowercase_() { STRNCMP_EQUAL("hello world!", "HELLO WORLD!", 12); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -418,13 +418,13 @@ static void _compareNFirstCharsWithUpperAndLowercase() TEST(UnitTestStringMacros, CompareNFirstCharsWithUpperAndLowercase) { - fixture.runTestWithMethod(_compareNFirstCharsWithUpperAndLowercase); + fixture.runTestWithMethod(compareNFirstCharsWithUpperAndLowercase_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 0"); } -static void _compareNFirstCharsWithDifferenceInTheMiddle() +static void compareNFirstCharsWithDifferenceInTheMiddle_() { STRNCMP_EQUAL("Hello World!", "Hello Peter!", 12); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -432,13 +432,13 @@ static void _compareNFirstCharsWithDifferenceInTheMiddle() TEST(UnitTestStringMacros, CompareNFirstCharsWithDifferenceInTheMiddle) { - fixture.runTestWithMethod(_compareNFirstCharsWithDifferenceInTheMiddle); + fixture.runTestWithMethod(compareNFirstCharsWithDifferenceInTheMiddle_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 6"); } -static void _compareNFirstCharsWithEmptyString() +static void compareNFirstCharsWithEmptyString_() { STRNCMP_EQUAL("", "Not empty string", 5); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -446,13 +446,13 @@ static void _compareNFirstCharsWithEmptyString() TEST(UnitTestStringMacros, CompareNFirstCharsWithEmptyString) { - fixture.runTestWithMethod(_compareNFirstCharsWithEmptyString); + fixture.runTestWithMethod(compareNFirstCharsWithEmptyString_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 0"); } -static void _compareNFirstCharsWithLastCharDifferent() +static void compareNFirstCharsWithLastCharDifferent_() { STRNCMP_EQUAL("Not empty string?", "Not empty string!", 17); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE @@ -460,9 +460,8 @@ static void _compareNFirstCharsWithLastCharDifferent() TEST(UnitTestStringMacros, CompareNFirstCharsWithLastCharDifferent) { - fixture.runTestWithMethod(_compareNFirstCharsWithLastCharDifferent); + fixture.runTestWithMethod(compareNFirstCharsWithLastCharDifferent_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was "); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 16"); } - diff --git a/tests/UtestPlatformTest.cpp b/tests/CppUTest/UtestPlatformTest.cpp similarity index 51% rename from tests/UtestPlatformTest.cpp rename to tests/CppUTest/UtestPlatformTest.cpp index cf8bbd469..4faf52695 100644 --- a/tests/UtestPlatformTest.cpp +++ b/tests/CppUTest/UtestPlatformTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -29,6 +29,10 @@ #include "CppUTest/TestHarness.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTest/PlatformSpecificFunctions.h" +#include "CppUTest/StandardCLibrary.h" +#include "CppUTest/TestMemoryAllocator.h" + +#if CPPUTEST_USE_STD_C_LIB // This will cause a crash in VS2010 due to PlatformSpecificFree being uninitialized static const SimpleString str1("abc"); @@ -40,36 +44,47 @@ TEST_GROUP(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess) TestTestingFixture fixture; }; -#ifndef CPPUTEST_HAVE_FORK +// There is a possibility that a compiler provides fork but not waitpid. +#if !defined(CPPUTEST_HAVE_FORK) || !defined(CPPUTEST_HAVE_WAITPID) || !defined(CPPUTEST_HAVE_KILL) TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, DummyFailsWithMessage) { - fixture.registry_->setRunTestsInSeperateProcess(); + fixture.setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("-p doesn't work on this platform, as it is lacking fork.\b"); } #else -static void _failFunction() +static void failFunction_() { FAIL("This test fails"); } +CPPUTEST_NORETURN static void exitNonZeroFunction_(); +static void exitNonZeroFunction_() +{ + /* destructor of static objects will be called. If StringCache was there then the allocator will report invalid deallocations of static SimpleString */ + SimpleString::setStringAllocator(SimpleString::getStringAllocator()->actualAllocator()); + exit(1); +} + #include +static int waitpid_while_debugging_stub_number_called = 0; +static int waitpid_while_debugging_stub_forced_failures = 0; + extern "C" { - static int (*original_waitpid)(int, int*, int) = NULL; + static int (*original_waitpid)(int, int*, int) = NULLPTR; static int fork_failed_stub(void) { return -1; } static int waitpid_while_debugging_stub(int pid, int* status, int options) { - static int number_called = 0; static int saved_status; - if (number_called++ < 10) { + if (waitpid_while_debugging_stub_number_called++ < waitpid_while_debugging_stub_forced_failures) { saved_status = *status; errno=EINTR; return -1; @@ -83,66 +98,114 @@ extern "C" { static int waitpid_failed_stub(int, int*, int) { return -1; } } -static int _accessViolationTestFunction() -{ - return *(volatile int*) 0; -} - #include #include -static void _stoppedTestFunction() +static void stoppedTestFunction_() { kill(getpid(), SIGSTOP); } +TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, TestInSeparateProcessWorks) +{ + fixture.setRunTestsInSeperateProcess(); + fixture.runAllTests(); + fixture.assertPrintContains("OK (1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out"); +} + TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, FailureInSeparateProcessWorks) { - fixture.registry_->setRunTestsInSeperateProcess(); - fixture.setTestFunction(_failFunction); + fixture.setRunTestsInSeperateProcess(); + fixture.setTestFunction(failFunction_); fixture.runAllTests(); fixture.assertPrintContains("Failed in separate process"); + fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out"); +} + +#if (! CPPUTEST_SANITIZE_ADDRESS) + +static int accessViolationTestFunction_() +{ + return *(volatile int*) NULLPTR; // NOLINT(clang-analyzer-core.NullDereference) } TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, AccessViolationInSeparateProcessWorks) { - fixture.registry_->setRunTestsInSeperateProcess(); - fixture.setTestFunction((void(*)())_accessViolationTestFunction); + fixture.setRunTestsInSeperateProcess(); + fixture.setTestFunction((void(*)())accessViolationTestFunction_); fixture.runAllTests(); fixture.assertPrintContains("Failed in separate process - killed by signal 11"); + fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran"); } +#endif + TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, StoppedInSeparateProcessWorks) { - fixture.registry_->setRunTestsInSeperateProcess(); - fixture.setTestFunction(_stoppedTestFunction); + fixture.setRunTestsInSeperateProcess(); + fixture.setTestFunction(stoppedTestFunction_); fixture.runAllTests(); fixture.assertPrintContains("Stopped in separate process - continuing"); + fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran"); } TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, CallToForkFailedInSeparateProcessWorks) { UT_PTR_SET(PlatformSpecificFork, fork_failed_stub); - fixture.registry_->setRunTestsInSeperateProcess(); + fixture.setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("Call to fork() failed"); + fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran"); } TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, CallToWaitPidWhileDebuggingInSeparateProcessWorks) { UT_PTR_SET(original_waitpid, PlatformSpecificWaitPid); UT_PTR_SET(PlatformSpecificWaitPid, waitpid_while_debugging_stub); - fixture.registry_->setRunTestsInSeperateProcess(); + waitpid_while_debugging_stub_number_called = 0; + waitpid_while_debugging_stub_forced_failures = 10; + fixture.setRunTestsInSeperateProcess(); fixture.runAllTests(); - fixture.assertPrintContains("OK (1 tests, 0 ran, 0 checks, 0 ignored, 0 filtered out"); + fixture.assertPrintContains("OK (1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out"); + // extra check to confirm that waitpid() was polled until it passed (and passed call adds one) + CHECK(waitpid_while_debugging_stub_number_called > waitpid_while_debugging_stub_forced_failures); } +TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, CallToWaitPidStopsAndReportsAnErrorAfter20TimesRetry) +{ + UT_PTR_SET(original_waitpid, PlatformSpecificWaitPid); + UT_PTR_SET(PlatformSpecificWaitPid, waitpid_while_debugging_stub); + waitpid_while_debugging_stub_number_called = 0; + waitpid_while_debugging_stub_forced_failures = 40; + fixture.setRunTestsInSeperateProcess(); + fixture.runAllTests(); + fixture.assertPrintContains("Call to waitpid() failed with EINTR. Tried 30 times and giving up! Sometimes happens in debugger"); + // extra check to confirm that waitpid() was polled until it passed (and passed call adds one) + CHECK(waitpid_while_debugging_stub_number_called > 30); +} + + TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, CallToWaitPidFailedInSeparateProcessWorks) { UT_PTR_SET(PlatformSpecificWaitPid, waitpid_failed_stub); - fixture.registry_->setRunTestsInSeperateProcess(); + fixture.setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("Call to waitpid() failed"); + fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran"); } +TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, MultipleTestsInSeparateProcessAreCountedProperly) +{ + fixture.setRunTestsInSeperateProcess(); + fixture.runTestWithMethod(NULLPTR); + fixture.runTestWithMethod(stoppedTestFunction_); + fixture.runTestWithMethod(NULLPTR); + fixture.runTestWithMethod(exitNonZeroFunction_); + fixture.runTestWithMethod(NULLPTR); + fixture.assertPrintContains("Failed in separate process"); + fixture.assertPrintContains("Stopped in separate process"); + fixture.assertPrintContains("Errors (2 failures, 5 tests, 5 ran, 0 checks, 0 ignored, 0 filtered out"); +} + +#endif #endif diff --git a/tests/CppUTest/UtestTest.cpp b/tests/CppUTest/UtestTest.cpp new file mode 100644 index 000000000..b1e2fb421 --- /dev/null +++ b/tests/CppUTest/UtestTest.cpp @@ -0,0 +1,675 @@ +/* + * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "CppUTest/TestHarness.h" +#include "CppUTest/TestOutput.h" +#include "CppUTest/TestTestingFixture.h" +#include "CppUTest/PlatformSpecificFunctions.h" + +#if CPPUTEST_USE_STD_C_LIB +#include +#endif + +TEST_GROUP(UtestShell) +{ + TestTestingFixture fixture; +}; + +static void failMethod_() +{ + FAIL("This test fails"); +} + +static void passingTestMethod_() +{ + CHECK(true); +} + +static void passingCheckEqualTestMethod_() +{ + CHECK_EQUAL(1, 1); +} + +static void exitTestMethod_() +{ + TEST_EXIT; + FAIL("Should not get here"); +} + +TEST(UtestShell, compareDoubles) +{ + CHECK(doubles_equal(1.0, 1.001, 0.01)); + CHECK(!doubles_equal(1.0, 1.1, 0.05)); + double a = 1.2345678; + CHECK(doubles_equal(a, a, 0.000000001)); +} + +#ifdef NAN +TEST(UtestShell, compareDoublesNaN) +{ + CHECK(!doubles_equal((double)NAN, 1.001, 0.01)); + CHECK(!doubles_equal(1.0, (double)NAN, 0.01)); + CHECK(!doubles_equal(1.0, 1.001, (double)NAN)); +} +#endif + +#ifdef INFINITY +TEST(UtestShell, compareDoublesInf) +{ + CHECK(!doubles_equal((double)INFINITY, 1.0, 0.01)); + CHECK(!doubles_equal(1.0, (double)INFINITY, 0.01)); + CHECK(doubles_equal(1.0, -1.0, (double)INFINITY)); + CHECK(doubles_equal((double)INFINITY, (double)INFINITY, 0.01)); + CHECK(doubles_equal((double)INFINITY, (double)INFINITY, (double)INFINITY)); +} +#endif + +TEST(UtestShell, FailWillIncreaseTheAmountOfChecks) +{ + fixture.setTestFunction(failMethod_); + fixture.runAllTests(); + LONGS_EQUAL(1, fixture.getCheckCount()); +} + +TEST(UtestShell, PassedCheckEqualWillIncreaseTheAmountOfChecks) +{ + fixture.setTestFunction(passingCheckEqualTestMethod_); + fixture.runAllTests(); + LONGS_EQUAL(1, fixture.getCheckCount()); +} + +IGNORE_TEST(UtestShell, IgnoreTestAccessingFixture) +{ + CHECK(&fixture != NULLPTR); +} + +TEST(UtestShell, MacrosUsedInSetup) +{ + IGNORE_ALL_LEAKS_IN_TEST(); + fixture.setSetup(failMethod_); + fixture.setTestFunction(passingTestMethod_); + fixture.runAllTests(); + LONGS_EQUAL(1, fixture.getFailureCount()); +} + +TEST(UtestShell, MacrosUsedInTearDown) +{ + IGNORE_ALL_LEAKS_IN_TEST(); + fixture.setTeardown(failMethod_); + fixture.setTestFunction(passingTestMethod_); + fixture.runAllTests(); + LONGS_EQUAL(1, fixture.getFailureCount()); +} + +TEST(UtestShell, ExitLeavesQuietly) +{ + fixture.setTestFunction(exitTestMethod_); + fixture.runAllTests(); + LONGS_EQUAL(0, fixture.getFailureCount()); +} + +static bool cpputestHasCrashed; + +static void crashMethod() +{ + cpputestHasCrashed = true; +} + +TEST(UtestShell, FailWillNotCrashIfNotEnabled) +{ + cpputestHasCrashed = false; + UtestShell::setCrashMethod(crashMethod); + + fixture.setTestFunction(failMethod_); + fixture.runAllTests(); + + CHECK_FALSE(cpputestHasCrashed); + LONGS_EQUAL(1, fixture.getFailureCount()); + + UtestShell::resetCrashMethod(); +} + +TEST(UtestShell, FailWillCrashIfEnabled) +{ + cpputestHasCrashed = false; + UtestShell::setCrashOnFail(); + UtestShell::setCrashMethod(crashMethod); + + fixture.setTestFunction(failMethod_); + fixture.runAllTests(); + + CHECK(cpputestHasCrashed); + + UtestShell::restoreDefaultTestTerminator(); + UtestShell::resetCrashMethod(); +} + + + +static int teardownCalled = 0; + +static void teardownMethod_() +{ + teardownCalled++; +} + +TEST(UtestShell, TeardownCalledAfterTestFailure) +{ + teardownCalled = 0; + IGNORE_ALL_LEAKS_IN_TEST(); + fixture.setTeardown(teardownMethod_); + fixture.setTestFunction(failMethod_); + fixture.runAllTests(); + LONGS_EQUAL(1, fixture.getFailureCount()); + LONGS_EQUAL(1, teardownCalled); +} + +static int stopAfterFailure = 0; +static void stopAfterFailureMethod_() +{ + FAIL("fail"); + stopAfterFailure++; +} + +TEST(UtestShell, TestStopsAfterTestFailure) +{ + IGNORE_ALL_LEAKS_IN_TEST(); + stopAfterFailure = 0; + fixture.setTestFunction(stopAfterFailureMethod_); + fixture.runAllTests(); + CHECK(fixture.hasTestFailed()); + LONGS_EQUAL(1, fixture.getFailureCount()); + LONGS_EQUAL(0, stopAfterFailure); +} + +TEST(UtestShell, TestStopsAfterSetupFailure) +{ + stopAfterFailure = 0; + fixture.setSetup(stopAfterFailureMethod_); + fixture.setTeardown(stopAfterFailureMethod_); + fixture.setTestFunction(failMethod_); + fixture.runAllTests(); + LONGS_EQUAL(2, fixture.getFailureCount()); + LONGS_EQUAL(0, stopAfterFailure); +} + +#if CPPUTEST_HAVE_EXCEPTIONS + +// Prevents -Wunreachable-code; should always be 'true' +static bool shouldThrowException = true; + +static void thrownUnknownExceptionMethod_() +{ + if (shouldThrowException) + { + throw 33; + } + stopAfterFailure++; +} + +TEST(UtestShell, TestStopsAfterUnknownExceptionIsThrown) +{ + bool initialRethrowExceptions = UtestShell::isRethrowingExceptions(); + UtestShell::setRethrowExceptions(false); + stopAfterFailure = 0; + shouldThrowException = true; + fixture.setTestFunction(thrownUnknownExceptionMethod_); + fixture.runAllTests(); + LONGS_EQUAL(1, fixture.getFailureCount()); + fixture.assertPrintContains("Unexpected exception of unknown type was thrown"); + LONGS_EQUAL(0, stopAfterFailure); + UtestShell::setRethrowExceptions(initialRethrowExceptions); +} + +TEST(UtestShell, NoExceptionIsRethrownIfEnabledButNotThrown) +{ + bool initialRethrowExceptions = UtestShell::isRethrowingExceptions(); + bool exceptionRethrown = false; + stopAfterFailure = 0; + UtestShell::setRethrowExceptions(true); + shouldThrowException = false; + fixture.setTestFunction(thrownUnknownExceptionMethod_); + try + { + fixture.runAllTests(); + } + catch(...) + { + exceptionRethrown = true; + } + CHECK_FALSE(exceptionRethrown); + LONGS_EQUAL(0, fixture.getFailureCount()); + LONGS_EQUAL(1, stopAfterFailure); + UtestShell::setRethrowExceptions(initialRethrowExceptions); +} + +TEST(UtestShell, UnknownExceptionIsRethrownIfEnabled) +{ + bool initialRethrowExceptions = UtestShell::isRethrowingExceptions(); + bool exceptionRethrown = false; + stopAfterFailure = 0; + UtestShell::setRethrowExceptions(true); + shouldThrowException = true; + fixture.setTestFunction(thrownUnknownExceptionMethod_); + try + { + fixture.runAllTests(); + stopAfterFailure++; + } + catch(...) + { + exceptionRethrown = true; + } + CHECK_TRUE(exceptionRethrown); + LONGS_EQUAL(1, fixture.getFailureCount()); + fixture.assertPrintContains("Unexpected exception of unknown type was thrown"); + LONGS_EQUAL(0, stopAfterFailure); + UtestShell::setRethrowExceptions(initialRethrowExceptions); +} + +#if CPPUTEST_USE_STD_CPP_LIB +static void thrownStandardExceptionMethod_() +{ + if (shouldThrowException) + { + throw std::runtime_error("exception text"); + } + stopAfterFailure++; +} + +TEST(UtestShell, TestStopsAfterStandardExceptionIsThrown) +{ + bool initialRethrowExceptions = UtestShell::isRethrowingExceptions(); + UtestShell::setRethrowExceptions(false); + stopAfterFailure = 0; + shouldThrowException = true; + fixture.setTestFunction(thrownStandardExceptionMethod_); + fixture.runAllTests(); + LONGS_EQUAL(1, fixture.getFailureCount()); +#if CPPUTEST_HAVE_RTTI + fixture.assertPrintContains("Unexpected exception of type '"); + fixture.assertPrintContains("runtime_error"); + fixture.assertPrintContains("' was thrown: exception text"); +#else + fixture.assertPrintContains("Unexpected exception of unknown type was thrown"); +#endif + LONGS_EQUAL(0, stopAfterFailure); + UtestShell::setRethrowExceptions(initialRethrowExceptions); +} + +TEST(UtestShell, StandardExceptionIsRethrownIfEnabled) +{ + bool initialRethrowExceptions = UtestShell::isRethrowingExceptions(); + bool exceptionRethrown = false; + stopAfterFailure = 0; + UtestShell::setRethrowExceptions(true); + shouldThrowException = true; + fixture.setTestFunction(thrownStandardExceptionMethod_); + try + { + fixture.runAllTests(); + stopAfterFailure++; + } + catch(const std::exception &) + { + exceptionRethrown = true; + } + CHECK_TRUE(exceptionRethrown); + LONGS_EQUAL(1, fixture.getFailureCount()); + fixture.assertPrintContains("Unexpected exception of type '"); + fixture.assertPrintContains("runtime_error"); + fixture.assertPrintContains("' was thrown: exception text"); + LONGS_EQUAL(0, stopAfterFailure); + UtestShell::setRethrowExceptions(initialRethrowExceptions); +} +#endif // CPPUTEST_USE_STD_CPP_LIB +#endif // CPPUTEST_HAVE_EXCEPTIONS + +TEST(UtestShell, veryVebose) +{ + UtestShell shell("Group", "name", __FILE__, __LINE__); + StringBufferTestOutput normalOutput; + normalOutput.verbose(TestOutput::level_veryVerbose); + NullTestPlugin plugin; + + TestResult result(normalOutput); + shell.runOneTestInCurrentProcess(&plugin, result); + STRCMP_CONTAINS("\n------ before runTest", normalOutput.getOutput().asCharString()); +} + +class defaultUtestShell: public UtestShell +{ +}; + +TEST(UtestShell, this_test_covers_the_UtestShell_createTest_and_Utest_testBody_methods) +{ + defaultUtestShell shell; + fixture.addTest(&shell); + fixture.runAllTests(); + LONGS_EQUAL(2, fixture.getTestCount()); +} + + +static void StubPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result) +{ + result->addFailure(TestFailure(shell, "Failed in separate process")); +} + +TEST(UtestShell, RunInSeparateProcessTest) +{ + UT_PTR_SET(PlatformSpecificRunTestInASeperateProcess, StubPlatformSpecificRunTestInASeperateProcess); + fixture.getRegistry()->setRunTestsInSeperateProcess(); + fixture.runAllTests(); + fixture.assertPrintContains("Failed in separate process"); +} + +// There is a possibility that a compiler provides fork but not waitpid. +#if !defined(CPPUTEST_HAVE_FORK) || !defined(CPPUTEST_HAVE_WAITPID) || !defined(CPPUTEST_HAVE_KILL) + +IGNORE_TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) {} + +#else + +TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) +{ + fixture.setTestFunction(UtestShell::crash); + fixture.setRunTestsInSeperateProcess(); + fixture.runAllTests(); + fixture.assertPrintContains("Failed in separate process - killed by signal"); +} + +#endif + +#if CPPUTEST_HAVE_EXCEPTIONS + +static bool destructorWasCalledOnFailedTest = false; + +static void destructorCalledForLocalObjects_() +{ + SetBooleanOnDestructorCall pleaseCallTheDestructor(destructorWasCalledOnFailedTest); + destructorWasCalledOnFailedTest = false; + FAIL("fail"); +} + +TEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails) +{ + fixture.setTestFunction(destructorCalledForLocalObjects_); + fixture.runAllTests(); + CHECK(destructorWasCalledOnFailedTest); +} + +#endif + +TEST_GROUP(IgnoredUtestShell) +{ + TestTestingFixture fixture; + IgnoredUtestShell ignoredTest; + ExecFunctionTestShell normalUtestShell; + + void setup() CPPUTEST_OVERRIDE + { + fixture.addTest(&ignoredTest); + fixture.addTest(&normalUtestShell); + } +}; + +TEST(IgnoredUtestShell, doesIgnoreCount) +{ + fixture.runAllTests(); + LONGS_EQUAL(1, fixture.getIgnoreCount()); +} + +TEST(IgnoredUtestShell, printsIGNORE_TESTwhenVerbose) +{ + fixture.setOutputVerbose(); + fixture.runAllTests(); + fixture.assertPrintContains("IGNORE_TEST"); +} + +TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenIncreaseRunCount) +{ + ignoredTest.setRunIgnored(); + fixture.runAllTests(); + LONGS_EQUAL(3, fixture.getRunCount()); + LONGS_EQUAL(0, fixture.getIgnoreCount()); +} + +TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenIncreaseIgnoredCount) +{ + fixture.runAllTests(); + LONGS_EQUAL(2, fixture.getRunCount()); + LONGS_EQUAL(1, fixture.getIgnoreCount()); +} + +TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedWillNotInfluenceNormalTestCount) +{ + normalUtestShell.setRunIgnored(); + fixture.runAllTests(); + LONGS_EQUAL(2, fixture.getRunCount()); + LONGS_EQUAL(1, fixture.getIgnoreCount()); +} + +TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenReturnTESTInFormattedName) +{ + ignoredTest.setGroupName("TestGroup"); + ignoredTest.setTestName("TestName"); + ignoredTest.setRunIgnored(); + fixture.runAllTests(); + STRCMP_EQUAL("TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString()); +} + +TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenReturnIGNORETESTInFormattedName) +{ + ignoredTest.setGroupName("TestGroup"); + ignoredTest.setTestName("TestName"); + fixture.runAllTests(); + STRCMP_EQUAL("IGNORE_TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString()); +} + +TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenWillRunReturnFalse) +{ + CHECK_FALSE(ignoredTest.willRun()); +} + +TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenWillRunReturnTrue) +{ + ignoredTest.setRunIgnored(); + CHECK_TRUE(ignoredTest.willRun()); +} + +TEST_BASE(MyOwnTest) +{ + MyOwnTest() : + inTest(false) + { + } + bool inTest; + + void setup() CPPUTEST_OVERRIDE + { + CHECK(!inTest); + inTest = true; + } + void teardown() CPPUTEST_OVERRIDE + { + CHECK(inTest); + inTest = false; + } +}; + +TEST_GROUP_BASE(UtestMyOwn, MyOwnTest) +{ +}; + +TEST(UtestMyOwn, test) +{ + CHECK(inTest); +} + +class NullParameterTest: public UtestShell +{ +}; + +TEST(UtestMyOwn, NullParameters) +{ + NullParameterTest nullTest; /* Bug fix tests for creating a test without a name, fix in SimpleString */ + TestFilter emptyFilter; + CHECK(nullTest.shouldRun(&emptyFilter, &emptyFilter)); +} + +class AllocateAndDeallocateInConstructorAndDestructor +{ + char* memory_; + char* morememory_; +public: + AllocateAndDeallocateInConstructorAndDestructor() + { + memory_ = new char[100]; + morememory_ = NULLPTR; + } + void allocateMoreMemory() + { + morememory_ = new char[123]; + } + + ~AllocateAndDeallocateInConstructorAndDestructor() + { + delete [] memory_; + delete [] morememory_; + } +}; + +TEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks) +{ + AllocateAndDeallocateInConstructorAndDestructor dummy; +}; + +TEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName) +{ + dummy.allocateMoreMemory(); +} + +static int getZero() +{ + return 0; +} + +static int getOne() +{ + return 1; +} + +TEST_GROUP(UtestShellPointerArrayTest) +{ + UtestShell* test0; + UtestShell* test1; + UtestShell* test2; + + void setup() CPPUTEST_OVERRIDE + { + test0 = new IgnoredUtestShell(); + test1 = new IgnoredUtestShell(); + test2 = new IgnoredUtestShell(); + + test0->addTest(test1); + test1->addTest(test2); + } + + void teardown() CPPUTEST_OVERRIDE + { + delete test0; + delete test1; + delete test2; + } +}; + + +TEST(UtestShellPointerArrayTest, empty) +{ + UtestShellPointerArray tests(NULLPTR); + tests.shuffle(0); + CHECK(NULLPTR == tests.getFirstTest()); +} + +TEST(UtestShellPointerArrayTest, testsAreInOrder) +{ + UtestShellPointerArray tests(test0); + CHECK(tests.get(0) == test0); + CHECK(tests.get(1) == test1); + CHECK(tests.get(2) == test2); +} + +TEST(UtestShellPointerArrayTest, relinkingTestsWillKeepThemTheSameWhenNothingWasDone) +{ + UtestShellPointerArray tests(test0); + tests.relinkTestsInOrder(); + CHECK(tests.get(0) == test0); + CHECK(tests.get(1) == test1); + CHECK(tests.get(2) == test2); +} + + +TEST(UtestShellPointerArrayTest, firstTestisNotTheFirstTestWithSeed1234) +{ + UtestShellPointerArray tests(test0); + tests.shuffle(1234); + CHECK(tests.getFirstTest() != test0); +} + +TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningZero) +{ + UT_PTR_SET(PlatformSpecificRand, getZero); + + UtestShellPointerArray tests(test0); + tests.shuffle(3); + CHECK(tests.get(0) == test1); + CHECK(tests.get(1) == test2); + CHECK(tests.get(2) == test0); +} + +// swaps with 4 mod 3 (1) then 4 mod 2 (0): 1, [2], [0] --> [1], [0], 2 --> 0, 1, 2 +TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningOne) +{ + UT_PTR_SET(PlatformSpecificRand, getOne); + + UtestShellPointerArray tests(test0); + tests.shuffle(3); + CHECK(tests.get(0) == test0); + CHECK(tests.get(1) == test2); + CHECK(tests.get(2) == test1); +} + +TEST(UtestShellPointerArrayTest, reverse) +{ + UT_PTR_SET(PlatformSpecificRand, getOne); + + UtestShellPointerArray tests(test0); + tests.reverse(); + CHECK(tests.get(0) == test2); + CHECK(tests.get(1) == test1); + CHECK(tests.get(2) == test0); +} diff --git a/tests/CppUTestExt/AllTests.cpp b/tests/CppUTestExt/AllTests.cpp index 5ca0bf79f..6b4ca8666 100644 --- a/tests/CppUTestExt/AllTests.cpp +++ b/tests/CppUTestExt/AllTests.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -27,6 +27,7 @@ #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/TestRegistry.h" +#include "CppUTest/SimpleStringInternalCache.h" #include "CppUTestExt/MemoryReporterPlugin.h" #include "CppUTestExt/MockSupportPlugin.h" @@ -34,28 +35,35 @@ #include "CppUTestExt/GTestConvertor.h" #endif -int main(int ac, const char** av) +int main(int ac, const char *const *av) { + int result = 0; + GlobalSimpleStringCache simpleStringCache; + + { #ifdef CPPUTEST_INCLUDE_GTEST_TESTS - GTestConvertor convertor; - convertor.addAllGTestToTestRegistry(); + GTestConvertor convertor; + convertor.addAllGTestToTestRegistry(); #endif - MemoryReporterPlugin plugin; - MockSupportPlugin mockPlugin; - TestRegistry::getCurrentRegistry()->installPlugin(&plugin); - TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin); + MemoryReporterPlugin plugin; + MockSupportPlugin mockPlugin; + TestRegistry::getCurrentRegistry()->installPlugin(&plugin); + TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin); #ifndef GMOCK_RENAME_MAIN - return CommandLineTestRunner::RunAllTests(ac, av); + result = CommandLineTestRunner::RunAllTests(ac, av); #else - /* Don't have any memory leak detector when running the Google Test tests */ + /* Don't have any memory leak detector when running the Google Test tests */ - testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity; + testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity; - ConsoleTestOutput output; - CommandLineTestRunner runner(ac, av, &output, TestRegistry::getCurrentRegistry()); - return runner.runAllTestsMain(); + ConsoleTestOutput output; + CommandLineTestRunner runner(ac, av, TestRegistry::getCurrentRegistry()); + result = runner.runAllTestsMain(); #endif + } + + return result; } diff --git a/tests/CppUTestExt/CMakeLists.txt b/tests/CppUTestExt/CMakeLists.txt index 8039a3b52..c50179852 100644 --- a/tests/CppUTestExt/CMakeLists.txt +++ b/tests/CppUTestExt/CMakeLists.txt @@ -1,39 +1,139 @@ -set(CppUTestExtTests_src +add_library(CppUTestExtTests_main OBJECT AllTests.cpp - CodeMemoryReporterTest.cpp +) + +if(CPPUTEST_STD_C_LIB_DISABLED) + target_sources(CppUTestExtTests_main + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/../DummyUTestPlatform/DummyUTestPlatform.cpp + ) +endif() + +if(CPPUTEST_TEST_GTEST) + find_package(GTest) + if(NOT GTest_FOUND) + if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.11") + include(FetchContent) + FetchContent_Declare(googletest + URL https://github.com/google/googletest/archive/release-1.8.0.zip + ) + if(NOT googletest_POPULATED) + FetchContent_Populate(googletest) + add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR}) + endif() + set(GTEST_LIBRARIES gmock gtest) + else() + # FetchContent is not supported. + message(FATAL_ERROR + "GTest not found" + ) + endif() + endif() + target_link_libraries(CppUTestExtTests_main PUBLIC ${GTEST_LIBRARIES}) + target_compile_definitions(CppUTestExtTests_main PUBLIC CPPUTEST_INCLUDE_GTEST_TESTS) +endif() + +target_link_libraries(CppUTestExtTests_main + PUBLIC + CppUTest + CppUTestExt +) + +if(NOT CPPUTEST_SPLIT_TESTS) + add_executable(CppUTestExtTests) + + add_mapfile(CppUTestExtTests) + + include(CppUTest) + cpputest_discover_tests(CppUTestExtTests + DETAILED FALSE + ) +endif() + +function(add_cpputestext_test number) + set(name CppUTestExtTests) + + if(CPPUTEST_SPLIT_TESTS) + string(APPEND name ${number}) + add_executable(${name}) + add_mapfile(${name}) + cpputest_discover_tests(${name}) + endif() + + target_sources(${name} + PRIVATE ${ARGN} + ) + target_link_libraries(${name} + PRIVATE CppUTestExtTests_main + ) +endfunction() + +add_cpputestext_test(1 + MockFailureReporterForTest.cpp + ExpectedFunctionsListTest.cpp GMockTest.cpp GTest1Test.cpp - IEEE754PluginTest.cpp - IEEE754PluginTest_c.c + GTest2ConvertorTest.cpp +) + +add_cpputestext_test(2 + MockFailureReporterForTest.cpp MemoryReportAllocatorTest.cpp - MemoryReporterPluginTest.cpp MemoryReportFormatterTest.cpp + MemoryReporterPluginTest.cpp MockActualCallTest.cpp MockCheatSheetTest.cpp - MockCallTest.cpp MockComparatorCopierTest.cpp MockExpectedCallTest.cpp - ExpectedFunctionsListTest.cpp - MockFailureReporterForTest.cpp - MockFailureTest.cpp MockHierarchyTest.cpp +) + +add_cpputestext_test(3 + MockFailureReporterForTest.cpp + CodeMemoryReporterTest.cpp + OrderedTestTest.cpp + OrderedTestTest_c.c +) + +add_cpputestext_test(4 + MockFailureReporterForTest.cpp + MockReturnValueTest.cpp MockNamedValueTest.cpp - MockParameterTest.cpp +) + +add_cpputestext_test(5 + MockFailureReporterForTest.cpp MockPluginTest.cpp - MockSupportTest.cpp - MockSupport_cTestCFile.c MockSupport_cTest.cpp - MockStrictOrderTest.cpp - MockReturnValueTest.cpp - OrderedTestTest.cpp + MockSupport_cTestCFile.c +) + +add_cpputestext_test(6 + MockFailureReporterForTest.cpp + ExpectedFunctionsListTest.cpp + MockCallTest.cpp +) + +add_cpputestext_test(7 + MockFailureReporterForTest.cpp + MockComparatorCopierTest.cpp + MockHierarchyTest.cpp + MockParameterTest.cpp ) -if (MINGW) - find_package (Threads REQUIRED) - set(THREAD_LIB "pthread") -endif (MINGW) +add_cpputestext_test(8 + MockFailureReporterForTest.cpp + IEEE754PluginTest.cpp + IEEE754PluginTest_c.c + MockComparatorCopierTest.cpp +) -add_executable(CppUTestExtTests ${CppUTestExtTests_src}) -cpputest_normalize_test_output_location(CppUTestExtTests) -target_link_libraries(CppUTestExtTests CppUTest CppUTestExt ${THREAD_LIB} ${CPPUNIT_EXTERNAL_LIBRARIES}) -cpputest_buildtime_discover_tests(CppUTestExtTests) +add_cpputestext_test(9 + MockFailureReporterForTest.cpp + MockFailureTest.cpp + MockHierarchyTest.cpp + MockPluginTest.cpp + MockReturnValueTest.cpp + MockStrictOrderTest.cpp + MockSupportTest.cpp +) diff --git a/tests/CppUTestExt/CodeMemoryReporterTest.cpp b/tests/CppUTestExt/CodeMemoryReporterTest.cpp index 41b01f33d..c2b390504 100644 --- a/tests/CppUTestExt/CodeMemoryReporterTest.cpp +++ b/tests/CppUTestExt/CodeMemoryReporterTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,8 +30,8 @@ #include "CppUTestExt/MemoryReportAllocator.h" #include "CppUTestExt/CodeMemoryReportFormatter.h" -#define TESTOUTPUT_EQUAL(a) STRCMP_EQUAL_LOCATION(a, testOutput.getOutput().asCharString(), "", __FILE__, __LINE__); -#define TESTOUTPUT_CONTAINS(a) STRCMP_CONTAINS_LOCATION(a, testOutput.getOutput().asCharString(), "", __FILE__, __LINE__); +#define TESTOUTPUT_EQUAL(a) STRCMP_EQUAL_LOCATION(a, testOutput.getOutput().asCharString(), "", __FILE__, __LINE__) +#define TESTOUTPUT_CONTAINS(a) STRCMP_CONTAINS_LOCATION(a, testOutput.getOutput().asCharString(), "", __FILE__, __LINE__) TEST_GROUP(CodeMemoryReportFormatter) { @@ -45,7 +45,7 @@ TEST_GROUP(CodeMemoryReportFormatter) TestResult* testResult; CodeMemoryReportFormatter* formatter; - void setup() + void setup() CPPUTEST_OVERRIDE { cAllocator = defaultMallocAllocator(); newAllocator = defaultNewAllocator(); @@ -57,7 +57,7 @@ TEST_GROUP(CodeMemoryReportFormatter) testResult = new TestResult(testOutput); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete testResult; delete formatter; @@ -124,7 +124,7 @@ TEST(CodeMemoryReportFormatter, NewAllocatorGeneratesDeleteCode) TEST(CodeMemoryReportFormatter, DeleteNullWorksFine) { - formatter->report_free_memory(testResult, newAllocator, NULL, "boo", 4); + formatter->report_free_memory(testResult, newAllocator, NULLPTR, "boo", 4); TESTOUTPUT_CONTAINS("delete [] NULL; /* using delete at boo:4 */"); } diff --git a/tests/CppUTestExt/ExpectedFunctionsListTest.cpp b/tests/CppUTestExt/ExpectedFunctionsListTest.cpp index 1c374bece..526db2393 100644 --- a/tests/CppUTestExt/ExpectedFunctionsListTest.cpp +++ b/tests/CppUTestExt/ExpectedFunctionsListTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -38,7 +38,7 @@ TEST_GROUP(MockExpectedCallsList) MockCheckedExpectedCall* call2; MockCheckedExpectedCall* call3; MockCheckedExpectedCall* call4; - void setup() + void setup() CPPUTEST_OVERRIDE { list = new MockExpectedCallsList; call1 = new MockCheckedExpectedCall; @@ -49,7 +49,7 @@ TEST_GROUP(MockExpectedCallsList) call2->withName("bar"); call3->withName("boo"); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete call1; delete call2; @@ -57,13 +57,14 @@ TEST_GROUP(MockExpectedCallsList) delete call4; delete list; CHECK_NO_MOCK_FAILURE(); + MockFailureReporterForTest::clearReporter(); } }; TEST(MockExpectedCallsList, emptyList) { CHECK(! list->hasUnfulfilledExpectations()); - CHECK(! list->hasFulfilledExpectations()); + CHECK(! list->hasFinalizedMatchingExpectations()); LONGS_EQUAL(0, list->size()); } @@ -74,7 +75,7 @@ TEST(MockExpectedCallsList, addingCalls) LONGS_EQUAL(2, list->size()); } -TEST(MockExpectedCallsList, listWithFulfilledExpectationHasNoUnfillfilledOnes) +TEST(MockExpectedCallsList, listWithFulfilledExpectationHasNoUnfulfilledOnes) { call1->callWasMade(1); call2->callWasMade(2); @@ -112,17 +113,15 @@ TEST(MockExpectedCallsList, deleteAllExpectationsAndClearList) list->deleteAllExpectationsAndClearList(); } -TEST(MockExpectedCallsList, onlyKeepUnfulfilledExpectations) +TEST(MockExpectedCallsList, onlyKeepUnmatchingExpectations) { call1->withName("relate"); call2->withName("unrelate"); - call3->withName("relate"); - call2->callWasMade(1); - call3->callWasMade(2); + call3->withName("relate").withParameter("param",1); list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); - list->onlyKeepUnfulfilledExpectations(); + list->onlyKeepUnmatchingExpectations(); LONGS_EQUAL(1, list->size()); } @@ -200,38 +199,42 @@ TEST(MockExpectedCallsList, onlyKeepExpectationsWithInputParameter) LONGS_EQUAL(2, list->size()); } -TEST(MockExpectedCallsList, addUnfilfilledExpectationsWithEmptyList) +TEST(MockExpectedCallsList, addPotentiallyMatchingExpectationsWithEmptyList) { MockExpectedCallsList newList; - newList.addUnfulfilledExpectations(*list); + newList.addPotentiallyMatchingExpectations(*list); LONGS_EQUAL(0, newList.size()); } -TEST(MockExpectedCallsList, addUnfilfilledExpectationsMultipleUnfulfilledExpectations) +TEST(MockExpectedCallsList, addPotentiallyMatchingExpectationsMultipleUnmatchedExpectations) { call2->callWasMade(1); list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); MockExpectedCallsList newList; - newList.addUnfulfilledExpectations(*list); + newList.addPotentiallyMatchingExpectations(*list); LONGS_EQUAL(2, newList.size()); } -TEST(MockExpectedCallsList, amountOfExpectationsFor) +TEST(MockExpectedCallsList, amountOfActualCallsFulfilledFor_HasOneRelated) { call1->withName("foo"); + call1->callWasMade(1); call2->withName("bar"); + call2->callWasMade(2); list->addExpectedCall(call1); list->addExpectedCall(call2); - LONGS_EQUAL(1, list->amountOfExpectationsFor("bar")); + LONGS_EQUAL(1, list->amountOfActualCallsFulfilledFor("bar")); } -TEST(MockExpectedCallsList, amountOfExpectationsForHasNone) +TEST(MockExpectedCallsList, amountOfActualCallsFulfilledFor_HasNone) { call1->withName("foo"); + call1->callWasMade(1); + call2->withName("bar"); list->addExpectedCall(call1); - LONGS_EQUAL(0, list->amountOfExpectationsFor("bar")); + LONGS_EQUAL(0, list->amountOfActualCallsFulfilledFor("bar")); } TEST(MockExpectedCallsList, callToStringForUnfulfilledFunctions) @@ -250,6 +253,24 @@ TEST(MockExpectedCallsList, callToStringForUnfulfilledFunctions) STRCMP_EQUAL(expectedString.asCharString(), list->unfulfilledCallsToString().asCharString()); } +TEST(MockExpectedCallsList, callsWithMissingParametersToString) +{ + call1->withName("foo").withParameter("boo", 0); + call2->withName("bar").withParameter("baa", 10).withParameter("baz", "blah"); + call2->inputParameterWasPassed("baa"); + + list->addExpectedCall(call1); + list->addExpectedCall(call2); + + SimpleString expectedString; + expectedString = StringFromFormat("-%s\n-#%s\n-%s\n-#%s", + call1->callToString().asCharString(), + call1->missingParametersToString().asCharString(), + call2->callToString().asCharString(), + call2->missingParametersToString().asCharString()); + STRCMP_EQUAL(expectedString.asCharString(), list->callsWithMissingParametersToString("-", "#").asCharString()); +} + TEST(MockExpectedCallsList, callToStringForFulfilledFunctions) { call1->withName("foo"); @@ -262,21 +283,72 @@ TEST(MockExpectedCallsList, callToStringForFulfilledFunctions) list->addExpectedCall(call2); SimpleString expectedString; - expectedString = StringFromFormat("%s\n%s", call2->callToString().asCharString(), call1->callToString().asCharString()); + expectedString = StringFromFormat("%s\n%s", call1->callToString().asCharString(), call2->callToString().asCharString()); STRCMP_EQUAL(expectedString.asCharString(), list->fulfilledCallsToString().asCharString()); } -TEST(MockExpectedCallsList, removeOneFulfilledExpectationFromEmptyList) +TEST(MockExpectedCallsList, removeOneFinalizedMatchingExpectationFromEmptyList) { - POINTERS_EQUAL(NULL, list->removeOneFulfilledExpectation()); + POINTERS_EQUAL(NULLPTR, list->removeFirstFinalizedMatchingExpectation()); } -TEST(MockExpectedCallsList, getOneFulfilledExpectationWithIgnoredParametersFromEmptyList) +TEST(MockExpectedCallsList, getOneMatchingExpectationFromEmptyList) { - POINTERS_EQUAL(NULL, list->getOneFulfilledExpectationWithIgnoredParameters()); + POINTERS_EQUAL(NULLPTR, list->getFirstMatchingExpectation()); } TEST(MockExpectedCallsList, toStringOnEmptyList) { STRCMP_EQUAL("", list->unfulfilledCallsToString().asCharString()); } + +TEST(MockExpectedCallsList, hasFinalizedMatchingExpectations_emptyList) +{ + CHECK(! list->hasFinalizedMatchingExpectations()); +} + +TEST(MockExpectedCallsList, hasFinalizedMatchingExpectations_listHasNonMatchingCalls) +{ + call1->withParameter("param", 0); + call2->withParameter("param", 0); + call3->withParameter("param", 0); + list->addExpectedCall(call1); + list->addExpectedCall(call2); + list->addExpectedCall(call3); + + CHECK(! list->hasFinalizedMatchingExpectations()); +} + +TEST(MockExpectedCallsList, hasFinalizedMatchingExpectations_listHasMatchingButNotFinalizedCall) +{ + list->addExpectedCall(call1); + list->addExpectedCall(call2); + call1->ignoreOtherParameters(); + call2->withParameter("param", 0); + + CHECK(! list->hasFinalizedMatchingExpectations()); +} + +TEST(MockExpectedCallsList, hasFinalizedMatchingExpectations_listHasFinalizedCallThatIgnoresParameters) +{ + list->addExpectedCall(call1); + list->addExpectedCall(call2); + call1->ignoreOtherParameters(); + call2->withParameter("param", 0); + + call1->finalizeActualCallMatch(); + + CHECK(list->hasFinalizedMatchingExpectations()); +} + +TEST(MockExpectedCallsList, hasFinalizedMatchingExpectations_listHasFinalizedCallThatDoesntIgnoreParameters) +{ + list->addExpectedCall(call1); + list->addExpectedCall(call2); + call1->withParameter("param", 1); + call2->withParameter("param", 0); + + call1->inputParameterWasPassed("param"); + + CHECK(list->hasFinalizedMatchingExpectations()); +} diff --git a/tests/CppUTestExt/GMockTest.cpp b/tests/CppUTestExt/GMockTest.cpp index a3698ef2d..88b00e93d 100644 --- a/tests/CppUTestExt/GMockTest.cpp +++ b/tests/CppUTestExt/GMockTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -37,12 +37,12 @@ TEST_GROUP(GMock) { TestTestingFixture *fixture; - void setup() + void setup() CPPUTEST_OVERRIDE { fixture = new TestTestingFixture; } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete fixture; @@ -90,5 +90,3 @@ TEST(GMock, GMockNiceMocksWorkFine) } #endif - - diff --git a/tests/CppUTestExt/GTest1Test.cpp b/tests/CppUTestExt/GTest1Test.cpp index ae787ba2c..8f23d3482 100644 --- a/tests/CppUTestExt/GTest1Test.cpp +++ b/tests/CppUTestExt/GTest1Test.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -73,6 +73,9 @@ static void crashMe () TEST(GTestSimpleTest, GTestDeathTest) { +#if defined(GTEST_VERSION_GTEST_1_7) + CppuTestGTestIgnoreLeaksInTest(); +#endif ASSERT_DEATH(crashMe(), "Crash me!"); } @@ -114,37 +117,37 @@ TEST(gtest, SimpleGoogleTestGetCalled) static bool afterCheck; -static void _failMethodEXPECT_EQ() +static void failMethodEXPECT_EQ_() { EXPECT_EQ(1, 2); afterCheck = true; } -static void _failMethodASSERT_EQ() +static void failMethodASSERT_EQ_() { ASSERT_EQ(1, 2); afterCheck = true; } -static void _failMethodEXPECT_TRUE() +static void failMethodEXPECT_TRUE_() { EXPECT_TRUE(false); afterCheck = true; } -static void _failMethodASSERT_TRUE() +static void failMethodASSERT_TRUE_() { ASSERT_TRUE(false); afterCheck = true; } -static void _failMethodEXPECT_FALSE() +static void failMethodEXPECT_FALSE_() { EXPECT_FALSE(true); afterCheck = true; } -static void _failMethodEXPECT_STREQ() +static void failMethodEXPECT_STREQ_() { EXPECT_STREQ("hello", "world"); afterCheck = true; @@ -153,12 +156,12 @@ static void _failMethodEXPECT_STREQ() TEST_GROUP(gtestMacros) { TestTestingFixture* fixture; - void setup() + void setup() CPPUTEST_OVERRIDE { fixture = new TestTestingFixture(); afterCheck = false; } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete fixture; } @@ -175,32 +178,32 @@ TEST_GROUP(gtestMacros) TEST(gtestMacros, EXPECT_EQFails) { - testFailureWith(_failMethodEXPECT_EQ); + testFailureWith(failMethodEXPECT_EQ_); } TEST(gtestMacros, EXPECT_TRUEFails) { - testFailureWith(_failMethodEXPECT_TRUE); + testFailureWith(failMethodEXPECT_TRUE_); } TEST(gtestMacros, EXPECT_FALSEFails) { - testFailureWith(_failMethodEXPECT_FALSE); + testFailureWith(failMethodEXPECT_FALSE_); } TEST(gtestMacros, EXPECT_STREQFails) { - testFailureWith(_failMethodEXPECT_STREQ); + testFailureWith(failMethodEXPECT_STREQ_); } TEST(gtestMacros, ASSERT_EQFails) { - testFailureWith(_failMethodASSERT_EQ); + testFailureWith(failMethodASSERT_EQ_); } TEST(gtestMacros, ASSERT_TRUEFails) { - testFailureWith(_failMethodASSERT_TRUE); + testFailureWith(failMethodASSERT_TRUE_); } #endif diff --git a/tests/CppUTestExt/GTest2ConvertorTest.cpp b/tests/CppUTestExt/GTest2ConvertorTest.cpp index f65e5ea1e..f8c390fb7 100644 --- a/tests/CppUTestExt/GTest2ConvertorTest.cpp +++ b/tests/CppUTestExt/GTest2ConvertorTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -34,13 +34,13 @@ class GTestTestingFixtureTest : public testing::Test { bool setup_was_called; char* freed_during_teardown; - void SetUp() + void SetUp() CPPUTEST_OVERRIDE { setup_was_called = true; freed_during_teardown = NULL; } - void TearDown() + void TearDown() CPPUTEST_OVERRIDE { delete [] freed_during_teardown; } diff --git a/tests/CppUTestExt/IEEE754PluginTest.cpp b/tests/CppUTestExt/IEEE754PluginTest.cpp index b9400c5a3..e37e309cb 100644 --- a/tests/CppUTestExt/IEEE754PluginTest.cpp +++ b/tests/CppUTestExt/IEEE754PluginTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -31,45 +31,42 @@ #include "CppUTest/TestTestingFixture.h" #include "CppUTestExt/IEEE754ExceptionsPlugin.h" -#if CPPUTEST_FENV_IS_WORKING_PROPERLY +#if CPPUTEST_HAVE_FENV -extern "C" -{ - #include "IEEE754PluginTest_c.h" -} +#include "IEEE754PluginTest_c.h" -TEST_GROUP(FE__with_Plugin) +TEST_GROUP(FE_with_Plugin) { TestTestingFixture fixture; IEEE754ExceptionsPlugin ieee754Plugin; - void setup(void) _override + void setup(void) CPPUTEST_OVERRIDE { - fixture.registry_->installPlugin(&ieee754Plugin); + fixture.installPlugin(&ieee754Plugin); } }; -TEST(FE__with_Plugin, should_fail____when__FE_DIVBYZERO__is_set) +TEST(FE_with_Plugin, should_fail_when_FE_DIVBYZERO_is_set) { fixture.setTestFunction(set_divisionbyzero_c); fixture.runAllTests(); fixture.assertPrintContains("IEEE754_CHECK_CLEAR(FE_DIVBYZERO) failed"); } -TEST(FE__with_Plugin, should_fail____when__FE_OVERFLOW___is_set) +TEST(FE_with_Plugin, should_fail_when_FE_OVERFLOW_is_set) { fixture.setTestFunction(set_overflow_c); fixture.runAllTests(); fixture.assertPrintContains("IEEE754_CHECK_CLEAR(FE_OVERFLOW) failed"); } -TEST(FE__with_Plugin, should_fail____when__FE_UNDERFLOW__is_set) +TEST(FE_with_Plugin, should_fail_when_FE_UNDERFLOW_is_set) { fixture.setTestFunction(set_underflow_c); fixture.runAllTests(); fixture.assertPrintContains("IEEE754_CHECK_CLEAR(FE_UNDERFLOW) failed"); } -TEST(FE__with_Plugin, should_fail____when__FE_INEXACT____is_set_and_enabled) +TEST(FE_with_Plugin, should_fail_when_FE_INEXACT_is_set_and_enabled) { IEEE754ExceptionsPlugin::enableInexact(); fixture.setTestFunction(set_inexact_c); @@ -77,7 +74,7 @@ TEST(FE__with_Plugin, should_fail____when__FE_INEXACT____is_set_and_enabled) fixture.assertPrintContains("IEEE754_CHECK_CLEAR(FE_INEXACT) failed"); } -TEST(FE__with_Plugin, should_succeed_when__FE_INEXACT____is_set_and_disabled) +TEST(FE_with_Plugin, should_succeed_when_FE_INEXACT_is_set_and_disabled) { IEEE754ExceptionsPlugin::enableInexact(); IEEE754ExceptionsPlugin::disableInexact(); @@ -86,7 +83,7 @@ TEST(FE__with_Plugin, should_succeed_when__FE_INEXACT____is_set_and_disabled) fixture.assertPrintContains("OK"); } -TEST(FE__with_Plugin, should_succeed_with_5_checks_when_no_flags_are_set) +TEST(FE_with_Plugin, should_succeed_with_5_checks_when_no_flags_are_set) { IEEE754ExceptionsPlugin::enableInexact(); fixture.setTestFunction(set_nothing_c); @@ -95,14 +92,14 @@ TEST(FE__with_Plugin, should_succeed_with_5_checks_when_no_flags_are_set) IEEE754ExceptionsPlugin::disableInexact(); } -TEST(FE__with_Plugin, should_check_five_times_when_all_flags_are_set) +TEST(FE_with_Plugin, should_check_five_times_when_all_flags_are_set) { fixture.setTestFunction(set_everything_c); fixture.runAllTests(); LONGS_EQUAL(5, fixture.getCheckCount()); } -TEST(FE__with_Plugin, should_fail_only_once_when_all_flags_are_set) +TEST(FE_with_Plugin, should_fail_only_once_when_all_flags_are_set) { fixture.setTestFunction(set_everything_c); fixture.runAllTests(); @@ -115,7 +112,7 @@ static void set_everything_but_already_failed(void) CHECK(1 == 2); } -IGNORE_TEST(FE__with_Plugin, should_not_fail_again_when_test_has_already_failed) +TEST(FE_with_Plugin, should_not_fail_again_when_test_has_already_failed) { fixture.setTestFunction(set_everything_but_already_failed); fixture.runAllTests(); @@ -131,7 +128,7 @@ static IEEE754ExceptionsPlugin ip; TEST_GROUP(IEEE754ExceptionsPlugin2) { - void setup(void) _override + void setup(void) CPPUTEST_OVERRIDE { TestRegistry::getCurrentRegistry()->installPlugin(&ip); } diff --git a/tests/CppUTestExt/IEEE754PluginTest_c.c b/tests/CppUTestExt/IEEE754PluginTest_c.c index 45cc782f2..644ea6462 100644 --- a/tests/CppUTestExt/IEEE754PluginTest_c.c +++ b/tests/CppUTestExt/IEEE754PluginTest_c.c @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -28,11 +28,12 @@ #include "IEEE754PluginTest_c.h" static volatile float f; +static volatile float zero_float = 0.0f; void set_divisionbyzero_c(void) { f = 1.0f; - f /= 0.0f; + f /= zero_float; } void set_overflow_c(void) @@ -57,7 +58,7 @@ void set_nothing_c(void) { } -void set_everything_c() +void set_everything_c(void) { set_divisionbyzero_c(); set_overflow_c(); diff --git a/tests/CppUTestExt/IEEE754PluginTest_c.h b/tests/CppUTestExt/IEEE754PluginTest_c.h index 2f65ba7a5..6f1f02e91 100644 --- a/tests/CppUTestExt/IEEE754PluginTest_c.h +++ b/tests/CppUTestExt/IEEE754PluginTest_c.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -25,9 +25,22 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#ifndef IEEE754PLUGINTEST_C_H +#define IEEE754PLUGINTEST_C_H + +#ifdef __cplusplus +extern "C" { +#endif + void set_divisionbyzero_c(void); void set_overflow_c(void); void set_underflow_c(void); void set_inexact_c(void); void set_nothing_c(void); void set_everything_c(void); + +#ifdef __cplusplus +} +#endif + +#endif /* IEEE754PLUGINTEST_C_H */ diff --git a/tests/CppUTestExt/MemoryReportAllocatorTest.cpp b/tests/CppUTestExt/MemoryReportAllocatorTest.cpp index 1df85c114..13500be4c 100644 --- a/tests/CppUTestExt/MemoryReportAllocatorTest.cpp +++ b/tests/CppUTestExt/MemoryReportAllocatorTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -32,13 +32,20 @@ TEST_GROUP(MemoryReportAllocator) { + MemoryReportAllocator allocator; }; TEST(MemoryReportAllocator, FunctionsAreForwardedForMallocAllocator) { - MemoryReportAllocator allocator; allocator.setRealAllocator(getCurrentMallocAllocator()); STRCMP_EQUAL("malloc", allocator.alloc_name()); STRCMP_EQUAL("free", allocator.free_name()); } + +TEST(MemoryReportAllocator, keepingTrackOfActualAllocator) +{ + TestMemoryAllocator* originalAllocator = getCurrentMallocAllocator(); + allocator.setRealAllocator(getCurrentMallocAllocator()); + POINTERS_EQUAL(originalAllocator->actualAllocator(), allocator.actualAllocator()); +} diff --git a/tests/CppUTestExt/MemoryReportFormatterTest.cpp b/tests/CppUTestExt/MemoryReportFormatterTest.cpp index eda0ec09f..13b0b190d 100644 --- a/tests/CppUTestExt/MemoryReportFormatterTest.cpp +++ b/tests/CppUTestExt/MemoryReportFormatterTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,7 +30,7 @@ #include "CppUTestExt/MemoryReportAllocator.h" #include "CppUTestExt/MemoryReportFormatter.h" -#define TESTOUTPUT_EQUAL(a) STRCMP_EQUAL_LOCATION(a, testOutput.getOutput().asCharString(), "", __FILE__, __LINE__); +#define TESTOUTPUT_EQUAL(a) STRCMP_EQUAL_LOCATION(a, testOutput.getOutput().asCharString(), "", __FILE__, __LINE__) TEST_GROUP(NormalMemoryReportFormatter) { @@ -40,13 +40,13 @@ TEST_GROUP(NormalMemoryReportFormatter) TestResult* testResult; NormalMemoryReportFormatter formatter; - void setup() + void setup() CPPUTEST_OVERRIDE { memory01 = (char*) 0x01; testResult = new TestResult(testOutput); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete testResult; } diff --git a/tests/CppUTestExt/MemoryReporterPluginTest.cpp b/tests/CppUTestExt/MemoryReporterPluginTest.cpp index caf185a95..2a94646d4 100644 --- a/tests/CppUTestExt/MemoryReporterPluginTest.cpp +++ b/tests/CppUTestExt/MemoryReporterPluginTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -52,37 +52,37 @@ class TemporaryDefaultNewAllocator class MockMemoryReportFormatter : public MemoryReportFormatter { public: - virtual void report_testgroup_start(TestResult* result, UtestShell& test) + virtual void report_testgroup_start(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_testgroup_start").withParameter("result", result).withParameter("test", &test); } - virtual void report_testgroup_end(TestResult* result, UtestShell& test) + virtual void report_testgroup_end(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_testgroup_end").withParameter("result", result).withParameter("test", &test); } - virtual void report_test_start(TestResult* result, UtestShell& test) + virtual void report_test_start(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_test_start").withParameter("result", result).withParameter("test", &test); } - virtual void report_test_end(TestResult* result, UtestShell& test) + virtual void report_test_end(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_test_end").withParameter("result", result).withParameter("test", &test); } - virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t, char* , const char* , int ) + virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t, char* , const char* , size_t ) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", allocator); } - virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* , const char* , int ) + virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* , const char* , size_t ) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", allocator); @@ -94,23 +94,23 @@ static MockMemoryReportFormatter formatterForPluginTest; class MemoryReporterPluginUnderTest : public MemoryReporterPlugin { public: - MemoryReportFormatter* createMemoryFormatter(const SimpleString& type) + MemoryReportFormatter* createMemoryFormatter(const SimpleString& type) CPPUTEST_OVERRIDE { - mock("reporter").actualCall("createMemoryFormatter").onObject(this).withParameter("type", type.asCharString()); - return new MockMemoryReportFormatter; + mock("reporter").actualCall("createMemoryFormatter").onObject(this).withParameter("type", type.asCharString()); + return new MockMemoryReportFormatter; } }; class TestMemoryAllocatorComparator : public MockNamedValueComparator { public: - bool isEqual(const void* object1, const void* object2) + bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { - return ((TestMemoryAllocator*)object1)->name() == ((TestMemoryAllocator*)object2)->name(); + return ((const TestMemoryAllocator*)object1)->name() == ((const TestMemoryAllocator*)object2)->name(); } - SimpleString valueToString(const void* object) + SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { - return ((TestMemoryAllocator*)object)->name(); + return ((const TestMemoryAllocator*)object)->name(); } }; @@ -124,7 +124,7 @@ TEST_GROUP(MemoryReporterPlugin) TestResult* result; UtestShell* test; - void setup() + void setup() CPPUTEST_OVERRIDE { previousNewAllocator = getCurrentNewAllocator(); result = new TestResult(output); @@ -138,8 +138,10 @@ TEST_GROUP(MemoryReporterPlugin) reporter->parseArguments(1, cmd_line, 0); mock("reporter").enable(); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { + setCurrentNewAllocator(previousNewAllocator); + mock().clear(); delete reporter; delete test; delete result; @@ -178,55 +180,55 @@ TEST(MemoryReporterPlugin, preTestActionReportsTest) TEST(MemoryReporterPlugin, postTestActionReportsTest) { - mock("formatter").expectOneCall("report_test_end").withParameter("result", result).withParameter("test", test);; - mock("formatter").expectOneCall("report_testgroup_end").withParameter("result", result).withParameter("test", test);; + mock("formatter").expectOneCall("report_test_end").withParameter("result", result).withParameter("test", test); + mock("formatter").expectOneCall("report_testgroup_end").withParameter("result", result).withParameter("test", test); reporter->postTestAction(*test, *result); } TEST(MemoryReporterPlugin, newAllocationsAreReportedTest) { - mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", defaultNewAllocator()); - mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", defaultNewAllocator()); + mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getNewAllocator()); + mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getNewAllocator()); mock("formatter").ignoreOtherCalls(); reporter->preTestAction(*test, *result); char *memory = getCurrentNewAllocator()->allocMemoryLeakNode(100); - getCurrentNewAllocator()->free_memory(memory, "unknown", 1); + getCurrentNewAllocator()->free_memory(memory, 100, "unknown", 1); } TEST(MemoryReporterPlugin, whenUsingOnlyMallocAllocatorNoOtherOfTheAllocatorsAreUsed) { mock("formatter").expectOneCall("report_test_start").withParameter("result", result).withParameter("test", test); - mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", defaultMallocAllocator()); - mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", defaultMallocAllocator()); + mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getMallocAllocator()); + mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getMallocAllocator()); mock("formatter").ignoreOtherCalls(); reporter->preTestAction(*test, *result); char *memory = getCurrentMallocAllocator()->allocMemoryLeakNode(100); - getCurrentMallocAllocator()->free_memory(memory, "unknown", 1); + getCurrentMallocAllocator()->free_memory(memory, 100, "unknown", 1); } TEST(MemoryReporterPlugin, newArrayAllocationsAreReportedTest) { - mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", defaultNewArrayAllocator()); - mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", defaultNewArrayAllocator()); + mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getNewArrayAllocator()); + mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getNewArrayAllocator()); mock("formatter").ignoreOtherCalls(); reporter->preTestAction(*test, *result); char *memory = getCurrentNewArrayAllocator()->allocMemoryLeakNode(100); - getCurrentNewArrayAllocator()->free_memory(memory, "unknown", 1); + getCurrentNewArrayAllocator()->free_memory(memory, 100, "unknown", 1); } TEST(MemoryReporterPlugin, mallocAllocationsAreReportedTest) { - mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", defaultMallocAllocator()); - mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", defaultMallocAllocator()); + mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getMallocAllocator()); + mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getMallocAllocator()); mock("formatter").ignoreOtherCalls(); reporter->preTestAction(*test, *result); char *memory = getCurrentMallocAllocator()->allocMemoryLeakNode(100); - getCurrentMallocAllocator()->free_memory(memory, "unknown", 1); + getCurrentMallocAllocator()->free_memory(memory, 100, "unknown", 1); } TEST(MemoryReporterPlugin, startOfANewTestWillReportTheTestGroupStart) @@ -255,7 +257,7 @@ class UtestForMemoryReportingPlugingTest : public UtestShell TEST(MemoryReporterPlugin, endOfaTestGroupWillReportSo) { - UtestForMemoryReportingPlugingTest fourthTest("differentGroupName", NULL); + UtestForMemoryReportingPlugingTest fourthTest("differentGroupName", NULLPTR); UtestForMemoryReportingPlugingTest thirdTest("differentGroupName", &fourthTest); UtestForMemoryReportingPlugingTest secondTest("groupname", &thirdTest); UtestForMemoryReportingPlugingTest firstTest("groupname", &secondTest); @@ -312,4 +314,3 @@ TEST(MemoryReporterPlugin, shouldntCrashCreateInvalidMemoryReportFormatterWithou realReporter.preTestAction(*test, *result); realReporter.postTestAction(*test, *result); } - diff --git a/tests/CppUTestExt/MockActualCallTest.cpp b/tests/CppUTestExt/MockActualCallTest.cpp index e221208df..a38b85200 100644 --- a/tests/CppUTestExt/MockActualCallTest.cpp +++ b/tests/CppUTestExt/MockActualCallTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -38,16 +38,19 @@ TEST_GROUP(MockCheckedActualCall) MockExpectedCallsList* list; MockFailureReporter* reporter; - void setup() + void setup() CPPUTEST_OVERRIDE { emptyList = new MockExpectedCallsList; list = new MockExpectedCallsList; reporter = MockFailureReporterForTest::getReporter(); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { CHECK_NO_MOCK_FAILURE(); + + MockFailureReporterForTest::clearReporter(); + delete emptyList; delete list; } @@ -74,10 +77,23 @@ TEST(MockCheckedActualCall, unExpectedCallWithAParameter) TEST(MockCheckedActualCall, unExpectedCallWithAnOutputParameter) { MockCheckedActualCall actualCall(1, reporter, *emptyList); - actualCall.withName("unexpected").withOutputParameter("bar", (void*)0); + actualCall.withName("unexpected").withOutputParameter("bar", NULLPTR); + + MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "unexpected", *list); + CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); +} + +TEST(MockCheckedActualCall, unExpectedCallOnObject) +{ + int object; + + MockCheckedActualCall actualCall(1, reporter, *emptyList); + actualCall.withName("unexpected").onObject(&object); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "unexpected", *list); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); + + CHECK(actualCall.hasFailed()); // Checks that onObject() doesn't "reset" call state } TEST(MockCheckedActualCall, actualCallWithNoReturnValueAndMeaninglessCallOrderForCoverage) @@ -138,7 +154,8 @@ TEST(MockCheckedActualCall, MockIgnoredActualCallWorksAsItShould) actual.withCallOrder(1); CHECK(false == actual.returnBoolValue()); - CHECK(false == actual.returnBoolValueOrDefault(true)); + CHECK(true == actual.returnBoolValueOrDefault(true)); + CHECK(false == actual.returnBoolValueOrDefault(false)); CHECK(0 == actual.returnUnsignedLongIntValue()); CHECK(0 == actual.returnIntValue()); CHECK(1ul == actual.returnUnsignedLongIntValueOrDefault(1ul)); @@ -147,15 +164,21 @@ TEST(MockCheckedActualCall, MockIgnoredActualCallWorksAsItShould) CHECK(1l == actual.returnLongIntValueOrDefault(1l)); CHECK(0 == actual.returnUnsignedIntValue()); CHECK(1u == actual.returnUnsignedIntValueOrDefault(1u)); +#if CPPUTEST_USE_LONG_LONG + CHECK(0 == actual.returnLongLongIntValue()); + CHECK(1ll == actual.returnLongLongIntValueOrDefault(1ll)); + CHECK(0 == actual.returnUnsignedLongLongIntValue()); + CHECK(1ull == actual.returnUnsignedLongLongIntValueOrDefault(1ull)); +#endif DOUBLES_EQUAL(0.0, actual.returnDoubleValue(), 0.0); DOUBLES_EQUAL(1.5, actual.returnDoubleValueOrDefault(1.5), 0.0); STRCMP_EQUAL("bla", actual.returnStringValueOrDefault("bla")); STRCMP_EQUAL("", actual.returnStringValue()); - CHECK(0 == actual.returnPointerValue()); + CHECK(NULLPTR == actual.returnPointerValue()); CHECK((void*) 0x2 == actual.returnPointerValueOrDefault((void*) 0x2)); - CHECK(0 == actual.returnConstPointerValue()); + CHECK(NULLPTR == actual.returnConstPointerValue()); CHECK((const void*) 0x2 == actual.returnConstPointerValueOrDefault((const void*) 0x2)); - CHECK(0 == actual.returnFunctionPointerValue()); + CHECK(NULLPTR == actual.returnFunctionPointerValue()); CHECK((void(*)()) 1 == actual.returnFunctionPointerValueOrDefault((void(*)()) 0x1)); CHECK_FALSE(actual.hasReturnValue()); CHECK(actual.returnValue().equals(MockNamedValue(""))); @@ -176,6 +199,10 @@ TEST(MockCheckedActualCall, remainderOfMockActualCallTraceWorksAsItShould) actual.withUnsignedIntParameter("unsigned_int", (unsigned int) 1); actual.withUnsignedLongIntParameter("unsigned_long", (unsigned long)1); actual.withLongIntParameter("long_int", (long int) 1); +#if CPPUTEST_USE_LONG_LONG + actual.withLongLongIntParameter("long_long_int", (long long int) 1); + actual.withUnsignedLongLongIntParameter("unsigned_long_long_int", (unsigned long long int) 1); +#endif actual.withPointerParameter("pointer", &value); actual.withConstPointerParameter("const_pointer", &const_value); actual.withFunctionPointerParameter("function_pointer", function_value); @@ -187,9 +214,13 @@ TEST(MockCheckedActualCall, remainderOfMockActualCallTraceWorksAsItShould) expectedString += " onObject:0x"; expectedString += HexStringFrom(&value); expectedString += " bool:true"; - expectedString += " unsigned_int: 1 (0x00000001)"; + expectedString += " unsigned_int:1 (0x1)"; expectedString += " unsigned_long:1 (0x1)"; - expectedString += " long_int:1"; + expectedString += " long_int:1 (0x1)"; +#if CPPUTEST_USE_LONG_LONG + expectedString += " long_long_int:1 (0x1)"; + expectedString += " unsigned_long_long_int:1 (0x1)"; +#endif expectedString += " pointer:0x"; expectedString += HexStringFrom(&value); expectedString += " const_pointer:0x"; @@ -212,17 +243,30 @@ TEST(MockCheckedActualCall, remainderOfMockActualCallTraceWorksAsItShould) CHECK(0 == actual.returnIntValueOrDefault(1)); CHECK(0 == actual.returnLongIntValue()); CHECK(0 == actual.returnLongIntValueOrDefault(1l)); +#if CPPUTEST_USE_LONG_LONG + CHECK(0 == actual.returnLongLongIntValue()); + CHECK(0 == actual.returnLongLongIntValueOrDefault(1ll)); + CHECK(0 == actual.returnUnsignedLongLongIntValue()); + CHECK(0 == actual.returnUnsignedLongLongIntValueOrDefault(1ull)); +#endif CHECK(0 == actual.returnUnsignedIntValue()); CHECK(0 == actual.returnUnsignedIntValueOrDefault(1u)); DOUBLES_EQUAL(0.0, actual.returnDoubleValue(), 0.0); DOUBLES_EQUAL(0.0, actual.returnDoubleValueOrDefault(1.0), 0.0); STRCMP_EQUAL("", actual.returnStringValueOrDefault("bla")); STRCMP_EQUAL("", actual.returnStringValue()); - CHECK(0 == actual.returnPointerValue()); - CHECK(0 == actual.returnPointerValueOrDefault((void*) 0x0)); - CHECK(0 == actual.returnConstPointerValue()); - CHECK(0 == actual.returnConstPointerValueOrDefault((const void*) 0x0)); - CHECK(0 == actual.returnFunctionPointerValue()); - CHECK(0 == actual.returnFunctionPointerValueOrDefault((void (*)()) 0x0)); + CHECK(NULLPTR == actual.returnPointerValue()); + CHECK(NULLPTR == actual.returnPointerValueOrDefault((void*) NULLPTR)); + CHECK(NULLPTR == actual.returnConstPointerValue()); + CHECK(NULLPTR == actual.returnConstPointerValueOrDefault((const void*) NULLPTR)); + CHECK(NULLPTR == actual.returnFunctionPointerValue()); + CHECK(NULLPTR == actual.returnFunctionPointerValueOrDefault((void (*)()) NULLPTR)); } +TEST(MockCheckedActualCall, MockActualCallTraceClear) +{ + MockActualCallTrace actual; + actual.withName("func"); + actual.clear(); + STRCMP_EQUAL("", actual.getTraceOutput()); +} diff --git a/tests/CppUTestExt/MockCallTest.cpp b/tests/CppUTestExt/MockCallTest.cpp index 44f3f7829..2e36c9aa6 100644 --- a/tests/CppUTestExt/MockCallTest.cpp +++ b/tests/CppUTestExt/MockCallTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -31,10 +31,11 @@ TEST_GROUP(MockCallTest) { - void teardown() - { - mock().checkExpectations(); - } + void teardown() CPPUTEST_OVERRIDE + { + mock().checkExpectations(); + mock().clear(); + } }; TEST(MockCallTest, clear) @@ -49,20 +50,39 @@ TEST(MockCallTest, checkExpectationsDoesntFail) mock().checkExpectations(); } -TEST(MockCallTest, exceptACallThatHappens) +TEST(MockCallTest, expectASingleCallThatHappens) { mock().expectOneCall("func"); - mock().actualCall("func"); + MockCheckedActualCall& actualCall = (MockCheckedActualCall&) mock().actualCall("func"); + actualCall.checkExpectations(); CHECK(! mock().expectedCallsLeft()); } -TEST(MockCallTest, exceptACallInceasesExpectedCallsLeft) +TEST(MockCallTest, expectASingleCallThatDoesntHappen) { mock().expectOneCall("func"); CHECK(mock().expectedCallsLeft()); mock().clear(); } +TEST(MockCallTest, expectAMultiCallThatHappensTheExpectedTimes) +{ + mock().expectNCalls(2, "func"); + mock().actualCall("func"); + MockCheckedActualCall& actualCall = (MockCheckedActualCall&) mock().actualCall("func"); + actualCall.checkExpectations(); + CHECK(! mock().expectedCallsLeft()); +} + +TEST(MockCallTest, expectAMultiCallThatDoesntHappenTheExpectedTimes) +{ + mock().expectNCalls(2, "func"); + MockCheckedActualCall& actualCall = (MockCheckedActualCall&) mock().actualCall("func"); + actualCall.checkExpectations(); + CHECK(mock().expectedCallsLeft()); + mock().clear(); +} + TEST(MockCallTest, checkExpectationsClearsTheExpectations) { MockFailureReporterInstaller failureReporterInstaller; @@ -147,7 +167,7 @@ TEST(MockCallTest, expectOneCallInScopeButActualCallInGlobal) } -TEST(MockCallTest, expectMultipleCallsThatHappen) +TEST(MockCallTest, expectMultipleSingleCallsThatHappen) { mock().expectOneCall("foo"); mock().expectOneCall("foo"); @@ -179,6 +199,7 @@ TEST(MockCallTest, expectNoCallThatHappened) MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; + expectations.addFunction(0, "lazy"); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "lazy", expectations); mock().expectNoCall("lazy"); @@ -192,7 +213,8 @@ TEST(MockCallTest, expectNoCallDoesntInfluenceExpectOneCall) MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; - expectations.addFunction("influence", MockCheckedExpectedCall::NO_EXPECTED_CALL_ORDER)->callWasMade(1); + expectations.addFunction(0, "lazy"); + expectations.addFunction("influence")->callWasMade(1); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "lazy", expectations); mock().expectNoCall("lazy"); @@ -208,6 +230,7 @@ TEST(MockCallTest, expectNoCallOnlyFailureOnceWhenMultipleHappened) MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; + expectations.addFunction(0, "lazy"); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "lazy", expectations); mock().expectNoCall("lazy"); @@ -221,6 +244,7 @@ TEST(MockCallTest, ignoreOtherCallsExceptForTheUnExpectedOne) MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; + expectations.addFunction(0, "lazy"); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "lazy", expectations); mock().expectNoCall("lazy"); @@ -239,6 +263,7 @@ TEST(MockCallTest, expectNoCallInScopeThatHappened) MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; + expectations.addFunction(0, "scope::lazy"); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "scope::lazy", expectations); mock("scope").expectNoCall("lazy"); @@ -277,7 +302,7 @@ TEST(MockCallTest, ignoreOtherCallsExceptForTheExpectedOne) { mock().expectOneCall("foo"); mock().ignoreOtherCalls(); - mock().actualCall("bar").withParameter("foo", 1);; + mock().actualCall("bar").withParameter("foo", 1); mock().clear(); } @@ -347,6 +372,31 @@ TEST(MockCallTest, OnObject) mock().actualCall("boo").onObject(objectPtr); } +TEST(MockCallTest, OnObjectIgnored_MatchingAlreadyWhenObjectPassed) +{ + void* objectPtr = (void*) 0x001; + mock().expectOneCall("boo"); + mock().actualCall("boo").onObject(objectPtr); +} + +TEST(MockCallTest, OnObjectIgnored_NotMatchingYetWhenObjectPassed) +{ + void* objectPtr = (void*) 0x001; + mock().expectOneCall("boo").withBoolParameter("p", true); + mock().actualCall("boo").onObject(objectPtr).withBoolParameter("p", true); +} + +TEST(MockCallTest, OnObjectIgnored_InitialMatchDiscarded) +{ + void* objectPtr1 = (void*) 0x001; + void* objectPtr2 = (void*) 0x002; + + mock().expectOneCall("boo"); + mock().expectOneCall("boo").withBoolParameter("p", true); + mock().actualCall("boo").onObject(objectPtr2).withBoolParameter("p", true); + mock().actualCall("boo").onObject(objectPtr1); +} + TEST(MockCallTest, OnObjectFails) { MockFailureReporterInstaller failureReporterInstaller; @@ -383,7 +433,7 @@ TEST(MockCallTest, OnObjectExpectedButNotCalled) CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } -TEST(MockCallTest, expectMultipleCalls) +TEST(MockCallTest, expectNCalls_Fulfilled) { mock().expectNCalls(2, "boo"); mock().actualCall("boo"); @@ -391,15 +441,34 @@ TEST(MockCallTest, expectMultipleCalls) mock().checkExpectations(); } +TEST(MockCallTest, expectNCalls_NotFulfilled) +{ + MockFailureReporterInstaller failureReporterInstaller; + + MockExpectedCallsListForTest expectations; + expectations.addFunction(2, "boo")->callWasMade(1); + MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); + + mock().expectNCalls(2, "boo"); + mock().actualCall("boo"); + mock().checkExpectations(); + + CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); +} + TEST(MockCallTest, shouldntFailTwice) { MockFailureReporterInstaller failureReporterInstaller; + mock().strictOrder(); mock().expectOneCall("foo"); + mock().expectOneCall("boo"); + mock().actualCall("boo"); mock().actualCall("bar"); mock().checkExpectations(); CHECK(!MockFailureReporterForTest::getReporter()->mockFailureString.contains("bar")); + CHECK(MockFailureReporterForTest::getReporter()->mockFailureString.contains("boo")); } TEST(MockCallTest, shouldReturnDefaultWhenThereIsntAnythingToReturn) @@ -429,6 +498,16 @@ TEST(MockCallTest, mockExpectationShouldIncreaseNumberOfChecks) TestTestingFixture fixture; fixture.setTestFunction(mocksAreCountedAsChecksTestFunction_); fixture.runAllTests(); - LONGS_EQUAL(5, fixture.getCheckCount()); + LONGS_EQUAL(3, fixture.getCheckCount()); } +TEST(MockCallTest, expectationsLeftBeforCheckExpectations) +{ + CHECK(!mock().expectedCallsLeft()); + mock().expectOneCall("boo"); + CHECK(mock().expectedCallsLeft()); + mock().actualCall("boo"); + CHECK(!mock().expectedCallsLeft()); + mock().checkExpectations(); + CHECK(!mock().expectedCallsLeft()); +} diff --git a/tests/CppUTestExt/MockCheatSheetTest.cpp b/tests/CppUTestExt/MockCheatSheetTest.cpp index 6e91b475d..ec74a22ce 100644 --- a/tests/CppUTestExt/MockCheatSheetTest.cpp +++ b/tests/CppUTestExt/MockCheatSheetTest.cpp @@ -25,6 +25,7 @@ static int productionCodeFooCalls() { int return_value; return_value = foo("value_string", 10); + (void)return_value; return_value = foo("value_string", 10); return return_value; } @@ -38,10 +39,12 @@ static void productionCodeBarCalls() /* Actual test */ TEST_GROUP(MockCheatSheet) { - void teardown() + void teardown() CPPUTEST_OVERRIDE { /* Check expectations. Alternatively use MockSupportPlugin */ mock().checkExpectations(); + + mock().clear(); } }; @@ -70,4 +73,3 @@ TEST(MockCheatSheet, bar) /* And the production code call */ productionCodeBarCalls(); } - diff --git a/tests/CppUTestExt/MockComparatorCopierTest.cpp b/tests/CppUTestExt/MockComparatorCopierTest.cpp index 0b83a6811..5cad7a4a5 100644 --- a/tests/CppUTestExt/MockComparatorCopierTest.cpp +++ b/tests/CppUTestExt/MockComparatorCopierTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,10 +30,12 @@ TEST_GROUP(MockComparatorCopierTest) { - void teardown() - { - mock().checkExpectations(); - } + void teardown() CPPUTEST_OVERRIDE + { + mock().checkExpectations(); + mock().clear(); + mock().removeAllComparatorsAndCopiers(); + } }; class MyTypeForTesting @@ -53,13 +55,13 @@ class MyTypeForTesting class MyTypeForTestingComparator : public MockNamedValueComparator { public: - virtual bool isEqual(const void* object1, const void* object2) + virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { const MyTypeForTesting* obj1 = (const MyTypeForTesting*) object1; const MyTypeForTesting* obj2 = (const MyTypeForTesting*) object2; return *(obj1->value) == *(obj2->value); } - virtual SimpleString valueToString(const void* object) + virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { const MyTypeForTesting* obj = (const MyTypeForTesting*) object; return StringFrom(*(obj->value)); @@ -69,7 +71,7 @@ class MyTypeForTestingComparator : public MockNamedValueComparator class MyTypeForTestingCopier : public MockNamedValueCopier { public: - virtual void copy(void* dst_, const void* src_) + virtual void copy(void* dst_, const void* src_) CPPUTEST_OVERRIDE { MyTypeForTesting* dst = (MyTypeForTesting*) dst_; const MyTypeForTesting* src = (const MyTypeForTesting*) src_; @@ -117,12 +119,12 @@ TEST(MockComparatorCopierTest, customObjectParameterSucceeds) static bool myTypeIsEqual(const void* object1, const void* object2) { - return ((MyTypeForTesting*)object1)->value == ((MyTypeForTesting*)object2)->value; + return ((const MyTypeForTesting*)object1)->value == ((const MyTypeForTesting*)object2)->value; } static SimpleString myTypeValueToString(const void* object) { - return StringFrom(((MyTypeForTesting*)object)->value); + return StringFrom(((const MyTypeForTesting*)object)->value); } TEST(MockComparatorCopierTest, customObjectWithFunctionComparator) @@ -205,7 +207,7 @@ TEST(MockComparatorCopierTest, unexpectedCustomTypeOutputParameter) MockExpectedCallsListForTest expectations; expectations.addFunction("foo"); MockNamedValue parameter("parameterName"); - parameter.setObjectPointer("MyTypeForTesting", &actualObject); + parameter.setConstObjectPointer("MyTypeForTesting", &actualObject); MockUnexpectedOutputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo"); @@ -227,7 +229,7 @@ TEST(MockComparatorCopierTest, customTypeOutputParameterMissing) MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); - MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations); + MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations, expectations); mock().expectOneCall("foo").withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); mock().actualCall("foo"); @@ -250,7 +252,7 @@ TEST(MockComparatorCopierTest, customTypeOutputParameterOfWrongType) MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); MockNamedValue parameter("output"); - parameter.setObjectPointer("OtherTypeForTesting", &actualObject); + parameter.setConstObjectPointer("OtherTypeForTesting", &actualObject); MockUnexpectedOutputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); @@ -565,11 +567,11 @@ TEST(MockComparatorCopierTest, installCopiersWorksHierarchically) class StubComparator : public MockNamedValueComparator { public: - virtual bool isEqual(const void*, const void*) + virtual bool isEqual(const void*, const void*) CPPUTEST_OVERRIDE { return true; } - virtual SimpleString valueToString(const void*) + virtual SimpleString valueToString(const void*) CPPUTEST_OVERRIDE { return ""; } @@ -596,4 +598,3 @@ TEST(MockComparatorCopierTest, shouldSupportConstParameters) mock().checkExpectations(); } - diff --git a/tests/CppUTestExt/MockExpectedCallTest.cpp b/tests/CppUTestExt/MockExpectedCallTest.cpp index c8d546b68..7bd76aa73 100644 --- a/tests/CppUTestExt/MockExpectedCallTest.cpp +++ b/tests/CppUTestExt/MockExpectedCallTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -47,13 +47,13 @@ class TypeForTestingExpectedFunctionCall class TypeForTestingExpectedFunctionCallComparator : public MockNamedValueComparator { public: - virtual bool isEqual(const void* object1, const void* object2) + virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { const TypeForTestingExpectedFunctionCall* obj1 = (const TypeForTestingExpectedFunctionCall*) object1; const TypeForTestingExpectedFunctionCall* obj2 = (const TypeForTestingExpectedFunctionCall*) object2; return *(obj1->value) == *(obj2->value); } - virtual SimpleString valueToString(const void* object) + virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { const TypeForTestingExpectedFunctionCall* obj = (const TypeForTestingExpectedFunctionCall*) object; return StringFrom(*(obj->value)); @@ -63,7 +63,7 @@ class TypeForTestingExpectedFunctionCallComparator : public MockNamedValueCompar class TypeForTestingExpectedFunctionCallCopier : public MockNamedValueCopier { public: - virtual void copy(void* dst_, const void* src_) + virtual void copy(void* dst_, const void* src_) CPPUTEST_OVERRIDE { TypeForTestingExpectedFunctionCall* dst = (TypeForTestingExpectedFunctionCall*) dst_; const TypeForTestingExpectedFunctionCall* src = (const TypeForTestingExpectedFunctionCall*) src_; @@ -73,16 +73,17 @@ class TypeForTestingExpectedFunctionCallCopier : public MockNamedValueCopier TEST_GROUP(MockNamedValueHandlerRepository) { - void teardown() + void teardown() CPPUTEST_OVERRIDE { CHECK_NO_MOCK_FAILURE(); + MockFailureReporterForTest::clearReporter(); } }; TEST(MockNamedValueHandlerRepository, getComparatorForNonExistingName) { MockNamedValueComparatorsAndCopiersRepository repository; - POINTERS_EQUAL(NULL, repository.getComparatorForType("typeName")); + POINTERS_EQUAL(NULLPTR, repository.getComparatorForType("typeName")); } TEST(MockNamedValueHandlerRepository, installComparator) @@ -108,7 +109,7 @@ TEST(MockNamedValueHandlerRepository, installMultipleComparators) TEST(MockNamedValueHandlerRepository, getCopierForNonExistingName) { MockNamedValueComparatorsAndCopiersRepository repository; - POINTERS_EQUAL(NULL, repository.getCopierForType("typeName")); + POINTERS_EQUAL(NULLPTR, repository.getCopierForType("typeName")); } TEST(MockNamedValueHandlerRepository, installCopier) @@ -153,14 +154,19 @@ TEST(MockNamedValueHandlerRepository, installMultipleHandlers) TEST_GROUP(MockExpectedCall) { MockCheckedExpectedCall* call; - void setup() + MockNamedValueComparatorsAndCopiersRepository* originalComparatorRepository; + void setup() CPPUTEST_OVERRIDE { - call = new MockCheckedExpectedCall; + originalComparatorRepository = MockNamedValue::getDefaultComparatorsAndCopiersRepository(); + call = new MockCheckedExpectedCall(1); + call->withName("funcName"); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { + MockNamedValue::setDefaultComparatorsAndCopiersRepository(originalComparatorRepository); delete call; CHECK_NO_MOCK_FAILURE(); + MockFailureReporterForTest::clearReporter(); } }; @@ -173,110 +179,173 @@ TEST(MockExpectedCall, callWithoutParameterSetOrNotFound) TEST(MockExpectedCall, callWithUnsignedIntegerParameter) { - const SimpleString name = "unsigned integer"; - unsigned int value = 777; - call->withParameter(name, value); - STRCMP_EQUAL("unsigned int", call->getInputParameterType(name).asCharString()); - LONGS_EQUAL(value, call->getInputParameter(name).getUnsignedIntValue()); - CHECK(call->hasInputParameterWithName(name)); + const SimpleString paramName = "paramName"; + unsigned int value = 356; + call->withParameter(paramName, value); + STRCMP_EQUAL("unsigned int", call->getInputParameterType(paramName).asCharString()); + LONGS_EQUAL(value, call->getInputParameter(paramName).getUnsignedIntValue()); + CHECK(call->hasInputParameterWithName(paramName)); + STRCMP_CONTAINS("funcName -> unsigned int paramName: <356 (0x164)>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithIntegerParameter) { - call->withParameter("integer", 1); - STRCMP_EQUAL("int", call->getInputParameterType("integer").asCharString()); - LONGS_EQUAL(1, call->getInputParameter("integer").getIntValue()); - CHECK(call->hasInputParameterWithName("integer")); + const SimpleString paramName = "paramName"; + int value = 2; + call->withParameter(paramName, value); + STRCMP_EQUAL("int", call->getInputParameterType(paramName).asCharString()); + LONGS_EQUAL(value, call->getInputParameter(paramName).getIntValue()); + CHECK(call->hasInputParameterWithName(paramName)); + STRCMP_CONTAINS("funcName -> int paramName: <2 (0x2)>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithBooleanParameter) { - call->withParameter("boolean", true); - STRCMP_EQUAL("bool", call->getInputParameterType("boolean").asCharString()); - CHECK_EQUAL(true, call->getInputParameter("boolean").getBoolValue()); - CHECK(call->hasInputParameterWithName("boolean")); + const SimpleString paramName = "paramName"; + bool value = true; + call->withParameter(paramName, value); + STRCMP_EQUAL("bool", call->getInputParameterType(paramName).asCharString()); + CHECK_EQUAL(value, call->getInputParameter(paramName).getBoolValue()); + CHECK(call->hasInputParameterWithName(paramName)); + STRCMP_CONTAINS("funcName -> bool paramName: ", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithUnsignedLongIntegerParameter) { - const SimpleString name = "unsigned long integer"; - unsigned long value = 777; - call->withParameter(name, value); - STRCMP_EQUAL("unsigned long int", call->getInputParameterType(name).asCharString()); - LONGS_EQUAL(value, call->getInputParameter(name).getUnsignedLongIntValue()); - CHECK(call->hasInputParameterWithName(name)); + const SimpleString paramName = "paramName"; + unsigned long value = 888; + call->withParameter(paramName, value); + STRCMP_EQUAL("unsigned long int", call->getInputParameterType(paramName).asCharString()); + LONGS_EQUAL(value, call->getInputParameter(paramName).getUnsignedLongIntValue()); + CHECK(call->hasInputParameterWithName(paramName)); + STRCMP_CONTAINS("funcName -> unsigned long int paramName: <888 (0x378)>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithLongIntegerParameter) { - const SimpleString name = "long integer"; + const SimpleString paramName = "paramName"; long value = 777; - call->withParameter(name, value); - STRCMP_EQUAL("long int", call->getInputParameterType(name).asCharString()); - LONGS_EQUAL(value, call->getInputParameter(name).getLongIntValue()); - CHECK(call->hasInputParameterWithName(name)); + call->withParameter(paramName, value); + STRCMP_EQUAL("long int", call->getInputParameterType(paramName).asCharString()); + LONGS_EQUAL(value, call->getInputParameter(paramName).getLongIntValue()); + CHECK(call->hasInputParameterWithName(paramName)); + STRCMP_CONTAINS("funcName -> long int paramName: <777 (0x309)>", call->callToString().asCharString()); +} + +#if CPPUTEST_USE_LONG_LONG + +TEST(MockExpectedCall, callWithUnsignedLongLongIntegerParameter) +{ + const SimpleString paramName = "paramName"; + unsigned long long value = 888; + call->withParameter(paramName, value); + STRCMP_EQUAL("unsigned long long int", call->getInputParameterType(paramName).asCharString()); + UNSIGNED_LONGLONGS_EQUAL(value, call->getInputParameter(paramName).getUnsignedLongLongIntValue()); + CHECK(call->hasInputParameterWithName(paramName)); + STRCMP_CONTAINS("funcName -> unsigned long long int paramName: <888 (0x378)>", call->callToString().asCharString()); +} + +TEST(MockExpectedCall, callWithLongLongIntegerParameter) +{ + const SimpleString paramName = "paramName"; + long long value = 777; + call->withParameter(paramName, value); + STRCMP_EQUAL("long long int", call->getInputParameterType(paramName).asCharString()); + LONGLONGS_EQUAL(value, call->getInputParameter(paramName).getLongLongIntValue()); + CHECK(call->hasInputParameterWithName(paramName)); + STRCMP_CONTAINS("funcName -> long long int paramName: <777 (0x309)>", call->callToString().asCharString()); } +#endif + TEST(MockExpectedCall, callWithDoubleParameter) { - call->withParameter("double", 1.2); - STRCMP_EQUAL("double", call->getInputParameterType("double").asCharString()); - DOUBLES_EQUAL(1.2, call->getInputParameter("double").getDoubleValue(), 0.05); + const SimpleString paramName = "paramName"; + double value = 1.2; + call->withParameter(paramName, value); + STRCMP_EQUAL("double", call->getInputParameterType(paramName).asCharString()); + DOUBLES_EQUAL(value, call->getInputParameter(paramName).getDoubleValue(), 0.0); + STRCMP_CONTAINS("funcName -> double paramName: <1.2>", call->callToString().asCharString()); +} + +TEST(MockExpectedCall, callWithDoubleParameterAndTolerance) +{ + const SimpleString paramName = "paramName"; + double value = 1.2; + double tolerance = 0.2; + call->withParameter(paramName, value, tolerance); + STRCMP_EQUAL("double", call->getInputParameterType(paramName).asCharString()); + DOUBLES_EQUAL(value, call->getInputParameter(paramName).getDoubleValue(), 0.0); + DOUBLES_EQUAL(tolerance, call->getInputParameter(paramName).getDoubleTolerance(), 0.0); + STRCMP_CONTAINS("funcName -> double paramName: <1.2>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithStringParameter) { - call->withParameter("string", "hello world"); - STRCMP_EQUAL("const char*", call->getInputParameterType("string").asCharString()); - STRCMP_EQUAL("hello world", call->getInputParameter("string").getStringValue()); + const SimpleString paramName = "paramName"; + const char* value = "hello world"; + call->withParameter(paramName, value); + STRCMP_EQUAL("const char*", call->getInputParameterType(paramName).asCharString()); + STRCMP_EQUAL(value, call->getInputParameter(paramName).getStringValue()); + STRCMP_CONTAINS("funcName -> const char* paramName: ", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithPointerParameter) { - void* ptr = (void*) 0x123; - call->withParameter("pointer", ptr); - STRCMP_EQUAL("void*", call->getInputParameterType("pointer").asCharString()); - POINTERS_EQUAL(ptr, call->getInputParameter("pointer").getPointerValue()); + const SimpleString paramName = "paramName"; + void* value = (void*) 0x123; + call->withParameter(paramName, value); + STRCMP_EQUAL("void*", call->getInputParameterType(paramName).asCharString()); + POINTERS_EQUAL(value, call->getInputParameter(paramName).getPointerValue()); + STRCMP_CONTAINS("funcName -> void* paramName: <0x123>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithConstPointerParameter) { - const void* ptr = (const void*) 0x345; - call->withParameter("constPointer", ptr); - STRCMP_EQUAL("const void*", call->getInputParameterType("constPointer").asCharString()); - POINTERS_EQUAL(ptr, call->getInputParameter("constPointer").getConstPointerValue()); + const SimpleString paramName = "paramName"; + const void* value = (const void*) 0x345; + call->withParameter(paramName, value); + STRCMP_EQUAL("const void*", call->getInputParameterType(paramName).asCharString()); + POINTERS_EQUAL(value, call->getInputParameter(paramName).getConstPointerValue()); + STRCMP_CONTAINS("funcName -> const void* paramName: <0x345>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithFunctionPointerParameter) { - void (*ptr)() = (void (*)()) 0x123; - call->withParameter("functionPointer", ptr); - STRCMP_EQUAL("void (*)()", call->getInputParameterType("functionPointer").asCharString()); - FUNCTIONPOINTERS_EQUAL(ptr, call->getInputParameter("functionPointer").getFunctionPointerValue()); + const SimpleString paramName = "paramName"; + void (*value)() = (void (*)()) 0xdead; + call->withParameter(paramName, value); + STRCMP_EQUAL("void (*)()", call->getInputParameterType(paramName).asCharString()); + FUNCTIONPOINTERS_EQUAL(value, call->getInputParameter(paramName).getFunctionPointerValue()); + STRCMP_CONTAINS("funcName -> void (*)() paramName: <0xdead>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithMemoryBuffer) { - const unsigned char mem_buffer[] = { 0x12, 0xFE, 0xA1 }; - call->withParameter("memoryBuffer", mem_buffer, sizeof(mem_buffer)); - STRCMP_EQUAL("const unsigned char*", call->getInputParameterType("memoryBuffer").asCharString()); - POINTERS_EQUAL( (void*) mem_buffer, (void*) call->getInputParameter("memoryBuffer").getMemoryBuffer() ); - LONGS_EQUAL(sizeof(mem_buffer), call->getInputParameter("memoryBuffer").getSize()); + const SimpleString paramName = "paramName"; + const unsigned char value[] = { 0x12, 0xFE, 0xA1 }; + call->withParameter(paramName, value, sizeof(value)); + STRCMP_EQUAL("const unsigned char*", call->getInputParameterType(paramName).asCharString()); + POINTERS_EQUAL(value, call->getInputParameter(paramName).getMemoryBuffer()); + LONGS_EQUAL(sizeof(value), call->getInputParameter(paramName).getSize()); + STRCMP_CONTAINS("funcName -> const unsigned char* paramName: ", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithObjectParameter) { - void* ptr = (void*) 0x123; - call->withParameterOfType("class", "object", ptr); - POINTERS_EQUAL(ptr, call->getInputParameter("object").getObjectPointer()); - STRCMP_EQUAL("class", call->getInputParameterType("object").asCharString()); + const SimpleString paramName = "paramName"; + void* value = (void*) 0x123; + call->withParameterOfType("ClassName", paramName, value); + POINTERS_EQUAL(value, call->getInputParameter(paramName).getConstObjectPointer()); + STRCMP_EQUAL("ClassName", call->getInputParameterType(paramName).asCharString()); + STRCMP_CONTAINS("funcName -> ClassName paramName: ", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithObjectParameterUnequalComparison) { TypeForTestingExpectedFunctionCall type(1), unequalType(2); MockNamedValue parameter("name"); - parameter.setObjectPointer("type", &unequalType); + parameter.setConstObjectPointer("type", &unequalType); call->withParameterOfType("type", "name", &type); CHECK(!call->hasInputParameter(parameter)); } @@ -285,7 +354,7 @@ TEST(MockExpectedCall, callWithObjectParameterEqualComparisonButFailsWithoutRepo { TypeForTestingExpectedFunctionCall type(1), equalType(1); MockNamedValue parameter("name"); - parameter.setObjectPointer("type", &equalType); + parameter.setConstObjectPointer("type", &equalType); call->withParameterOfType("type", "name", &type); CHECK(!call->hasInputParameter(parameter)); } @@ -297,7 +366,7 @@ TEST(MockExpectedCall, callWithObjectParameterEqualComparisonButFailsWithoutComp TypeForTestingExpectedFunctionCall type(1), equalType(1); MockNamedValue parameter("name"); - parameter.setObjectPointer("type", &equalType); + parameter.setConstObjectPointer("type", &equalType); call->withParameterOfType("type", "name", &type); CHECK(!call->hasInputParameter(parameter)); } @@ -311,7 +380,7 @@ TEST(MockExpectedCall, callWithObjectParameterEqualComparison) TypeForTestingExpectedFunctionCall type(1), equalType(1); MockNamedValue parameter("name"); - parameter.setObjectPointer("type", &equalType); + parameter.setConstObjectPointer("type", &equalType); call->withParameterOfType("type", "name", &type); CHECK(call->hasInputParameter(parameter)); @@ -326,7 +395,7 @@ TEST(MockExpectedCall, getParameterValueOfObjectType) TypeForTestingExpectedFunctionCall type(1); call->withParameterOfType("type", "name", &type); - POINTERS_EQUAL(&type, call->getInputParameter("name").getObjectPointer()); + POINTERS_EQUAL(&type, call->getInputParameter("name").getConstObjectPointer()); STRCMP_EQUAL("1", call->getInputParameterValueString("name").asCharString()); } @@ -385,58 +454,121 @@ TEST(MockExpectedCall, callWithThreeDifferentParameter) DOUBLES_EQUAL(0.12, call->getInputParameter("double").getDoubleValue(), 0.05); } -TEST(MockExpectedCall, withoutANameItsFulfilled) +TEST(MockExpectedCall, singleCallNotMadeIsNotFulfilledButCanMatchActualCalls) { - CHECK(call->isFulfilled()); + MockCheckedExpectedCall expectedCall(1); + expectedCall.withName("name"); + CHECK(!expectedCall.isFulfilled()); + CHECK(expectedCall.canMatchActualCalls()); } -TEST(MockExpectedCall, withANameItsNotFulfilled) +TEST(MockExpectedCall, singleCallMadeIsFulFilledAndCannotMatchActualCalls) { - call->withName("name"); - CHECK(!call->isFulfilled()); + MockCheckedExpectedCall expectedCall(1); + expectedCall.callWasMade(1); + CHECK(expectedCall.isFulfilled()); + CHECK(!expectedCall.canMatchActualCalls()); } -TEST(MockExpectedCall, afterSettingCallFulfilledItsFulFilled) +TEST(MockExpectedCall, multiCallNotMadeIsNotFulfilledButCanMatchActualCalls) { - call->withName("name"); - call->callWasMade(1); - CHECK(call->isFulfilled()); + MockCheckedExpectedCall expectedCall(2); + expectedCall.withName("name"); + CHECK(!expectedCall.isFulfilled()); + CHECK(expectedCall.canMatchActualCalls()); } -TEST(MockExpectedCall, calledButNotWithParameterIsNotFulFilled) +TEST(MockExpectedCall, multiCallNotMadeExpectedTimesIsNotFulfilledButCanMatchActualCalls) { - call->withName("name").withParameter("para", 1); - call->callWasMade(1); - CHECK(!call->isFulfilled()); + MockCheckedExpectedCall expectedCall(2); + expectedCall.withName("name"); + expectedCall.callWasMade(1); + CHECK(!expectedCall.isFulfilled()); + CHECK(expectedCall.canMatchActualCalls()); } -TEST(MockExpectedCall, calledAndParametersAreFulfilled) +TEST(MockExpectedCall, multiCallsMadeExpectedTimesIsFulfilledAndCannotMatchActualCalls) { - call->withName("name").withParameter("para", 1); - call->callWasMade(1); - call->inputParameterWasPassed("para"); - CHECK(call->isFulfilled()); + MockCheckedExpectedCall expectedCall(3); + expectedCall.withName("name"); + expectedCall.callWasMade(1); + expectedCall.callWasMade(2); + expectedCall.callWasMade(3); + CHECK(expectedCall.isFulfilled()); + CHECK(!expectedCall.canMatchActualCalls()); } -TEST(MockExpectedCall, calledButNotAllParametersAreFulfilled) +TEST(MockExpectedCall, multiCallsMadeMoreThanExpectedTimesIsNotFulfilledAndCannotMatchActualCalls) { - call->withName("name").withParameter("para", 1).withParameter("two", 2); - call->callWasMade(1); - call->inputParameterWasPassed("para"); - CHECK(!call->isFulfilled()); + MockCheckedExpectedCall expectedCall(3); + expectedCall.withName("name"); + expectedCall.callWasMade(1); + expectedCall.callWasMade(2); + expectedCall.callWasMade(3); + expectedCall.callWasMade(4); + CHECK(!expectedCall.isFulfilled()); + CHECK(!expectedCall.canMatchActualCalls()); } -TEST(MockExpectedCall, toStringForNoParameters) +TEST(MockExpectedCall, callsWithoutParameterAlwaysMatch) { - call->withName("name"); - STRCMP_EQUAL("name -> no parameters", call->callToString().asCharString()); + MockCheckedExpectedCall expectedCall(1); + CHECK(expectedCall.isMatchingActualCall()); +} + +TEST(MockExpectedCall, callsWithParameterNotFulfilledDontMatch) +{ + MockCheckedExpectedCall expectedCall(1); + expectedCall.withParameter("para", 1); + CHECK(!expectedCall.isMatchingActualCall()); +} + +TEST(MockExpectedCall, callsWithParameterFulfilledDoMatch) +{ + MockCheckedExpectedCall expectedCall(1); + expectedCall.withParameter("para", 1); + expectedCall.inputParameterWasPassed("para"); + CHECK(expectedCall.isMatchingActualCall()); +} + +TEST(MockExpectedCall, callsWithSomeParametersNotFulfilledDontMatch) +{ + MockCheckedExpectedCall expectedCall(1); + expectedCall.withParameter("para", 1).withParameter("two", 2); + expectedCall.inputParameterWasPassed("para"); + CHECK(!expectedCall.isMatchingActualCall()); +} + +TEST(MockExpectedCall, toStringForNoParametersSingleCallNotCalled) +{ + MockCheckedExpectedCall expectedCall(1); + expectedCall.withName("name"); + STRCMP_EQUAL("name -> no parameters (expected 1 call, called 0 times)", expectedCall.callToString().asCharString()); +} + +TEST(MockExpectedCall, toStringForNoParametersMultiCallCalledLessThanExpectedTimes) +{ + MockCheckedExpectedCall expectedCall(2); + expectedCall.withName("name"); + expectedCall.callWasMade(1); + STRCMP_EQUAL("name -> no parameters (expected 2 calls, called 1 time)", expectedCall.callToString().asCharString()); +} + +TEST(MockExpectedCall, toStringForNoParametersMultiCallCalledExpectedTimes) +{ + MockCheckedExpectedCall expectedCall(2); + expectedCall.withName("name"); + expectedCall.callWasMade(1); + expectedCall.callWasMade(2); + STRCMP_EQUAL("name -> no parameters (expected 2 calls, called 2 times)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForIgnoredParameters) { - call->withName("name"); - call->ignoreOtherParameters(); - STRCMP_EQUAL("name -> all parameters ignored", call->callToString().asCharString()); + MockCheckedExpectedCall expectedCall(1); + expectedCall.withName("name"); + expectedCall.ignoreOtherParameters(); + STRCMP_EQUAL("name -> all parameters ignored (expected 1 call, called 0 times)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForMultipleInputParameters) @@ -444,11 +576,14 @@ TEST(MockExpectedCall, toStringForMultipleInputParameters) int int_value = 10; unsigned int uint_value = 7; - call->withName("name"); - call->withParameter("string", "value"); - call->withParameter("integer", int_value); - call->withParameter("unsigned-integer", uint_value); - STRCMP_EQUAL("name -> const char* string: , int integer: <10>, unsigned int unsigned-integer: < 7 (0x00000007)>", call->callToString().asCharString()); + MockCheckedExpectedCall expectedCall(1); + expectedCall.withName("name"); + expectedCall.withParameter("string", "value"); + expectedCall.withParameter("integer", int_value); + expectedCall.withParameter("unsigned-integer", uint_value); + expectedCall.callWasMade(1); + STRCMP_EQUAL("name -> const char* string: , int integer: <10 (0xa)>, unsigned int unsigned-integer: <7 (0x7)> " + "(expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForMultipleInputAndOutputParameters) @@ -457,41 +592,71 @@ TEST(MockExpectedCall, toStringForMultipleInputAndOutputParameters) unsigned int uint_value = 7; unsigned char buffer_value[3]; - call->withName("name"); - call->withParameter("string", "value"); - call->withParameter("integer", int_value); - call->withParameter("unsigned-integer", uint_value); - call->withOutputParameterReturning("buffer", buffer_value, sizeof(buffer_value)); - STRCMP_EQUAL("name -> const char* string: , int integer: <10>, unsigned int unsigned-integer: < 7 (0x00000007)>, " - "const void* buffer: ", call->callToString().asCharString()); + MockCheckedExpectedCall expectedCall(1); + expectedCall.withName("name"); + expectedCall.withParameter("string", "value"); + expectedCall.withParameter("integer", int_value); + expectedCall.withParameter("unsigned-integer", uint_value); + expectedCall.withOutputParameterReturning("buffer", buffer_value, sizeof(buffer_value)); + expectedCall.callWasMade(1); + STRCMP_EQUAL("name -> const char* string: , int integer: <10 (0xa)>, unsigned int unsigned-integer: <7 (0x7)>, " + "const void* buffer: (expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForMultipleOutputParameters) { unsigned char buffer_value[3]; - call->withName("name"); - call->withOutputParameterReturning("buffer1", buffer_value, sizeof(buffer_value)); - call->withOutputParameterReturning("buffer2", buffer_value, sizeof(buffer_value)); - STRCMP_EQUAL("name -> const void* buffer1: , const void* buffer2: ", call->callToString().asCharString()); + MockCheckedExpectedCall expectedCall(1); + expectedCall.withName("name"); + expectedCall.withOutputParameterReturning("buffer1", buffer_value, sizeof(buffer_value)); + expectedCall.withOutputParameterReturning("buffer2", buffer_value, sizeof(buffer_value)); + expectedCall.callWasMade(1); + STRCMP_EQUAL("name -> const void* buffer1: , const void* buffer2: (expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); +} + +TEST(MockExpectedCall, toStringForUnmodifiedOutputParameter) +{ + MockCheckedExpectedCall expectedCall(1); + expectedCall.withName("name"); + expectedCall.withUnmodifiedOutputParameter("buffer1"); + expectedCall.callWasMade(1); + STRCMP_EQUAL("name -> const void* buffer1: (expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForParameterAndIgnored) { - call->withName("name"); - call->withParameter("string", "value"); - call->ignoreOtherParameters(); - STRCMP_EQUAL("name -> const char* string: , other parameters are ignored", call->callToString().asCharString()); + MockCheckedExpectedCall expectedCall(1); + expectedCall.withName("name"); + expectedCall.withParameter("string", "value"); + expectedCall.ignoreOtherParameters(); + expectedCall.callWasMade(1); + STRCMP_EQUAL("name -> const char* string: , other parameters are ignored (expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); } -TEST(MockExpectedCall, toStringForCallOrder) +TEST(MockExpectedCall, toStringForCallOrderSingle) { - call->withName("name"); - call->withCallOrder(2); - STRCMP_EQUAL("name -> expected call order: <2> -> no parameters", call->callToString().asCharString()); + MockCheckedExpectedCall expectedCall(1); + expectedCall.withName("name"); + expectedCall.withCallOrder(2); + expectedCall.callWasMade(1); + STRCMP_EQUAL("name -> expected call order: <2> -> no parameters (expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); +} + +TEST(MockExpectedCall, toStringForCallOrderMultiple) +{ + MockCheckedExpectedCall expectedCall(5); + expectedCall.withName("name"); + expectedCall.withCallOrder(5, 9); + expectedCall.callWasMade(5); + expectedCall.callWasMade(6); + expectedCall.callWasMade(7); + expectedCall.callWasMade(8); + expectedCall.callWasMade(9); + STRCMP_EQUAL("name -> expected calls order: <5..9> -> no parameters (expected 5 calls, called 5 times)", expectedCall.callToString().asCharString()); } -TEST(MockExpectedCall, callOrderIsNotFulfilledWithWrongOrder) +TEST(MockExpectedCall, callOrderIsFulfilledButWithWrongOrderSingle) { call->withName("name"); call->withCallOrder(2); @@ -500,7 +665,31 @@ TEST(MockExpectedCall, callOrderIsNotFulfilledWithWrongOrder) CHECK(call->isOutOfOrder()); } -TEST(MockExpectedCall, callOrderIsFulfilled) +TEST(MockExpectedCall, callOrderIsFulfilledButWithWrongOrderMultipleTooEarly) +{ + MockCheckedExpectedCall expectedCall(3); + expectedCall.withName("name"); + expectedCall.withCallOrder(10, 12); + expectedCall.callWasMade(9); + expectedCall.callWasMade(10); + expectedCall.callWasMade(11); + CHECK(expectedCall.isFulfilled()); + CHECK(expectedCall.isOutOfOrder()); +} + +TEST(MockExpectedCall, callOrderIsFulfilledButWithWrongOrderMultipleTooLate) +{ + MockCheckedExpectedCall expectedCall(3); + expectedCall.withName("name"); + expectedCall.withCallOrder(10, 12); + expectedCall.callWasMade(11); + expectedCall.callWasMade(12); + expectedCall.callWasMade(13); + CHECK(expectedCall.isFulfilled()); + CHECK(expectedCall.isOutOfOrder()); +} + +TEST(MockExpectedCall, callOrderIsFulfilledSingle) { call->withName("name"); call->withCallOrder(1); @@ -509,6 +698,19 @@ TEST(MockExpectedCall, callOrderIsFulfilled) CHECK_FALSE(call->isOutOfOrder()); } +TEST(MockExpectedCall, callOrderIsFulfilledMultiple) +{ + MockCheckedExpectedCall expectedCall(4); + expectedCall.withName("name"); + expectedCall.withCallOrder(150, 153); + expectedCall.callWasMade(150); + expectedCall.callWasMade(151); + expectedCall.callWasMade(152); + expectedCall.callWasMade(153); + CHECK(expectedCall.isFulfilled()); + CHECK_FALSE(expectedCall.isOutOfOrder()); +} + TEST(MockExpectedCall, hasOutputParameter) { const int value = 1; @@ -518,6 +720,15 @@ TEST(MockExpectedCall, hasOutputParameter) CHECK(call->hasOutputParameter(foo)); } +TEST(MockExpectedCall, hasUnmodifiedOutputParameter) +{ + call->withUnmodifiedOutputParameter("foo"); + MockNamedValue foo("foo"); + foo.setValue((const void *)NULLPTR); + foo.setSize(0); + CHECK(call->hasOutputParameter(foo)); +} + TEST(MockExpectedCall, hasNoOutputParameter) { call->withIntParameter("foo", (int)1); @@ -531,7 +742,7 @@ TEST(MockExpectedCall, hasOutputParameterOfType) TypeForTestingExpectedFunctionCall object(6789); call->withOutputParameterOfTypeReturning("TypeForTestingExpectedFunctionCall", "foo", &object); MockNamedValue foo("foo"); - foo.setObjectPointer("TypeForTestingExpectedFunctionCall", &object); + foo.setConstObjectPointer("TypeForTestingExpectedFunctionCall", &object); CHECK(call->hasOutputParameter(foo)); } @@ -540,7 +751,7 @@ TEST(MockExpectedCall, hasNoOutputParameterOfTypeSameTypeButInput) TypeForTestingExpectedFunctionCall object(543); call->withParameterOfType("TypeForTestingExpectedFunctionCall", "foo", &object); MockNamedValue foo("foo"); - foo.setObjectPointer("TypeForTestingExpectedFunctionCall", &object); + foo.setConstObjectPointer("TypeForTestingExpectedFunctionCall", &object); CHECK_FALSE(call->hasOutputParameter(foo)); } @@ -549,184 +760,10 @@ TEST(MockExpectedCall, hasNoOutputParameterOfTypeDifferentType) TypeForTestingExpectedFunctionCall object(543); call->withOutputParameterOfTypeReturning("TypeForTestingExpectedFunctionCall", "foo", &object); MockNamedValue foo("foo"); - foo.setObjectPointer("OtherTypeForTestingExpectedFunctionCall", &object); + foo.setConstObjectPointer("OtherTypeForTestingExpectedFunctionCall", &object); CHECK_FALSE(call->hasOutputParameter(foo)); } -static MockExpectedCallComposite composite; - -TEST_GROUP(MockExpectedCallComposite) -{ - MockCheckedExpectedCall call; - - void setup() _override - { - composite.add(call); - composite.withName("name"); - } - - void teardown() _override - { - CHECK_NO_MOCK_FAILURE(); - composite.clear(); - } -}; - -TEST(MockExpectedCallComposite, hasBoolParameter) -{ - composite.withParameter("param", true); - STRCMP_EQUAL("name -> bool param: ", call.callToString().asCharString()); -} - -TEST(MockExpectedCallComposite, hasLongIntParameter) -{ - composite.withParameter("param", (long int) -1); - STRCMP_EQUAL("name -> long int param: <-1>", call.callToString().asCharString()); -} - -TEST(MockExpectedCallComposite, hasUnsignedLongIntParameter) -{ - composite.withParameter("param", (unsigned long int) 5); - STRCMP_EQUAL("name -> unsigned long int param: <5 (0x5)>", call.callToString().asCharString()); -} - -TEST(MockExpectedCallComposite, hasPointerParameter) -{ - composite.withParameter("param", (void*) 0); - STRCMP_EQUAL("name -> void* param: <0x0>", call.callToString().asCharString()); -} - -TEST(MockExpectedCallComposite, hasConstPointerParameter) -{ - composite.withParameter("param", (const void*) 0); - STRCMP_EQUAL("name -> const void* param: <0x0>", call.callToString().asCharString()); -} - -TEST(MockExpectedCallComposite, hasFunctionPointerParameter) -{ - composite.withParameter("param", (void (*)()) 0); - STRCMP_EQUAL("name -> void (*)() param: <0x0>", call.callToString().asCharString()); -} - -TEST(MockExpectedCallComposite, hasMemoryBufferParameter) -{ - const unsigned char mem_buffer[] = { 0x89, 0xFE, 0x15 }; - composite.withParameter("param", mem_buffer, sizeof(mem_buffer)); - STRCMP_EQUAL("name -> const unsigned char* param: ", call.callToString().asCharString()); -} - -TEST(MockExpectedCallComposite, hasParameterOfType) -{ - composite.withParameterOfType("type", "param", (const void*) 0); - STRCMP_EQUAL("name -> type param: ", call.callToString().asCharString()); -} - -TEST(MockExpectedCallComposite, hasOutputParameterReturning) -{ - composite.withOutputParameterReturning("out", (const void*) 0, 1); - STRCMP_EQUAL("name -> const void* out: ", call.callToString().asCharString()); -} - -TEST(MockExpectedCallComposite, hasOutputParameterOfTypeReturning) -{ - composite.withOutputParameterOfTypeReturning("type", "out", (const void*) 0); - STRCMP_EQUAL("name -> type out: ", call.callToString().asCharString()); -} - -TEST(MockExpectedCallComposite, hasBoolReturnValue) -{ - composite.andReturnValue(true); - STRCMP_EQUAL("bool", call.returnValue().getType().asCharString()); - CHECK_EQUAL(true, call.returnValue().getBoolValue()); -} - -TEST(MockExpectedCallComposite, hasUnsignedIntReturnValue) -{ - composite.andReturnValue((unsigned int) 2); - STRCMP_EQUAL("unsigned int", call.returnValue().getType().asCharString()); - LONGS_EQUAL(2, call.returnValue().getUnsignedIntValue()); -} - -TEST(MockExpectedCallComposite, hasIntReturnValue) -{ - composite.andReturnValue((int) -5); - STRCMP_EQUAL("int", call.returnValue().getType().asCharString()); - LONGS_EQUAL(-5, call.returnValue().getIntValue()); -} - -TEST(MockExpectedCallComposite, hasLongIntReturnValue) -{ - composite.andReturnValue((long int) -17); - STRCMP_EQUAL("long int", call.returnValue().getType().asCharString()); - LONGS_EQUAL(-17, call.returnValue().getLongIntValue()); -} - -TEST(MockExpectedCallComposite, hasUnsignedLongIntReturnValue) -{ - composite.andReturnValue((unsigned long int) 6); - STRCMP_EQUAL("unsigned long int", call.returnValue().getType().asCharString()); - LONGS_EQUAL(6, call.returnValue().getUnsignedLongIntValue()); -} - -TEST(MockExpectedCallComposite, hasDoubleReturnValue) -{ - composite.andReturnValue((double) 3.005); - STRCMP_EQUAL("double", call.returnValue().getType().asCharString()); - DOUBLES_EQUAL(3.005, call.returnValue().getDoubleValue(), 0.0001); -} - -TEST(MockExpectedCallComposite, hasStringReturnValue) -{ - composite.andReturnValue("hello"); - STRCMP_EQUAL("const char*", call.returnValue().getType().asCharString()); - STRCMP_EQUAL("hello", call.returnValue().getStringValue()); -} - -TEST(MockExpectedCallComposite, hasPointerReturnValue) -{ - composite.andReturnValue((void*) 0); - STRCMP_EQUAL("void*", call.returnValue().getType().asCharString()); - POINTERS_EQUAL((void*) 0, call.returnValue().getPointerValue()); -} - -TEST(MockExpectedCallComposite, hasConstPointerReturnValue) -{ - composite.andReturnValue((const void*) 0); - STRCMP_EQUAL("const void*", call.returnValue().getType().asCharString()); - POINTERS_EQUAL((const void*) 0, call.returnValue().getConstPointerValue()); -} - -TEST(MockExpectedCallComposite, hasFunctionPointerReturnValue) -{ - composite.andReturnValue((void(*)()) 0); - STRCMP_EQUAL("void (*)()", call.returnValue().getType().asCharString()); - FUNCTIONPOINTERS_EQUAL((void(*)()) 0, call.returnValue().getFunctionPointerValue()); -} - -TEST(MockExpectedCallComposite, isOnObject) -{ - composite.onObject(&composite); - SimpleString info("(object address: "); - info += StringFromFormat("%p", (void*) &composite); - info += ")::name -> no parameters"; - STRCMP_EQUAL(info.asCharString(), call.callToString().asCharString()); -} - -#include "CppUTest/TestTestingFixture.h" - -static void withCallOrderNotSupportedFailMethod_(void) -{ - composite.withCallOrder(5); -} // LCOV_EXCL_LINE - -TEST(MockExpectedCallComposite, doesNotSupportCallOrder) -{ - TestTestingFixture fixture; - fixture.setTestFunction(&withCallOrderNotSupportedFailMethod_); - fixture.runAllTests(); - fixture.assertPrintContains("withCallOrder not supported for CompositeCalls"); -} - TEST_GROUP(MockIgnoredExpectedCall) { MockIgnoredExpectedCall ignored; @@ -736,21 +773,28 @@ TEST(MockIgnoredExpectedCall, worksAsItShould) { ignored.withName("func"); ignored.withCallOrder(1); - ignored.onObject((void*) 0); + ignored.withCallOrder(1, 1); + ignored.onObject(NULLPTR); ignored.withBoolParameter("umm", true); ignored.withIntParameter("bla", (int) 1); ignored.withUnsignedIntParameter("foo", (unsigned int) 1); ignored.withLongIntParameter("hey", (long int) 1); ignored.withUnsignedLongIntParameter("bah", (unsigned long int) 1); +#if CPPUTEST_USE_LONG_LONG + ignored.withLongLongIntParameter("yo", (long long int) 1); + ignored.withUnsignedLongLongIntParameter("grr", (unsigned long long int) 1); +#endif ignored.withDoubleParameter("hah", (double) 1.1f); + ignored.withDoubleParameter("gah", 2.1, 0.3); ignored.withStringParameter("goo", "hello"); - ignored.withPointerParameter("pie", (void*) 0); - ignored.withConstPointerParameter("woo", (const void*) 0); - ignored.withFunctionPointerParameter("fop", (void(*)()) 0); - ignored.withMemoryBufferParameter("waa", (const unsigned char*) 0, 0); - ignored.withParameterOfType( "mytype", "top", (const void*) 0); - ignored.withOutputParameterReturning("bar", (void*) 0, 1); - ignored.withOutputParameterOfTypeReturning("mytype", "bar", (const void*) 0); + ignored.withPointerParameter("pie", (void*) NULLPTR); + ignored.withConstPointerParameter("woo", (const void*) NULLPTR); + ignored.withFunctionPointerParameter("fop", (void(*)()) NULLPTR); + ignored.withMemoryBufferParameter("waa", (const unsigned char*) NULLPTR, 0); + ignored.withParameterOfType( "mytype", "top", (const void*) NULLPTR); + ignored.withOutputParameterReturning("bar", (void*) NULLPTR, 1); + ignored.withOutputParameterOfTypeReturning("mytype", "bar", (const void*) NULLPTR); + ignored.withUnmodifiedOutputParameter("unmod"); ignored.ignoreOtherParameters(); ignored.andReturnValue(true); ignored.andReturnValue((double) 1.0f); @@ -758,8 +802,12 @@ TEST(MockIgnoredExpectedCall, worksAsItShould) ignored.andReturnValue((int) 1); ignored.andReturnValue((unsigned long int) 1); ignored.andReturnValue((long int) 1); +#if CPPUTEST_USE_LONG_LONG + ignored.andReturnValue((unsigned long long int) 1); + ignored.andReturnValue((long long int) 1); +#endif ignored.andReturnValue("boo"); - ignored.andReturnValue((void*) 0); - ignored.andReturnValue((const void*) 0); - ignored.andReturnValue((void(*)()) 0); + ignored.andReturnValue((void*) NULLPTR); + ignored.andReturnValue((const void*) NULLPTR); + ignored.andReturnValue((void(*)()) NULLPTR); } diff --git a/tests/CppUTestExt/MockFailureReporterForTest.cpp b/tests/CppUTestExt/MockFailureReporterForTest.cpp index 4e0b0cfb6..5330b7472 100644 --- a/tests/CppUTestExt/MockFailureReporterForTest.cpp +++ b/tests/CppUTestExt/MockFailureReporterForTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -32,10 +32,20 @@ void MockFailureReporterForTest::failTest(const MockFailure& failure) mockFailureString = failure.getMessage(); } +MockFailureReporterForTest* MockFailureReporterForTest::instance_ = NULLPTR; + MockFailureReporterForTest* MockFailureReporterForTest::getReporter() { - static MockFailureReporterForTest reporter; - return &reporter; + if (instance_ == NULLPTR) + instance_ = new MockFailureReporterForTest; + + return instance_; +} + +void MockFailureReporterForTest::clearReporter() +{ + delete instance_; + instance_ = NULLPTR; } MockFailureReporterInstaller::MockFailureReporterInstaller() @@ -45,7 +55,8 @@ MockFailureReporterInstaller::MockFailureReporterInstaller() MockFailureReporterInstaller::~MockFailureReporterInstaller() { - mock().setMockFailureStandardReporter(NULL); + mock().setMockFailureStandardReporter(NULLPTR); + MockFailureReporterForTest::clearReporter(); } UtestShell* mockFailureTest() @@ -63,7 +74,7 @@ void CLEAR_MOCK_FAILURE() MockFailureReporterForTest::getReporter()->mockFailureString = ""; } -void CHECK_EXPECTED_MOCK_FAILURE_LOCATION(const MockFailure& expectedFailure, const char* file, int line) +void CHECK_EXPECTED_MOCK_FAILURE_LOCATION(const MockFailure& expectedFailure, const char* file, size_t line) { SimpleString expectedFailureString = expectedFailure.getMessage(); SimpleString actualFailureString = mockFailureString(); @@ -79,7 +90,7 @@ void CHECK_EXPECTED_MOCK_FAILURE_LOCATION(const MockFailure& expectedFailure, co } } -void CHECK_NO_MOCK_FAILURE_LOCATION(const char* file, int line) +void CHECK_NO_MOCK_FAILURE_LOCATION(const char* file, size_t line) { if (mockFailureString() != "") { SimpleString error = "Unexpected mock failure:\n"; @@ -104,7 +115,15 @@ MockCheckedExpectedCall* MockExpectedCallsListForTest::addFunction(const SimpleS return newCall; } -MockCheckedExpectedCall* MockExpectedCallsListForTest::addFunction(const SimpleString& name, int order) +MockCheckedExpectedCall* MockExpectedCallsListForTest::addFunction(unsigned int numCalls, const SimpleString& name) +{ + MockCheckedExpectedCall* newCall = new MockCheckedExpectedCall(numCalls); + newCall->withName(name); + addExpectedCall(newCall); + return newCall; +} + +MockCheckedExpectedCall* MockExpectedCallsListForTest::addFunctionOrdered(const SimpleString& name, unsigned int order) { MockCheckedExpectedCall* newCall = addFunction(name); newCall->withCallOrder(order); diff --git a/tests/CppUTestExt/MockFailureReporterForTest.h b/tests/CppUTestExt/MockFailureReporterForTest.h index bbc58e793..f1b599f60 100644 --- a/tests/CppUTestExt/MockFailureReporterForTest.h +++ b/tests/CppUTestExt/MockFailureReporterForTest.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -38,8 +38,11 @@ class MockFailureReporterForTest : public MockFailureReporter public: SimpleString mockFailureString; - virtual void failTest(const MockFailure& failure); + virtual void failTest(const MockFailure& failure) CPPUTEST_OVERRIDE; static MockFailureReporterForTest* getReporter(); + static void clearReporter(); +private: + static MockFailureReporterForTest* instance_; }; class MockFailureReporterInstaller @@ -52,16 +55,16 @@ class MockFailureReporterInstaller UtestShell* mockFailureTest(); SimpleString mockFailureString(); void CLEAR_MOCK_FAILURE(); -void CHECK_EXPECTED_MOCK_FAILURE_LOCATION(const MockFailure& expectedFailure, const char* file, int line); -void CHECK_NO_MOCK_FAILURE_LOCATION(const char* file, int line); +void CHECK_EXPECTED_MOCK_FAILURE_LOCATION(const MockFailure& expectedFailure, const char* file, size_t line); +void CHECK_NO_MOCK_FAILURE_LOCATION(const char* file, size_t line); class MockExpectedCallsListForTest : public MockExpectedCallsList { public: - ~MockExpectedCallsListForTest(); + ~MockExpectedCallsListForTest() CPPUTEST_DESTRUCTOR_OVERRIDE; MockCheckedExpectedCall* addFunction(const SimpleString& name); - MockCheckedExpectedCall* addFunction(const SimpleString& name, int order); + MockCheckedExpectedCall* addFunction(unsigned int numCalls, const SimpleString& name); + MockCheckedExpectedCall* addFunctionOrdered(const SimpleString& name, unsigned int order); }; #endif - diff --git a/tests/CppUTestExt/MockFailureTest.cpp b/tests/CppUTestExt/MockFailureTest.cpp index 7e9b9e417..0e1aea2b5 100644 --- a/tests/CppUTestExt/MockFailureTest.cpp +++ b/tests/CppUTestExt/MockFailureTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -39,38 +39,65 @@ TEST_GROUP(MockFailureTest) MockCheckedExpectedCall* call1; MockCheckedExpectedCall* call2; MockCheckedExpectedCall* call3; + MockCheckedExpectedCall* call4; + MockCheckedExpectedCall* call5; - void setup () + void setup () CPPUTEST_OVERRIDE { list = new MockExpectedCallsList; call1 = new MockCheckedExpectedCall; call2 = new MockCheckedExpectedCall; call3 = new MockCheckedExpectedCall; + call4 = new MockCheckedExpectedCall; + call5 = new MockCheckedExpectedCall; } - void teardown () + void teardown () CPPUTEST_OVERRIDE { delete list; delete call1; delete call2; delete call3; + delete call4; + delete call5; CHECK_NO_MOCK_FAILURE(); + MockFailureReporterForTest::clearReporter(); } - void addAllToList() + + void addThreeCallsToList() + { + list->addExpectedCall(call1); + list->addExpectedCall(call2); + list->addExpectedCall(call3); + } + + void addFiveCallsToList() { list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); + list->addExpectedCall(call4); + list->addExpectedCall(call5); } void checkUnexpectedNthCallMessage(unsigned int count, const char* expectedOrdinal) { MockExpectedCallsList callList; - MockCheckedExpectedCall expCall; + MockCheckedExpectedCall expectedCallSingle(1); + MockCheckedExpectedCall expectedCallMulti(count-1); - expCall.withName("bar"); - for (unsigned int i = 0; i < (count - 1); i++) { - expCall.callWasMade(1); - callList.addExpectedCall(&expCall); + expectedCallSingle.withName("bar"); + expectedCallMulti.withName("bar"); + + if (count > 1) { + callList.addExpectedCall(&expectedCallSingle); + expectedCallSingle.callWasMade(1); + } + + if (count > 2) { + callList.addExpectedCall(&expectedCallMulti); + for (unsigned int i = 1; i < (count - 1); i++) { + expectedCallMulti.callWasMade(i+1); + } } MockUnexpectedCallHappenedFailure failure(UtestShell::getCurrent(), "bar", callList); @@ -90,9 +117,9 @@ TEST(MockFailureTest, unexpectedCallHappened) { MockUnexpectedCallHappenedFailure failure(UtestShell::getCurrent(), "foobar", *list); STRCMP_EQUAL("Mock Failure: Unexpected call to function: foobar\n" - "\tEXPECTED calls that did NOT happen:\n" + "\tEXPECTED calls that WERE NOT fulfilled:\n" "\t\t\n" - "\tACTUAL calls that did happen (in call order):\n" + "\tEXPECTED calls that WERE fulfilled:\n" "\t\t", failure.getMessage().asCharString()); } @@ -102,15 +129,15 @@ TEST(MockFailureTest, expectedCallDidNotHappen) call2->withName("world").withParameter("boo", 2).withParameter("hello", "world"); call3->withName("haphaphap"); call3->callWasMade(1); - addAllToList(); + addThreeCallsToList(); MockExpectedCallsDidntHappenFailure failure(UtestShell::getCurrent(), *list); - STRCMP_EQUAL("Mock Failure: Expected call did not happen.\n" - "\tEXPECTED calls that did NOT happen:\n" - "\t\tfoobar -> no parameters\n" - "\t\tworld -> int boo: <2>, const char* hello: \n" - "\tACTUAL calls that did happen (in call order):\n" - "\t\thaphaphap -> no parameters", failure.getMessage().asCharString()); + STRCMP_EQUAL("Mock Failure: Expected call WAS NOT fulfilled.\n" + "\tEXPECTED calls that WERE NOT fulfilled:\n" + "\t\tfoobar -> no parameters (expected 1 call, called 0 times)\n" + "\t\tworld -> int boo: <2 (0x2)>, const char* hello: (expected 1 call, called 0 times)\n" + "\tEXPECTED calls that WERE fulfilled:\n" + "\t\thaphaphap -> no parameters (expected 1 call, called 1 time)", failure.getMessage().asCharString()); } TEST(MockFailureTest, MockUnexpectedNthAdditionalCallFailure) @@ -132,20 +159,20 @@ TEST(MockFailureTest, MockUnexpectedInputParameterFailure) call1->withName("foo").withParameter("boo", 2); call2->withName("foo").withParameter("boo", 3.3); call3->withName("unrelated"); - addAllToList(); + addThreeCallsToList(); MockNamedValue actualParameter("bar"); actualParameter.setValue(2); MockUnexpectedInputParameterFailure failure(UtestShell::getCurrent(), "foo", actualParameter, *list); STRCMP_EQUAL("Mock Failure: Unexpected parameter name to function \"foo\": bar\n" - "\tEXPECTED calls that DID NOT happen related to function: foo\n" - "\t\tfoo -> int boo: <2>\n" - "\t\tfoo -> double boo: <3.3>\n" - "\tACTUAL calls that DID happen related to function: foo\n" + "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" + "\t\tfoo -> int boo: <2 (0x2)> (expected 1 call, called 0 times)\n" + "\t\tfoo -> double boo: <3.3> (expected 1 call, called 0 times)\n" + "\tEXPECTED calls that WERE fulfilled related to function: foo\n" "\t\t\n" "\tACTUAL unexpected parameter passed to function: foo\n" - "\t\tint bar: <2>", failure.getMessage().asCharString()); + "\t\tint bar: <2 (0x2)>", failure.getMessage().asCharString()); } TEST(MockFailureTest, MockUnexpectedOutputParameterFailure) @@ -155,17 +182,39 @@ TEST(MockFailureTest, MockUnexpectedOutputParameterFailure) call1->withName("foo").withOutputParameterReturning("boo", &out1, sizeof(out1)); call2->withName("foo").withOutputParameterReturning("boo", &out2, sizeof(out2)); call3->withName("unrelated"); - addAllToList(); + addThreeCallsToList(); MockNamedValue actualParameter("bar"); actualParameter.setValue((void *)0x123); MockUnexpectedOutputParameterFailure failure(UtestShell::getCurrent(), "foo", actualParameter, *list); STRCMP_EQUAL("Mock Failure: Unexpected output parameter name to function \"foo\": bar\n" - "\tEXPECTED calls that DID NOT happen related to function: foo\n" - "\t\tfoo -> const void* boo: \n" - "\t\tfoo -> const void* boo: \n" - "\tACTUAL calls that DID happen related to function: foo\n" + "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" + "\t\tfoo -> const void* boo: (expected 1 call, called 0 times)\n" + "\t\tfoo -> const void* boo: (expected 1 call, called 0 times)\n" + "\tEXPECTED calls that WERE fulfilled related to function: foo\n" + "\t\t\n" + "\tACTUAL unexpected output parameter passed to function: foo\n" + "\t\tvoid* bar", failure.getMessage().asCharString()); +} + +TEST(MockFailureTest, MockUnexpectedUnmodifiedOutputParameterFailure) +{ + int out1; + call1->withName("foo").withOutputParameterReturning("boo", &out1, sizeof(out1)); + call2->withName("foo").withUnmodifiedOutputParameter("boo"); + call3->withName("unrelated"); + addThreeCallsToList(); + + MockNamedValue actualParameter("bar"); + actualParameter.setValue((void *)0x123); + + MockUnexpectedOutputParameterFailure failure(UtestShell::getCurrent(), "foo", actualParameter, *list); + STRCMP_EQUAL("Mock Failure: Unexpected output parameter name to function \"foo\": bar\n" + "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" + "\t\tfoo -> const void* boo: (expected 1 call, called 0 times)\n" + "\t\tfoo -> const void* boo: (expected 1 call, called 0 times)\n" + "\tEXPECTED calls that WERE fulfilled related to function: foo\n" "\t\t\n" "\tACTUAL unexpected output parameter passed to function: foo\n" "\t\tvoid* bar", failure.getMessage().asCharString()); @@ -176,40 +225,54 @@ TEST(MockFailureTest, MockUnexpectedParameterValueFailure) call1->withName("foo").withParameter("boo", 2); call2->withName("foo").withParameter("boo", 10); call3->withName("unrelated"); - addAllToList(); + addThreeCallsToList(); MockNamedValue actualParameter("boo"); actualParameter.setValue(20); MockUnexpectedInputParameterFailure failure(UtestShell::getCurrent(), "foo", actualParameter, *list); - STRCMP_EQUAL("Mock Failure: Unexpected parameter value to parameter \"boo\" to function \"foo\": <20>\n" - "\tEXPECTED calls that DID NOT happen related to function: foo\n" - "\t\tfoo -> int boo: <2>\n" - "\t\tfoo -> int boo: <10>\n" - "\tACTUAL calls that DID happen related to function: foo\n" + STRCMP_EQUAL("Mock Failure: Unexpected parameter value to parameter \"boo\" to function \"foo\": <20 (0x14)>\n" + "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" + "\t\tfoo -> int boo: <2 (0x2)> (expected 1 call, called 0 times)\n" + "\t\tfoo -> int boo: <10 (0xa)> (expected 1 call, called 0 times)\n" + "\tEXPECTED calls that WERE fulfilled related to function: foo\n" "\t\t\n" "\tACTUAL unexpected parameter passed to function: foo\n" - "\t\tint boo: <20>", failure.getMessage().asCharString()); + "\t\tint boo: <20 (0x14)>", failure.getMessage().asCharString()); } TEST(MockFailureTest, MockExpectedParameterDidntHappenFailure) { call1->withName("foo").withParameter("bar", 2).withParameter("boo", "str"); + call1->inputParameterWasPassed("bar"); call2->withName("foo").withParameter("bar", 10).withParameter("boo", "bleh"); call2->callWasMade(1); call2->inputParameterWasPassed("bar"); call2->inputParameterWasPassed("boo"); - call3->withName("unrelated"); - addAllToList(); + call3->withName("foo").withParameter("bar", 2).withParameter("boo", "blah").withParameter("baa", 0u); + call3->inputParameterWasPassed("bar"); + call4->withName("foo").withParameter("bar", 20); + call5->withName("unrelated"); + addFiveCallsToList(); + + MockExpectedCallsList matchingCalls; + matchingCalls.addExpectedCall(call1); + matchingCalls.addExpectedCall(call3); - MockExpectedParameterDidntHappenFailure failure(UtestShell::getCurrent(), "foo", *list); + MockExpectedParameterDidntHappenFailure failure(UtestShell::getCurrent(), "foo", *list, matchingCalls); STRCMP_EQUAL("Mock Failure: Expected parameter for function \"foo\" did not happen.\n" - "\tEXPECTED calls that DID NOT happen related to function: foo\n" - "\t\tfoo -> int bar: <2>, const char* boo: \n" - "\tACTUAL calls that DID happen related to function: foo\n" - "\t\tfoo -> int bar: <10>, const char* boo: \n" - "\tMISSING parameters that didn't happen:\n" - "\t\tint bar, const char* boo", failure.getMessage().asCharString()); + "\tEXPECTED calls with MISSING parameters related to function: foo\n" + "\t\tfoo -> int bar: <2 (0x2)>, const char* boo: (expected 1 call, called 0 times)\n" + "\t\t\tMISSING parameters: const char* boo\n" + "\t\tfoo -> int bar: <2 (0x2)>, const char* boo: , unsigned int baa: <0 (0x0)> (expected 1 call, called 0 times)\n" + "\t\t\tMISSING parameters: const char* boo, unsigned int baa\n" + "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" + "\t\tfoo -> int bar: <2 (0x2)>, const char* boo: (expected 1 call, called 0 times)\n" + "\t\tfoo -> int bar: <2 (0x2)>, const char* boo: , unsigned int baa: <0 (0x0)> (expected 1 call, called 0 times)\n" + "\t\tfoo -> int bar: <20 (0x14)> (expected 1 call, called 0 times)\n" + "\tEXPECTED calls that WERE fulfilled related to function: foo\n" + "\t\tfoo -> int bar: <10 (0xa)>, const char* boo: (expected 1 call, called 1 time)", + failure.getMessage().asCharString()); } TEST(MockFailureTest, MockNoWayToCompareCustomTypeFailure) @@ -225,16 +288,16 @@ TEST(MockFailureTest, MockUnexpectedObjectFailure) call2->callWasMade(1); call2->wasPassedToObject(); call3->withName("unrelated"); - addAllToList(); + addThreeCallsToList(); MockUnexpectedObjectFailure failure(UtestShell::getCurrent(), "foo", (void*)0x1, *list); STRCMP_EQUAL(StringFromFormat ( "MockFailure: Function called on an unexpected object: foo\n" "\tActual object for call has address: <%p>\n" - "\tEXPECTED calls that DID NOT happen related to function: foo\n" - "\t\t(object address: %p)::foo -> no parameters\n" - "\tACTUAL calls that DID happen related to function: foo\n" - "\t\t(object address: %p)::foo -> no parameters", + "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" + "\t\t(object address: %p)::foo -> no parameters (expected 1 call, called 0 times)\n" + "\tEXPECTED calls that WERE fulfilled related to function: foo\n" + "\t\t(object address: %p)::foo -> no parameters (expected 1 call, called 1 time)", (void*) 0x01, (void*) 0x02, (void*) 0x03).asCharString(), failure.getMessage().asCharString()); } @@ -245,14 +308,14 @@ TEST(MockFailureTest, MockExpectedObjectDidntHappenFailure) call2->callWasMade(1); call2->wasPassedToObject(); call3->withName("unrelated"); - addAllToList(); + addThreeCallsToList(); MockExpectedObjectDidntHappenFailure failure(UtestShell::getCurrent(), "foo", *list); STRCMP_EQUAL(StringFromFormat( "Mock Failure: Expected call on object for function \"foo\" but it did not happen.\n" - "\tEXPECTED calls that DID NOT happen related to function: foo\n" - "\t\t(object address: %p)::foo -> no parameters\n" - "\tACTUAL calls that DID happen related to function: foo\n" - "\t\t(object address: %p)::foo -> no parameters", + "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" + "\t\t(object address: %p)::foo -> no parameters (expected 1 call, called 0 times)\n" + "\tEXPECTED calls that WERE fulfilled related to function: foo\n" + "\t\t(object address: %p)::foo -> no parameters (expected 1 call, called 1 time)", (void*) 0x2, (void*) 0x3).asCharString(), failure.getMessage().asCharString()); } diff --git a/tests/CppUTestExt/MockFakeLongLong.cpp b/tests/CppUTestExt/MockFakeLongLong.cpp new file mode 100644 index 000000000..e0cd1a61b --- /dev/null +++ b/tests/CppUTestExt/MockFakeLongLong.cpp @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "CppUTest/TestHarness.h" +#include "CppUTest/TestOutput.h" +#include "CppUTest/TestTestingFixture.h" +#include "CppUTestExt/MockCheckedActualCall.h" +#include "CppUTestExt/MockCheckedExpectedCall.h" +#include "CppUTestExt/MockExpectedCallsList.h" +#include "CppUTestExt/MockFailure.h" +#include "MockFailureReporterForTest.h" + + +TEST_GROUP(FakeLongLongs) +{ + TestTestingFixture fixture; +}; + +#ifndef CPPUTEST_USE_LONG_LONG + +#define CHECK_TEST_FAILS_PROPER_WITH_TEXT(text) fixture.checkTestFailsWithProperTestLocation(text, __FILE__, __LINE__) + +static void actualCallWithFakeLongLongParameter_() +{ + cpputest_longlong value = {0}; + + mock().expectOneCall("foo").withParameter("bar", 0); + mock().actualCall("foo").withParameter("bar", value); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(FakeLongLongs, ActualCallWithFakeLongLongParameterFAILS) +{ + fixture.runTestWithMethod(actualCallWithFakeLongLongParameter); + mock().clear(); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported"); +} + +static void actualCallWithFakeUnsignedLongLongParameter_() +{ + cpputest_ulonglong value = {0}; + + mock().expectOneCall("foo").withParameter("bar", 0); + mock().actualCall("foo").withParameter("bar", value); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(FakeLongLongs, ActualCallWithFakeUnsignedLongLongParameterFAILS) +{ + fixture.runTestWithMethod(actualCallWithFakeUnsignedLongLongParameter_); + mock().clear(); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported"); +} + +static void actualCallWithFakeLongLongReturn_() +{ + mock().expectOneCall("foo").andReturnValue(0); + mock().actualCall("foo").returnLongLongIntValue(); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(FakeLongLongs, ActualCallWithFakeLongLongReturnFAILS) +{ + fixture.runTestWithMethod(actualCallWithFakeLongLongReturn_); + mock().clear(); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported"); +} + +static void actualCallWithFakeUnsignedLongLongReturn_() +{ + mock().expectOneCall("foo").andReturnValue(0); + mock().actualCall("foo").returnUnsignedLongLongIntValue(); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(FakeLongLongs, ActualCallWithFakeUnsignedLongLongReturnFAILS) +{ + fixture.runTestWithMethod(actualCallWithFakeUnsignedLongLongReturn_); + mock().clear(); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported"); +} + +static void expectOneCallWithFakeLongLongParameter_() +{ + cpputest_longlong value = {0}; + + mock().expectOneCall("foo").withParameter("bar", value); + mock().actualCall("foo").withParameter("bar", 0); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(FakeLongLongs, ExpectedCallWithFakeLongLongParameterFAILS) +{ + fixture.runTestWithMethod(expectOneCallWithFakeLongLongParameter_); + mock().clear(); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported"); +} + +static void expectOneCallWithFakeUnsignedLongLongParameter_() +{ + cpputest_ulonglong value = {0}; + + mock().expectOneCall("foo").withParameter("bar", value); + mock().actualCall("foo").withParameter("bar", 0); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(FakeLongLongs, ExpectedCallWithFakeUnsignedLongLongParameterFAILS) +{ + fixture.runTestWithMethod(expectOneCallWithFakeUnsignedLongLongParameter_); + mock().clear(); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported"); +} + +static void expectOneCallWithFakeLongLongReturn_() +{ + cpputest_longlong value = {0}; + + mock().expectOneCall("foo").andReturnValue(value); + mock().actualCall("foo").returnIntValue(); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(FakeLongLongs, ExpectedCallWithFakeLongLongReturnFAILS) +{ + fixture.runTestWithMethod(expectOneCallWithFakeLongLongReturn_); + mock().clear(); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported"); +} + +static void expectOneCallWithFakeUnsignedLongLongReturn_() +{ + cpputest_ulonglong value = {0}; + + mock().expectOneCall("foo").andReturnValue(value); + mock().actualCall("foo").returnIntValue(); + TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE +} // LCOV_EXCL_LINE + +TEST(FakeLongLongs, ExpectedCallWithFakeUnsignedLongLongReturnFAILS) +{ + fixture.runTestWithMethod(expectOneCallWithFakeUnsignedLongLongReturn_); + mock().clear(); + CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported"); +} + +#endif diff --git a/tests/CppUTestExt/MockHierarchyTest.cpp b/tests/CppUTestExt/MockHierarchyTest.cpp index 800ec74dc..8ee5901df 100644 --- a/tests/CppUTestExt/MockHierarchyTest.cpp +++ b/tests/CppUTestExt/MockHierarchyTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,6 +30,10 @@ TEST_GROUP(MockHierarchyTest) { + void teardown() CPPUTEST_OVERRIDE + { + mock().clear(); + } }; TEST(MockHierarchyTest, getMockSupportScope) @@ -128,7 +132,7 @@ TEST(MockHierarchyTest, checkExpectationsWorksHierarchicallyForLastCallNotFinish MockExpectedCallsListForTest expectations; expectations.addFunction("first::foobar")->withParameter("boo", 1); - MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "first::foobar", expectations); + MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "first::foobar", expectations, expectations); mock("first").expectOneCall("foobar").withParameter("boo", 1); mock("first").actualCall("foobar"); @@ -147,4 +151,3 @@ TEST(MockHierarchyTest, reporterIsInheritedInHierarchicalMocks) MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "differentScope::foobar", expectations); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } - diff --git a/tests/CppUTestExt/MockNamedValueTest.cpp b/tests/CppUTestExt/MockNamedValueTest.cpp index f54d9ffb7..0a0286f8f 100644 --- a/tests/CppUTestExt/MockNamedValueTest.cpp +++ b/tests/CppUTestExt/MockNamedValueTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -37,10 +37,10 @@ class MyComparator : public MockNamedValueComparator public: MyComparator() {} - virtual ~MyComparator() {} + virtual ~MyComparator() CPPUTEST_DESTRUCTOR_OVERRIDE {} - virtual bool isEqual(const void*, const void*) _override { return false; } - virtual SimpleString valueToString(const void*) _override { return ""; } + virtual bool isEqual(const void*, const void*) CPPUTEST_OVERRIDE { return false; } + virtual SimpleString valueToString(const void*) CPPUTEST_OVERRIDE { return ""; } }; class MyCopier : public MockNamedValueCopier @@ -48,9 +48,9 @@ class MyCopier : public MockNamedValueCopier public: MyCopier() {} - virtual ~MyCopier() {} + virtual ~MyCopier() CPPUTEST_DESTRUCTOR_OVERRIDE {} - virtual void copy(void*, const void*) _override {} + virtual void copy(void*, const void*) CPPUTEST_OVERRIDE {} }; TEST(ComparatorsAndCopiersRepository, InstallCopierAndRetrieveIt) @@ -74,3 +74,68 @@ TEST(ComparatorsAndCopiersRepository, ComparatorAndCopierByTheSameNameShouldBoth repository.clear(); } +TEST(ComparatorsAndCopiersRepository, InstallComparatorsAndCopiersFromRepository) +{ + MyComparator comparator; + MyCopier copier; + MockNamedValueComparatorsAndCopiersRepository source; + MockNamedValueComparatorsAndCopiersRepository target; + + source.installCopier("MyType", copier); + source.installComparator("MyType", comparator); + + target.installComparatorsAndCopiers(source); + + POINTERS_EQUAL(&comparator, target.getComparatorForType("MyType")); + POINTERS_EQUAL(&copier, target.getCopierForType("MyType")); + + source.clear(); + target.clear(); +} + +TEST_GROUP(MockNamedValue) +{ + MockNamedValue * value; + void setup() CPPUTEST_OVERRIDE + { + value = new MockNamedValue("param"); + } + + void teardown() CPPUTEST_OVERRIDE + { + delete value; + } +}; + +TEST(MockNamedValue, DefaultToleranceUsedWhenNoToleranceGiven) +{ + value->setValue(0.2); + DOUBLES_EQUAL(MockNamedValue::defaultDoubleTolerance, value->getDoubleTolerance(), 0.0); +} + +TEST(MockNamedValue, GivenToleranceUsed) +{ + value->setValue(0.2, 3.2); + STRCMP_EQUAL("double", value->getType().asCharString()); + DOUBLES_EQUAL(0.2, value->getDoubleValue(), 0.0); + DOUBLES_EQUAL(3.2, value->getDoubleTolerance(), 0.0); +} + +TEST(MockNamedValue, DoublesEqualIfWithinTolerance) +{ + value->setValue(5.0, 0.4); + MockNamedValue other("param2"); + other.setValue(5.3); + + CHECK_TRUE(value->equals(other)); +} + + +TEST(MockNamedValue, DoublesNotEqualIfOutsideTolerance) +{ + value->setValue(5.0, 0.4); + MockNamedValue other("param2"); + other.setValue(5.5); + + CHECK_FALSE(value->equals(other)); +} diff --git a/tests/CppUTestExt/MockParameterTest.cpp b/tests/CppUTestExt/MockParameterTest.cpp index 64f6d15f6..54f719662 100644 --- a/tests/CppUTestExt/MockParameterTest.cpp +++ b/tests/CppUTestExt/MockParameterTest.cpp @@ -14,7 +14,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -31,9 +31,10 @@ TEST_GROUP(MockParameterTest) { - void teardown() + void teardown() CPPUTEST_OVERRIDE { - mock().checkExpectations(); + mock().checkExpectations(); + mock().clear(); } }; @@ -62,6 +63,29 @@ TEST(MockParameterTest, expectOneIntegerParameterAndValue) mock().checkExpectations(); } +#if CPPUTEST_USE_LONG_LONG + +TEST(MockParameterTest, expectOneUnsignedLongLongIntegerParameterAndValue) +{ + unsigned long long value = 0xFFFFAAAAFFFFAAAAULL; + mock().expectOneCall("foo").withParameter("parameter", value); + mock().actualCall("foo").withParameter("parameter", value); + + mock().checkExpectations(); +} + +TEST(MockParameterTest, expectOneLongLongIntegerParameterAndValue) +{ + long long value = 0x7FFFAAAAFFFFAAAAULL; + + mock().expectOneCall("foo").withParameter("parameter", value); + mock().actualCall("foo").withParameter("parameter", value); + + mock().checkExpectations(); +} + +#endif + TEST(MockParameterTest, mismatchedIntegerTypesIntAndLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (int)1); @@ -128,6 +152,109 @@ TEST(MockParameterTest, mismatchedIntegerTypesLongAndUnsignedLongAreAllowed) mock().checkExpectations(); } +#if CPPUTEST_USE_LONG_LONG + +TEST(MockParameterTest, mismatchedIntegerTypesIntAndLongLongAreAllowed) +{ + mock().expectOneCall("foo").withParameter("parameter", (int)1); + mock().actualCall("foo").withParameter("parameter", (long long)1); + + mock().expectOneCall("foo").withParameter("parameter", (long long)1); + mock().actualCall("foo").withParameter("parameter", (int)1); + + mock().checkExpectations(); +} + +TEST(MockParameterTest, mismatchedIntegerTypesIntAndUnsignedLongLongAreAllowed) +{ + mock().expectOneCall("foo").withParameter("parameter", (int)1); + mock().actualCall("foo").withParameter("parameter", (unsigned long long)1); + + mock().expectOneCall("foo").withParameter("parameter", (unsigned long long)1); + mock().actualCall("foo").withParameter("parameter", (int)1); + + mock().checkExpectations(); +} + +TEST(MockParameterTest, mismatchedIntegerTypesUnsignedAndLongLongAreAllowed) +{ + mock().expectOneCall("foo").withParameter("parameter", (unsigned)1); + mock().actualCall("foo").withParameter("parameter", (long long)1); + + mock().expectOneCall("foo").withParameter("parameter", (long long)1); + mock().actualCall("foo").withParameter("parameter", (unsigned)1); + + mock().checkExpectations(); +} + +TEST(MockParameterTest, mismatchedIntegerTypesUnsignedAndUnsignedLongLongAreAllowed) +{ + mock().expectOneCall("foo").withParameter("parameter", (unsigned)1); + mock().actualCall("foo").withParameter("parameter", (unsigned long long)1); + + mock().expectOneCall("foo").withParameter("parameter", (unsigned long long)1); + mock().actualCall("foo").withParameter("parameter", (unsigned)1); + + mock().checkExpectations(); +} + +TEST(MockParameterTest, mismatchedIntegerTypesUnsignedLongAndUnsignedLongLongAreAllowed) +{ + mock().expectOneCall("foo").withParameter("parameter", (unsigned long)1); + mock().actualCall("foo").withParameter("parameter", (unsigned long long)1); + + mock().expectOneCall("foo").withParameter("parameter", (unsigned long long)1); + mock().actualCall("foo").withParameter("parameter", (unsigned long)1); + + mock().checkExpectations(); +} + +TEST(MockParameterTest, mismatchedIntegerTypesLongAndLongLongAreAllowed) +{ + mock().expectOneCall("foo").withParameter("parameter", (long)1); + mock().actualCall("foo").withParameter("parameter", (long long)1); + + mock().expectOneCall("foo").withParameter("parameter", (long long)1); + mock().actualCall("foo").withParameter("parameter", (long)1); + + mock().checkExpectations(); +} + +TEST(MockParameterTest, mismatchedIntegerTypesLongAndUnsignedLongLongAreAllowed) +{ + mock().expectOneCall("foo").withParameter("parameter", (long)1); + mock().actualCall("foo").withParameter("parameter", (unsigned long long)1); + + mock().expectOneCall("foo").withParameter("parameter", (unsigned long long)1); + mock().actualCall("foo").withParameter("parameter", (long)1); + + mock().checkExpectations(); +} + +TEST(MockParameterTest, mismatchedIntegerTypesUnsignedLongAndLongLongAreAllowed) +{ + mock().expectOneCall("foo").withParameter("parameter", (unsigned long)1); + mock().actualCall("foo").withParameter("parameter", (long long)1); + + mock().expectOneCall("foo").withParameter("parameter", (long long)1); + mock().actualCall("foo").withParameter("parameter", (unsigned long)1); + + mock().checkExpectations(); +} + +TEST(MockParameterTest, mismatchedIntegerTypesLongLongAndUnsignedLongLongAreAllowed) +{ + mock().expectOneCall("foo").withParameter("parameter", (long long)1); + mock().actualCall("foo").withParameter("parameter", (unsigned long long)1); + + mock().expectOneCall("foo").withParameter("parameter", (unsigned long long)1); + mock().actualCall("foo").withParameter("parameter", (long long)1); + + mock().checkExpectations(); +} + +#endif + TEST(MockParameterTest, longAndUnsignedLongWithSameBitRepresentationShouldNotBeTreatedAsEqual) { MockFailureReporterInstaller failureReporterInstaller; @@ -168,6 +295,31 @@ TEST(MockParameterTest, expectOneDoubleParameterAndValue) mock().checkExpectations(); } +TEST(MockParameterTest, expectOneDoubleParameterAndValueAndTolerance) +{ + mock( ).expectOneCall("foo").withParameter("parameter", 100.0, 5.0); + mock( ).actualCall("foo").withParameter("parameter", 96.0); + + mock( ).checkExpectations(); +} + +TEST(MockParameterTest, doubleParameterNotEqualIfOutsideTolerance) +{ + MockFailureReporterInstaller failureReporterInstaller; + + MockExpectedCallsListForTest expectations; + expectations.addFunction("foo")->withParameter("parameter", 100.0); + MockNamedValue parameter("parameter"); + parameter.setValue(106.0); + MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); + + mock( ).expectOneCall("foo").withParameter("parameter", 100.0, 5.0); + mock( ).actualCall("foo").withParameter("parameter", 106.0); + + CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); +} + + TEST(MockParameterTest, expectOneStringParameterAndValue) { mock().expectOneCall("foo").withParameter("parameter", "string"); @@ -383,7 +535,7 @@ TEST(MockParameterTest, calledWithoutParameters) MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("p1", 1); - MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations); + MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations, expectations); mock().expectOneCall("foo").withParameter("p1", 1); mock().actualCall("foo"); @@ -414,7 +566,7 @@ TEST(MockParameterTest, ignoreOtherParametersButExpectedParameterDidntHappen) MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("p1", 1).ignoreOtherParameters(); - MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations); + MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations, expectations); mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters(); mock().actualCall("foo").withParameter("p2", 2).withParameter("p3", 3).withParameter("p4", 4); @@ -442,7 +594,7 @@ TEST(MockParameterTest, ignoreOtherParametersMultipleCallsButOneDidntHappen) MockCheckedExpectedCall* call = expectations.addFunction("boo"); call->ignoreOtherParameters(); call->callWasMade(1); - call->parametersWereIgnored(); + call->finalizeActualCallMatch(); call->ignoreOtherParameters(); expectations.addFunction("boo")->ignoreOtherParameters(); MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); @@ -461,11 +613,11 @@ TEST(MockParameterTest, newCallStartsWhileNotAllParametersWerePassed) MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("p1", 1); - MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations); + MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations, expectations); mock().expectOneCall("foo").withParameter("p1", 1); mock().actualCall("foo"); - mock().actualCall("foo").withParameter("p1", 1);; + mock().actualCall("foo").withParameter("p1", 1); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } @@ -483,6 +635,17 @@ TEST(MockParameterTest, outputParameterSucceeds) mock().checkExpectations(); } +TEST(MockParameterTest, unmodifiedOutputParameterSucceeds) +{ + int param = 1; + + mock().expectOneCall("function").withUnmodifiedOutputParameter("parameterName"); + mock().actualCall("function").withOutputParameter("parameterName", ¶m); + + CHECK_EQUAL(param, 1); + mock().checkExpectations(); +} + TEST(MockParameterTest, noActualCallForOutputParameter) { MockFailureReporterInstaller failureReporterInstaller; @@ -498,6 +661,20 @@ TEST(MockParameterTest, noActualCallForOutputParameter) CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } +TEST(MockParameterTest, noActualCallForUnmodifiedOutputParameter) +{ + MockFailureReporterInstaller failureReporterInstaller; + + MockExpectedCallsListForTest expectations; + mock().expectOneCall("foo").withUnmodifiedOutputParameter("output"); + + expectations.addFunction("foo")->withUnmodifiedOutputParameter("output"); + MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); + + mock().checkExpectations(); + CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); +} + TEST(MockParameterTest, unexpectedOutputParameter) { MockFailureReporterInstaller failureReporterInstaller; @@ -526,7 +703,7 @@ TEST(MockParameterTest, outputParameterMissing) mock().actualCall("foo"); expectations.addFunction("foo")->withOutputParameterReturning("output", &output, sizeof(output)); - MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations); + MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations, expectations); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); @@ -678,6 +855,29 @@ TEST(MockParameterTest, outputParameterWithIgnoredParameters) mock().actualCall("foo").withOutputParameter("bar", &retval).withParameter("other", 1); LONGS_EQUAL(param, retval); + + mock().checkExpectations(); +} + +/* + * This test checks that the proper output parameters are copied when multiple calls to the same + * function are expected. + */ +TEST(MockParameterTest, properOutputParametersAreCopied) +{ + int expectedValue1 = 1; + int expectedValue2 = 2; + mock().expectOneCall("foo").withOutputParameterReturning("param", &expectedValue1, sizeof(expectedValue1)).ignoreOtherParameters(); + mock().expectOneCall("foo").withOutputParameterReturning("param", &expectedValue2, sizeof(expectedValue2)); + + int returnedValue1 = 0; + int returnedValue2 = 0; + mock().actualCall("foo").withOutputParameter("param", &returnedValue1); + mock().actualCall("foo").withOutputParameter("param", &returnedValue2).withParameter("optional", 50); + + CHECK_EQUAL_TEXT(expectedValue2, returnedValue1, "Wrong output value in 1st call"); + CHECK_EQUAL_TEXT(expectedValue1, returnedValue2, "Wrong output value in 2nd call"); + mock().checkExpectations(); } @@ -689,13 +889,17 @@ TEST(MockParameterTest, ignoreOtherCallsIgnoresWithAllKindsOfParameters) .withParameter("bar", 1u) .withParameter("foo", 1l) .withParameter("hey", 1ul) +#if CPPUTEST_USE_LONG_LONG + .withParameter("ick", 1ll) + .withParameter("grr", 1ull) +#endif .withParameter("duh", 1.0) - .withParameter("yoo", (const void*) 0) - .withParameter("func", (void(*)()) 0) - .withParameter("mem", (const unsigned char*) 0, 0) - .withParameterOfType("hoo", "int", (const void*) 0) - .withOutputParameter("gah", (void*) 0) - .withOutputParameterOfType("goo", "int", (void*) 0); + .withParameter("yoo", (const void*) NULLPTR) + .withParameter("func", (void(*)()) NULLPTR) + .withParameter("mem", (const unsigned char*) NULLPTR, 0) + .withParameterOfType("hoo", "int", (const void*) NULLPTR) + .withOutputParameter("gah", (void*) NULLPTR) + .withOutputParameterOfType("goo", "int", (void*) NULLPTR); mock().checkExpectations(); } @@ -726,4 +930,3 @@ TEST(MockParameterTest, expectMultipleMultipleCallsWithParameters) mock().checkExpectations(); } - diff --git a/tests/CppUTestExt/MockPluginTest.cpp b/tests/CppUTestExt/MockPluginTest.cpp index ae1739b86..e3c13a20b 100644 --- a/tests/CppUTestExt/MockPluginTest.cpp +++ b/tests/CppUTestExt/MockPluginTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -40,16 +40,18 @@ TEST_GROUP(MockPlugin) MockSupportPlugin plugin; - void setup() + void setup() CPPUTEST_OVERRIDE { test = new UtestShell("group", "name", "file", 1); result = new TestResult(output); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete test; delete result; + mock().clear(); + mock().removeAllComparatorsAndCopiers(); } }; @@ -65,7 +67,7 @@ TEST(MockPlugin, checkExpectationsAndClearAtEnd) plugin.postTestAction(*test, *result); - STRCMP_CONTAINS(expectedFailure.getMessage().asCharString(), output.getOutput().asCharString()) + STRCMP_CONTAINS(expectedFailure.getMessage().asCharString(), output.getOutput().asCharString()); LONGS_EQUAL(0, mock().expectedCallsLeft()); CHECK_NO_MOCK_FAILURE(); } @@ -83,18 +85,18 @@ TEST(MockPlugin, checkExpectationsWorksAlsoWithHierachicalObjects) plugin.postTestAction(*test, *result); - STRCMP_CONTAINS(expectedFailure.getMessage().asCharString(), output.getOutput().asCharString()) + STRCMP_CONTAINS(expectedFailure.getMessage().asCharString(), output.getOutput().asCharString()); CHECK_NO_MOCK_FAILURE(); } class DummyComparator : public MockNamedValueComparator { public: - bool isEqual(const void* object1, const void* object2) + bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { return object1 == object2; } - SimpleString valueToString(const void*) + SimpleString valueToString(const void*) CPPUTEST_OVERRIDE { return "string"; } @@ -106,17 +108,19 @@ TEST(MockPlugin, installComparatorRecordsTheComparatorButNotInstallsItYet) DummyComparator comparator; plugin.installComparator("myType", comparator); - mock().expectOneCall("foo").withParameterOfType("myType", "name", NULL); - mock().actualCall("foo").withParameterOfType("myType", "name", NULL); + mock().expectOneCall("foo").withParameterOfType("myType", "name", NULLPTR); + mock().actualCall("foo").withParameterOfType("myType", "name", NULLPTR); MockNoWayToCompareCustomTypeFailure failure(test, "myType"); CHECK_EXPECTED_MOCK_FAILURE(failure); + + plugin.clear(); } class DummyCopier : public MockNamedValueCopier { public: - void copy(void* dst, const void* src) + void copy(void* dst, const void* src) CPPUTEST_OVERRIDE { *(int*)dst = *(const int*)src; } @@ -128,11 +132,13 @@ TEST(MockPlugin, installCopierRecordsTheCopierButNotInstallsItYet) DummyCopier copier; plugin.installCopier("myType", copier); - mock().expectOneCall("foo").withOutputParameterOfTypeReturning("myType", "name", NULL); - mock().actualCall("foo").withOutputParameterOfType("myType", "name", NULL); + mock().expectOneCall("foo").withOutputParameterOfTypeReturning("myType", "name", NULLPTR); + mock().actualCall("foo").withOutputParameterOfType("myType", "name", NULLPTR); MockNoWayToCopyCustomTypeFailure failure(test, "myType"); CHECK_EXPECTED_MOCK_FAILURE(failure); + + plugin.clear(); } TEST(MockPlugin, preTestActionWillEnableMultipleComparatorsToTheGlobalMockSupportSpace) @@ -150,9 +156,11 @@ TEST(MockPlugin, preTestActionWillEnableMultipleComparatorsToTheGlobalMockSuppor mock().checkExpectations(); LONGS_EQUAL(0, result->getFailureCount()); + + plugin.clear(); } -static void _failTwiceFunction() +static void failTwiceFunction_() { mock().expectOneCall("foobar"); FAIL("This failed"); @@ -161,9 +169,8 @@ static void _failTwiceFunction() TEST(MockPlugin, shouldNotFailAgainWhenTestAlreadyFailed) { TestTestingFixture fixture; - fixture.registry_->installPlugin(&plugin); - fixture.setTestFunction(_failTwiceFunction); + fixture.installPlugin(&plugin); + fixture.setTestFunction(failTwiceFunction_); fixture.runAllTests(); fixture.assertPrintContains("1 failures, 1 tests, 1 ran, 2 checks,"); } - diff --git a/tests/CppUTestExt/MockReturnValueTest.cpp b/tests/CppUTestExt/MockReturnValueTest.cpp index afeff76d5..e99890605 100644 --- a/tests/CppUTestExt/MockReturnValueTest.cpp +++ b/tests/CppUTestExt/MockReturnValueTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,9 +30,10 @@ TEST_GROUP(MockReturnValueTest) { - void teardown() + void teardown() CPPUTEST_OVERRIDE { - mock().checkExpectations(); + mock().checkExpectations(); + mock().clear(); } }; @@ -105,6 +106,87 @@ TEST(MockReturnValueTest, UnsignedIntReturnValueCanBeRetrievedAsUnsignedLongInt) UNSIGNED_LONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongIntValue()); } +#if CPPUTEST_USE_LONG_LONG + +TEST(MockReturnValueTest, PositiveIntReturnValueCanBeRetrievedAsUnsignedLongLongInt) +{ + int expected_value = 7; + mock().expectOneCall("foo").andReturnValue(expected_value); + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); +} + +TEST(MockReturnValueTest, PositiveLongIntReturnValueCanBeRetrievedAsUnsignedLongLongInt) +{ + long int expected_value = 7; + mock().expectOneCall("foo").andReturnValue(expected_value); + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); +} + +TEST(MockReturnValueTest, PositiveLongLongIntReturnValueCanBeRetrievedAsUnsignedLongLongInt) +{ + long long int expected_value = 7; + mock().expectOneCall("foo").andReturnValue(expected_value); + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); +} + +TEST(MockReturnValueTest, UnsignedIntReturnValueCanBeRetrievedAsUnsignedLongLongInt) +{ + unsigned int expected_value = 7; + mock().expectOneCall("foo").andReturnValue(expected_value); + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); +} + +TEST(MockReturnValueTest, UnsignedLongIntReturnValueCanBeRetrievedAsUnsignedLongLongInt) +{ + unsigned long int expected_value = 7; + mock().expectOneCall("foo").andReturnValue(expected_value); + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); +} + +TEST(MockReturnValueTest, UnsignedLongLongIntReturnValueCanBeRetrieved) +{ + unsigned long long int expected_value = 2ULL; + mock().expectOneCall("foo").andReturnValue(expected_value); + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); +} + +TEST(MockReturnValueTest, PositiveIntReturnValueCanBeRetrievedAsLongLongInt) +{ + int expected_value = 7; + mock().expectOneCall("foo").andReturnValue(expected_value); + LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); +} + +TEST(MockReturnValueTest, PositiveLongIntReturnValueCanBeRetrievedAsLongLongInt) +{ + long int expected_value = 7; + mock().expectOneCall("foo").andReturnValue(expected_value); + LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); +} + +TEST(MockReturnValueTest, UnsignedIntReturnValueCanBeRetrievedAsLongLongInt) +{ + unsigned int expected_value = 7; + mock().expectOneCall("foo").andReturnValue(expected_value); + LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); +} + +TEST(MockReturnValueTest, UnsignedLongIntReturnValueCanBeRetrievedAsLongLongInt) +{ + unsigned long int expected_value = 7; + mock().expectOneCall("foo").andReturnValue(expected_value); + LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); +} + +TEST(MockReturnValueTest, LongLongIntReturnValueCanBeRetrieved) +{ + long long int expected_value = 2LL; + mock().expectOneCall("foo").andReturnValue(expected_value); + LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); +} + +#endif + TEST(MockReturnValueTest, UnsignedIntegerReturnValueSetsDifferentValues) { unsigned int expected_value = 1; @@ -202,6 +284,44 @@ TEST(MockReturnValueTest, WhenNoLongIntegerReturnValueIsExpectedButThereIsADefau LONGS_EQUAL(default_return_value, mock().returnLongIntValueOrDefault(default_return_value)); } +#if CPPUTEST_USE_LONG_LONG + +TEST(MockReturnValueTest, WhenAUnsignedLongLongIntegerReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) +{ + unsigned long long int default_return_value = 2ULL; + unsigned long long int expected_return_value = default_return_value - 1; + mock().expectOneCall("foo").andReturnValue(expected_return_value); + LONGS_EQUAL(expected_return_value, mock().actualCall("foo").returnUnsignedLongLongIntValueOrDefault(default_return_value)); + LONGS_EQUAL(expected_return_value, mock().returnUnsignedLongLongIntValueOrDefault(default_return_value)); +} + +TEST(MockReturnValueTest, WhenNoUnsignedLongLongIntegerReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) +{ + unsigned long long int default_return_value = 2ULL; + mock().expectOneCall("foo"); + LONGS_EQUAL(default_return_value, mock().actualCall("foo").returnUnsignedLongLongIntValueOrDefault(default_return_value)); + LONGS_EQUAL(default_return_value, mock().returnUnsignedLongLongIntValueOrDefault(default_return_value)); +} + +TEST(MockReturnValueTest, WhenALongLongIntegerReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) +{ + long long int default_return_value = 2LL; + long long int expected_return_value = default_return_value - 1; + mock().expectOneCall("foo").andReturnValue(expected_return_value); + LONGS_EQUAL(expected_return_value, mock().actualCall("foo").returnLongLongIntValueOrDefault(default_return_value)); + LONGS_EQUAL(expected_return_value, mock().returnLongLongIntValueOrDefault(default_return_value)); +} + +TEST(MockReturnValueTest, WhenNoLongLongIntegerReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) +{ + long long int default_return_value = 2LL; + mock().expectOneCall("foo"); + LONGS_EQUAL(default_return_value, mock().actualCall("foo").returnLongLongIntValueOrDefault(default_return_value)); + LONGS_EQUAL(default_return_value, mock().returnLongLongIntValueOrDefault(default_return_value)); +} + +#endif + TEST(MockReturnValueTest, WhenABooleanReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { bool default_return_value = true; @@ -398,6 +518,90 @@ TEST(MockReturnValueTest, UnsignedLongIntegerReturnValueSetsDifferentValuesWhile LONGS_EQUAL(another_ret_value, mock().returnValue().getUnsignedLongIntValue()); } +#if CPPUTEST_USE_LONG_LONG + +TEST(MockReturnValueTest, LongLongIntegerReturnValue) +{ + long long int expected_value = 7; + mock().expectOneCall("foo").andReturnValue(expected_value); + + MockActualCall& actual_call = mock().actualCall("foo"); + LONGLONGS_EQUAL(expected_value, actual_call.returnValue().getLongLongIntValue()); + LONGLONGS_EQUAL(expected_value, actual_call.returnLongLongIntValue()); + LONGLONGS_EQUAL(expected_value, mock().returnValue().getLongLongIntValue()); + LONGLONGS_EQUAL(expected_value, mock().longLongIntReturnValue()); +} + +TEST(MockReturnValueTest, LongLongIntegerReturnValueSetsDifferentValues) +{ + long long int expected_value = 1; + long long int another_expected_value = 2; + + mock().expectOneCall("foo").andReturnValue(expected_value); + mock().expectOneCall("foo").andReturnValue(another_expected_value); + + LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); + LONGLONGS_EQUAL(expected_value, mock().returnValue().getLongLongIntValue()); + LONGLONGS_EQUAL(another_expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); + LONGLONGS_EQUAL(another_expected_value, mock().returnValue().getLongLongIntValue()); +} + +TEST(MockReturnValueTest, LongLongIntegerReturnValueSetsDifferentValuesWhileParametersAreIgnored) +{ + long long int ret_value = 1; + long long int another_ret_value = 2; + + mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(ret_value); + mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(another_ret_value); + + LONGLONGS_EQUAL(ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getLongLongIntValue()); + LONGLONGS_EQUAL(ret_value, mock().returnValue().getLongLongIntValue()); + LONGLONGS_EQUAL(another_ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getLongLongIntValue()); + LONGLONGS_EQUAL(another_ret_value, mock().returnValue().getLongLongIntValue()); +} + +TEST(MockReturnValueTest, UnsignedLongLongIntegerReturnValue) +{ + unsigned long long int expected_value = 7; + mock().expectOneCall("foo").andReturnValue(expected_value); + + MockActualCall& actual_call = mock().actualCall("foo"); + UNSIGNED_LONGLONGS_EQUAL(expected_value, actual_call.returnValue().getUnsignedLongLongIntValue()); + UNSIGNED_LONGLONGS_EQUAL(expected_value, actual_call.returnUnsignedLongLongIntValue()); + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().returnValue().getUnsignedLongLongIntValue()); + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().unsignedLongLongIntReturnValue()); +} + +TEST(MockReturnValueTest, UnsignedLongLongIntegerReturnValueSetsDifferentValues) +{ + unsigned long long int expected_value = 1; + unsigned long long int another_expected_value = 2; + + mock().expectOneCall("foo").andReturnValue(expected_value); + mock().expectOneCall("foo").andReturnValue(another_expected_value); + + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().returnValue().getUnsignedLongLongIntValue()); + UNSIGNED_LONGLONGS_EQUAL(another_expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); + UNSIGNED_LONGLONGS_EQUAL(another_expected_value, mock().returnValue().getUnsignedLongLongIntValue()); +} + +TEST(MockReturnValueTest, UnsignedLongLongIntegerReturnValueSetsDifferentValuesWhileParametersAreIgnored) +{ + unsigned long long int ret_value = 1; + unsigned long long int another_ret_value = 2; + + mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(ret_value); + mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(another_ret_value); + + UNSIGNED_LONGLONGS_EQUAL(ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getUnsignedLongLongIntValue()); + UNSIGNED_LONGLONGS_EQUAL(ret_value, mock().returnValue().getUnsignedLongLongIntValue()); + UNSIGNED_LONGLONGS_EQUAL(another_ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getUnsignedLongLongIntValue()); + UNSIGNED_LONGLONGS_EQUAL(another_ret_value, mock().returnValue().getUnsignedLongLongIntValue()); +} + +#endif + TEST(MockReturnValueTest, MatchingReturnValueOnWhileSignature) { mock().expectOneCall("foo").withParameter("p1", 1).andReturnValue(1); @@ -541,4 +745,3 @@ TEST(MockReturnValueTest, whenCallingDisabledOrIgnoredActualCallsThenTheyDontRet CHECK(!mock().hasReturnValue()); } - diff --git a/tests/CppUTestExt/MockStrictOrderTest.cpp b/tests/CppUTestExt/MockStrictOrderTest.cpp index 41fe96d9d..9151ffa5e 100644 --- a/tests/CppUTestExt/MockStrictOrderTest.cpp +++ b/tests/CppUTestExt/MockStrictOrderTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,7 +30,7 @@ TEST_GROUP(MockStrictOrderTest) { - void teardown() + void teardown() CPPUTEST_OVERRIDE { mock().clear(); } @@ -66,9 +66,9 @@ TEST(MockStrictOrderTest, orderViolated) mock().strictOrder(); MockExpectedCallsListForTest expectations; - expectations.addFunction("foo1", 1)->callWasMade(1); - expectations.addFunction("foo1", 2)->callWasMade(3); - expectations.addFunction("foo2", 3)->callWasMade(2); + expectations.addFunctionOrdered("foo1", 1)->callWasMade(1); + expectations.addFunctionOrdered("foo1", 2)->callWasMade(3); + expectations.addFunctionOrdered("foo2", 3)->callWasMade(2); MockCallOrderFailure expectedFailure(mockFailureTest(), expectations); mock().expectOneCall("foo1"); @@ -89,8 +89,8 @@ TEST(MockStrictOrderTest, orderViolatedWorksHierarchically) mock("bla").strictOrder(); MockExpectedCallsListForTest expectations; - expectations.addFunction("foo::foo1", 1)->callWasMade(2); - expectations.addFunction("foo::foo2", 2)->callWasMade(1); + expectations.addFunctionOrdered("foo::foo1", 1)->callWasMade(2); + expectations.addFunctionOrdered("foo::foo2", 2)->callWasMade(1); MockCallOrderFailure expectedFailure(mockFailureTest(), expectations); mock("bla").expectOneCall("foo1"); @@ -113,8 +113,8 @@ TEST(MockStrictOrderTest, orderViolatedWorksWithExtraUnexpectedCall) mock().ignoreOtherCalls(); MockExpectedCallsListForTest expectations; - expectations.addFunction("foo::foo1", 1)->callWasMade(2); - expectations.addFunction("foo::foo2", 2)->callWasMade(1); + expectations.addFunctionOrdered("foo::foo1", 1)->callWasMade(2); + expectations.addFunctionOrdered("foo::foo2", 2)->callWasMade(1); MockCallOrderFailure expectedFailure(mockFailureTest(), expectations); mock("bla").expectOneCall("foo1"); @@ -137,8 +137,8 @@ TEST(MockStrictOrderTest, orderViolatedWithinAScope) mock().strictOrder(); MockExpectedCallsListForTest expectations; - expectations.addFunction("scope::foo1", 1)->callWasMade(2); - expectations.addFunction("scope::foo2", 2)->callWasMade(1); + expectations.addFunctionOrdered("scope::foo1", 1)->callWasMade(2); + expectations.addFunctionOrdered("scope::foo2", 2)->callWasMade(1); MockCallOrderFailure expectedFailure(mockFailureTest(), expectations); mock("scope").expectOneCall("foo1"); @@ -185,11 +185,15 @@ TEST(MockStrictOrderTest, orderUsingNCalls) mock().expectOneCall("foo1"); mock().expectNCalls(2, "foo2"); mock().expectOneCall("foo1"); + mock().expectNCalls(3, "foo2"); + mock().actualCall("foo1"); mock().actualCall("foo2"); mock().actualCall("foo2"); mock().actualCall("foo1"); + mock().actualCall("foo2"); + mock().actualCall("foo2"); + mock().actualCall("foo2"); mock().checkExpectations(); } - diff --git a/tests/CppUTestExt/MockSupportTest.cpp b/tests/CppUTestExt/MockSupportTest.cpp index 4c616dd5d..7f9be3153 100644 --- a/tests/CppUTestExt/MockSupportTest.cpp +++ b/tests/CppUTestExt/MockSupportTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -37,10 +37,12 @@ TEST_GROUP(MockSupportTest) MockExpectedCallsListForTest expectations; MockFailureReporterInstaller failureReporterInstaller; - void teardown() + void teardown() CPPUTEST_OVERRIDE { - mock().checkExpectations(); - CHECK_NO_MOCK_FAILURE(); + mock().checkExpectations(); + CHECK_NO_MOCK_FAILURE(); + MockFailureReporterForTest::clearReporter(); + mock().clear(); } }; @@ -105,6 +107,20 @@ TEST(MockSupportTest, setDataDouble) DOUBLES_EQUAL(1.0, mock().getData("data").getDoubleValue(), 0.05); } +TEST(MockSupportTest, setDataLongInt) +{ + long int i = 100; + mock().setData("data", i); + LONGS_EQUAL(i, mock().getData("data").getLongIntValue()); +} + +TEST(MockSupportTest, setDataUnsignedLongInt) +{ + unsigned long int i = 100; + mock().setData("data", i); + UNSIGNED_LONGS_EQUAL(i, mock().getData("data").getUnsignedLongIntValue()); +} + TEST(MockSupportTest, setDataPointer) { void * ptr = (void*) 0x001; @@ -134,6 +150,14 @@ TEST(MockSupportTest, setDataObject) STRCMP_EQUAL("type", mock().getData("data").getType().asCharString()); } +TEST(MockSupportTest, setDataConstObject) +{ + void * ptr = (void*) 0x011; + mock().setDataConstObject("data", "type", ptr); + POINTERS_EQUAL(ptr, mock().getData("data").getConstObjectPointer()); + STRCMP_EQUAL("type", mock().getData("data").getType().asCharString()); +} + TEST(MockSupportTest, tracing) { mock().tracing(true); @@ -162,6 +186,12 @@ TEST(MockSupportTest, tracingWorksHierarchically) TEST_GROUP(MockSupportTestWithFixture) { TestTestingFixture fixture; + + void teardown() CPPUTEST_OVERRIDE + { + mock().clear(); + MockFailureReporterForTest::clearReporter(); + } }; static void CHECK_EXPECTED_MOCK_FAILURE_LOCATION_failedTestMethod_() @@ -215,6 +245,7 @@ static void unexpectedCallTestFunction_(void) TEST(MockSupportTestWithFixture, shouldCrashOnFailure) { + cpputestHasCrashed = false; mock().crashOnFailure(true); UtestShell::setCrashMethod(crashMethod); fixture.setTestFunction(unexpectedCallTestFunction_); @@ -240,6 +271,21 @@ TEST(MockSupportTestWithFixture, ShouldNotCrashOnFailureAfterCrashMethodWasReset CHECK_FALSE(cpputestHasCrashed); } +TEST(MockSupportTestWithFixture, shouldCrashOnFailureWithCppUTestSetting) +{ + cpputestHasCrashed = false; + UtestShell::setCrashOnFail(); + UtestShell::setCrashMethod(crashMethod); + fixture.setTestFunction(unexpectedCallTestFunction_); + + fixture.runAllTests(); + + CHECK(cpputestHasCrashed); + + UtestShell::restoreDefaultTestTerminator(); + UtestShell::resetCrashMethod(); +} + TEST(MockSupportTestWithFixture, failedMockShouldFailAgainWhenRepeated) { fixture.setTestFunction(unexpectedCallTestFunction_); @@ -249,9 +295,6 @@ TEST(MockSupportTestWithFixture, failedMockShouldFailAgainWhenRepeated) fixture.runAllTests(); fixture.assertPrintContains("Unexpected call to function: unexpected"); fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out"); - fixture.output_->flush(); - delete fixture.result_; - fixture.result_ = new TestResult(*fixture.output_); + fixture.flushOutputAndResetResult(); } } - diff --git a/tests/CppUTestExt/MockSupport_cTest.cpp b/tests/CppUTestExt/MockSupport_cTest.cpp index 8fc55ec70..0ce86bedf 100644 --- a/tests/CppUTestExt/MockSupport_cTest.cpp +++ b/tests/CppUTestExt/MockSupport_cTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -43,6 +43,10 @@ extern "C" { TEST_GROUP(MockSupport_c) { + void teardown() CPPUTEST_OVERRIDE + { + mock_c()->clear(); + } }; TEST(MockSupport_c, OrderObserved) @@ -60,12 +64,12 @@ TEST(MockSupport_c, OrderObserved) TEST(MockSupport_c, hasReturnValue) { mock_c()->expectOneCall("foo"); - CHECK(!mock_c()->actualCall("foo")->hasReturnValue()); - CHECK(!mock_c()->hasReturnValue()); + CHECK(mock_c()->actualCall("foo")->hasReturnValue() == 0); + CHECK(mock_c()->hasReturnValue() == 0); mock_c()->expectOneCall("foo2")->andReturnIntValue(1); - CHECK(mock_c()->actualCall("foo2")->hasReturnValue()); - CHECK(mock_c()->hasReturnValue()); + CHECK(mock_c()->actualCall("foo2")->hasReturnValue() != 0); + CHECK(mock_c()->hasReturnValue() != 0); } TEST(MockSupport_c, expectAndActualOneCall) @@ -116,7 +120,7 @@ extern "C"{ static void typeCopy(void* dst, const void* src) { - *(int*) dst = *(int*) src; + *(int*) dst = *(const int*) src; } } @@ -154,6 +158,28 @@ TEST(MockSupport_c, unsignedLongIntParameter) mock_c()->actualCall("foo")->withUnsignedLongIntParameters("p", 1); } +TEST(MockSupport_c, doubleParameterWithTolerance) +{ + mock_c( )->expectOneCall("foo")->withDoubleParametersAndTolerance("p", 2.0, 0.2); + mock_c( )->actualCall("foo")->withDoubleParameters("p", 1.9); +} + +#if CPPUTEST_USE_LONG_LONG + +TEST(MockSupport_c, longLongIntParameter) +{ + mock_c()->expectOneCall("foo")->withLongLongIntParameters("p", 1); + mock_c()->actualCall("foo")->withLongLongIntParameters("p", 1); +} + +TEST(MockSupport_c, unsignedLongLongIntParameter) +{ + mock_c()->expectOneCall("foo")->withUnsignedLongLongIntParameters("p", 1); + mock_c()->actualCall("foo")->withUnsignedLongLongIntParameters("p", 1); +} + +#endif + TEST(MockSupport_c, memoryBufferParameter) { const unsigned char mem_buffer[] = { 1, 2, 3}; @@ -173,6 +199,15 @@ TEST(MockSupport_c, outputParameters) LONGS_EQUAL(2, retval); } +TEST(MockSupport_c, unmodifiedOutputParameter) +{ + int param = 1; + mock_c()->expectOneCall("foo")->withUnmodifiedOutputParameter("out"); + mock_c()->actualCall("foo")->withOutputParameter("out", ¶m); + mock_c()->checkExpectations(); + LONGS_EQUAL(1, param); +} + TEST(MockSupport_c, outputParameters_differentType) { long param = 1; @@ -186,8 +221,8 @@ TEST(MockSupport_c, outputParameters_differentType) TEST(MockSupport_c, outputParametersOfType) { - long param = 1; - const long retval = 2; + int param = 1; + const int retval = 2; mock_c()->installCopier("typeName", typeCopy); mock_c()->expectOneCall("foo")->withOutputParameterOfTypeReturning("typeName", "out", &retval); mock_c()->actualCall("foo")->withOutputParameterOfType("typeName", "out", ¶m); @@ -334,6 +369,62 @@ TEST(MockSupport_c, whenNoReturnValueIsGivenReturnUnsignedLongIntValueOrDefaultS LONGS_EQUAL(defaultValue, mock_c()->returnUnsignedLongIntValueOrDefault(defaultValue)); } +#if CPPUTEST_USE_LONG_LONG + +TEST(MockSupport_c, returnLongLongIntValue) +{ + long long int expected_value = -10L; + mock_c()->expectOneCall("boo")->andReturnLongLongIntValue(expected_value); + LONGLONGS_EQUAL(expected_value, mock_c()->actualCall("boo")->longLongIntReturnValue()); + LONGLONGS_EQUAL(expected_value, mock_c()->longLongIntReturnValue()); + LONGLONGS_EQUAL(MOCKVALUETYPE_LONG_LONG_INTEGER, mock_c()->returnValue().type); +} + +TEST(MockSupport_c, whenReturnValueIsGivenReturnLongLongIntValueOrDefaultShouldIgnoreTheDefault) +{ + long long int defaultValue = -10L; + long long int expectedValue = defaultValue - 1L; + mock_c()->expectOneCall("foo")->andReturnLongLongIntValue(expectedValue); + LONGLONGS_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnLongLongIntValueOrDefault(defaultValue)); + LONGLONGS_EQUAL(expectedValue, mock_c()->returnLongLongIntValueOrDefault(defaultValue)); +} + +TEST(MockSupport_c, whenNoReturnValueIsGivenReturnLongLongIntValueOrDefaultShouldlUseTheDefaultValue) +{ + long long int defaultValue = -10L; + mock_c()->expectOneCall("foo"); + LONGLONGS_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnLongLongIntValueOrDefault(defaultValue)); + LONGLONGS_EQUAL(defaultValue, mock_c()->returnLongLongIntValueOrDefault(defaultValue)); +} + +TEST(MockSupport_c, returnUnsignedLongLongIntValue) +{ + unsigned long long int expected_value = 10; + mock_c()->expectOneCall("boo")->andReturnUnsignedLongLongIntValue(expected_value); + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock_c()->actualCall("boo")->unsignedLongLongIntReturnValue()); + UNSIGNED_LONGLONGS_EQUAL(expected_value, mock_c()->unsignedLongLongIntReturnValue()); + UNSIGNED_LONGLONGS_EQUAL(MOCKVALUETYPE_UNSIGNED_LONG_LONG_INTEGER, mock_c()->returnValue().type); +} + +TEST(MockSupport_c, whenReturnValueIsGivenReturnUnsignedLongLongIntValueOrDefaultShouldIgnoreTheDefault) +{ + unsigned long long int defaultValue = 10L; + unsigned long long int expectedValue = defaultValue + 1L; + mock_c()->expectOneCall("foo")->andReturnUnsignedLongLongIntValue(expectedValue); + UNSIGNED_LONGLONGS_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnUnsignedLongLongIntValueOrDefault(defaultValue)); + UNSIGNED_LONGLONGS_EQUAL(expectedValue, mock_c()->returnUnsignedLongLongIntValueOrDefault(defaultValue)); +} + +TEST(MockSupport_c, whenNoReturnValueIsGivenReturnUnsignedLongLongIntValueOrDefaultShouldlUseTheDefaultValue) +{ + unsigned long long int defaultValue = 10L; + mock_c()->expectOneCall("foo"); + UNSIGNED_LONGLONGS_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnUnsignedLongLongIntValueOrDefault(defaultValue)); + UNSIGNED_LONGLONGS_EQUAL(defaultValue, mock_c()->returnUnsignedLongLongIntValueOrDefault(defaultValue)); +} + +#endif + TEST(MockSupport_c, returnStringValue) { mock_c()->expectOneCall("boo")->andReturnStringValue("hello world"); @@ -476,6 +567,20 @@ TEST(MockSupport_c, MockSupportSetIntData) LONGS_EQUAL(10, mock_c()->getData("integer").value.intValue); } +TEST(MockSupport_c, MockSupportSetLongIntData) +{ + long int i = 100; + mock_c()->setLongIntData("long integer", i); + LONGS_EQUAL(i, mock_c()->getData("long integer").value.longIntValue); +} + +TEST(MockSupport_c, MockSupportSetUnsignedLongIntData) +{ + unsigned long int i = 100; + mock_c()->setUnsignedLongIntData("unsigned long integer", i); + UNSIGNED_LONGS_EQUAL(i, mock_c()->getData("unsigned long integer").value.unsignedLongIntValue); +} + TEST(MockSupport_c, MockSupportSetDoubleData) { mock_c()->setDoubleData("double", 1.0); @@ -519,6 +624,12 @@ TEST(MockSupport_c, MockSupportSetDataObject) POINTERS_EQUAL((void*) 1, mock_c()->getData("name").value.objectValue); } +TEST(MockSupport_c, MockSupportSetDataConstObject) +{ + mock_c()->setDataConstObject("name", "type", (const void*) 5); + POINTERS_EQUAL((void*) 5, mock_c()->getData("name").value.constObjectValue); +} + TEST(MockSupport_c, WorksInCFile) { all_mock_support_c_calls(); @@ -589,6 +700,40 @@ TEST_ORDERED(MockSupport_c, nextTestShouldNotCrashOnFailure, 22) UtestShell::resetCrashMethod(); } +TEST(MockSupport_c, FailWillNotCrashIfNotEnabled) +{ + cpputestHasCrashed = false; + TestTestingFixture fixture; + UtestShell::setCrashMethod(crashMethod); + + fixture.setTestFunction(failedCallToMockC); + + fixture.runAllTests(); + + CHECK_FALSE(cpputestHasCrashed); + LONGS_EQUAL(1, fixture.getFailureCount()); + + UtestShell::resetCrashMethod(); +} + +TEST(MockSupport_c, FailWillCrashIfEnabled) +{ + cpputestHasCrashed = false; + TestTestingFixture fixture; + UtestShell::setCrashOnFail(); + UtestShell::setCrashMethod(crashMethod); + + fixture.setTestFunction(failedCallToMockC); + + fixture.runAllTests(); + + CHECK(cpputestHasCrashed); + LONGS_EQUAL(1, fixture.getFailureCount()); + + UtestShell::restoreDefaultTestTerminator(); + UtestShell::resetCrashMethod(); +} + static void failingCallToMockCWithParameterOfType_() { mock_c()->expectOneCall("bar")->withParameterOfType("typeName", "name", (const void*) 1); diff --git a/tests/CppUTestExt/MockSupport_cTestCFile.c b/tests/CppUTestExt/MockSupport_cTestCFile.c index 38155c7a5..e3ad5fb1a 100644 --- a/tests/CppUTestExt/MockSupport_cTestCFile.c +++ b/tests/CppUTestExt/MockSupport_cTestCFile.c @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -53,7 +53,13 @@ void all_mock_support_c_calls(void) withUnsignedIntParameters("unsigned", 1)-> withLongIntParameters("long int", (long int) -1)-> withUnsignedLongIntParameters("unsigned long int", (unsigned long int) 1)-> +#if CPPUTEST_USE_LONG_LONG + withLongLongIntParameters("long long int", (long long int) -1)-> + withUnsignedLongLongIntParameters("unsigned long long int", (unsigned long long int) 1)-> +#endif + withDoubleParameters("double", 1.0)-> + withDoubleParametersAndTolerance("doubleWithTolerance", 1.0, 1.0)-> withStringParameters("string", "string")-> withPointerParameters("pointer", (void*) 1)-> withConstPointerParameters("constpointer", (const void*) 1)-> @@ -66,7 +72,12 @@ void all_mock_support_c_calls(void) withUnsignedIntParameters("unsigned", 1)-> withLongIntParameters("long int", (long int) -1)-> withUnsignedLongIntParameters("unsigned long int", (unsigned long int) 1)-> +#if CPPUTEST_USE_LONG_LONG + withLongLongIntParameters("long long int", (long long int) -1)-> + withUnsignedLongLongIntParameters("unsigned long long int", (unsigned long long int) 1)-> +#endif withDoubleParameters("double", 1.0)-> + withDoubleParameters("doubleWithTolerance", 0.0 )-> withStringParameters("string", "string")-> withPointerParameters("pointer", (void*) 1)-> withConstPointerParameters("constpointer", (const void*) 1)-> @@ -100,18 +111,28 @@ void all_mock_support_c_calls(void) mock_c()->intReturnValue(); mock_c()->returnValue(); - mock_c()->expectOneCall("boo2")->andReturnUnsignedIntValue(1.0); + mock_c()->expectOneCall("boo2")->andReturnUnsignedIntValue(1); mock_c()->actualCall("boo2")->unsignedIntReturnValue(); mock_c()->unsignedIntReturnValue(); - mock_c()->expectOneCall("boo3")->andReturnLongIntValue(1.0); + mock_c()->expectOneCall("boo3")->andReturnLongIntValue(1); mock_c()->actualCall("boo3")->longIntReturnValue(); mock_c()->longIntReturnValue(); - mock_c()->expectOneCall("boo3")->andReturnUnsignedLongIntValue(1.0); + mock_c()->expectOneCall("boo3")->andReturnUnsignedLongIntValue(1); mock_c()->actualCall("boo3")->unsignedLongIntReturnValue(); mock_c()->unsignedLongIntReturnValue(); +#if CPPUTEST_USE_LONG_LONG + mock_c()->expectOneCall("mgrgrgr1")->andReturnLongLongIntValue(1); + mock_c()->actualCall("mgrgrgr1")->longLongIntReturnValue(); + mock_c()->longLongIntReturnValue(); + + mock_c()->expectOneCall("mgrgrgr2")->andReturnUnsignedLongLongIntValue(1); + mock_c()->actualCall("mgrgrgr2")->unsignedLongLongIntReturnValue(); + mock_c()->unsignedLongLongIntReturnValue(); +#endif + mock_c()->expectOneCall("boo4")->andReturnDoubleValue(1.0); mock_c()->actualCall("boo4")->doubleReturnValue(); mock_c()->doubleReturnValue(); @@ -168,6 +189,10 @@ void all_mock_support_c_calls(void) mock_c()->returnUnsignedIntValueOrDefault(1); mock_c()->returnLongIntValueOrDefault(-1L); mock_c()->returnUnsignedLongIntValueOrDefault(1L); +#if CPPUTEST_USE_LONG_LONG + mock_c()->returnLongLongIntValueOrDefault(-1LL); + mock_c()->returnUnsignedLongLongIntValueOrDefault(1ULL); +#endif mock_c()->returnStringValueOrDefault(""); mock_c()->returnDoubleValueOrDefault(0.01); mock_c()->returnPointerValueOrDefault(0); diff --git a/tests/CppUTestExt/MockSupport_cTestCFile.h b/tests/CppUTestExt/MockSupport_cTestCFile.h index 686c75eee..245247494 100644 --- a/tests/CppUTestExt/MockSupport_cTestCFile.h +++ b/tests/CppUTestExt/MockSupport_cTestCFile.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY diff --git a/tests/CppUTestExt/OrderedTestTest.cpp b/tests/CppUTestExt/OrderedTestTest.cpp index 9d2c78bd7..0273cf587 100644 --- a/tests/CppUTestExt/OrderedTestTest.cpp +++ b/tests/CppUTestExt/OrderedTestTest.cpp @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -30,6 +30,7 @@ #include "CppUTest/TestRegistry.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTestExt/OrderedTest.h" +#include "OrderedTestTest.h" TEST_GROUP(TestOrderedTest) { @@ -43,16 +44,16 @@ TEST_GROUP(TestOrderedTest) ExecFunctionTestShell normalTest3; OrderedTestShell* orderedTestCache; - void setup() + void setup() CPPUTEST_OVERRIDE { orderedTestCache = OrderedTestShell::getOrderedTestHead(); - OrderedTestShell::setOrderedTestHead(0); + OrderedTestShell::setOrderedTestHead(NULLPTR); fixture = new TestTestingFixture(); - fixture->registry_->unDoLastAddTest(); + fixture->getRegistry()->unDoLastAddTest(); } - void teardown() + void teardown() CPPUTEST_OVERRIDE { delete fixture; OrderedTestShell::setOrderedTestHead(orderedTestCache); @@ -70,18 +71,18 @@ TEST_GROUP(TestOrderedTest) UtestShell* firstTest() { - return fixture->registry_->getFirstTest(); + return fixture->getRegistry()->getFirstTest(); } UtestShell* secondTest() { - return fixture->registry_->getFirstTest()->getNext(); + return firstTest()->getNext(); } }; TEST(TestOrderedTest, TestInstallerSetsFields) { - OrderedTestInstaller(orderedTest, "testgroup", "testname", "this.cpp", 10, 5); + OrderedTestInstaller installer(orderedTest, "testgroup", "testname", "this.cpp", 10, 5); STRCMP_EQUAL("testgroup", orderedTest.getGroup().asCharString()); STRCMP_EQUAL("testname", orderedTest.getName().asCharString()); STRCMP_EQUAL("this.cpp", orderedTest.getFile().asCharString()); @@ -168,7 +169,7 @@ int OrderedTestTestingFixture::count_ = 0; TEST_GROUP(TestOrderedTestMacros) { - void setup() + void setup() CPPUTEST_OVERRIDE { OrderedTestTestingFixture::checkRun(TestRegistry::getCurrentRegistry()->getCurrentRepetition()); } @@ -198,3 +199,48 @@ TEST_ORDERED(TestOrderedTestMacros, Test3, 3) { CHECK(OrderedTestTestingFixture::count() == 3); } + +// Test with same level +TEST_ORDERED(TestOrderedTestMacros, Test5_1, 5) +{ + CHECK(OrderedTestTestingFixture::count() == 5); +} + +TEST_ORDERED(TestOrderedTestMacros, Test6_1, 6) +{ + CHECK(OrderedTestTestingFixture::count() == 7); +} + +TEST_ORDERED(TestOrderedTestMacros, Test5_2, 5) +{ + CHECK(OrderedTestTestingFixture::count() == 6); +} + +TEST_ORDERED(TestOrderedTestMacros, Test6_2, 6) +{ + CHECK(OrderedTestTestingFixture::count() == 8); +} + +// Test C-Interface +TEST_ORDERED(TestOrderedTestMacros, Test10, 10) +{ + CHECK(OrderedTestTestingFixture::count() == 12); +} + +TEST_ORDERED(TestOrderedTestMacros, Test8, 8) +{ + CHECK(OrderedTestTestingFixture::count() == 10); +} + +// Export to be usable in OrderedTestTest_c.c +extern "C" { +int orderedTestFixtureCWrapper(void) { + return OrderedTestTestingFixture::count(); +} +} + +TEST_ORDERED_C_WRAPPER(TestOrderedTestMacros, Test11, 11) + +TEST_ORDERED_C_WRAPPER(TestOrderedTestMacros, Test7, 7) + +TEST_ORDERED_C_WRAPPER(TestOrderedTestMacros, Test9, 9) diff --git a/tests/AllTests.cpp b/tests/CppUTestExt/OrderedTestTest.h similarity index 80% rename from tests/AllTests.cpp rename to tests/CppUTestExt/OrderedTestTest.h index fefa35f36..4d6afbac4 100644 --- a/tests/AllTests.cpp +++ b/tests/CppUTestExt/OrderedTestTest.h @@ -13,7 +13,7 @@ * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY @@ -25,14 +25,18 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "CppUTest/CommandLineTestRunner.h" +#ifndef ORDEREDTESTTEST_H +#define ORDEREDTESTTEST_H -int main(int ac, const char** av) -{ - /* These checks are here to make sure assertions outside test runs don't crash */ - CHECK(true); - LONGS_EQUAL(1, 1); +#ifdef __cplusplus +extern "C" { +#endif - return CommandLineTestRunner::RunAllTests(ac, const_cast(av)); /* cover alternate method */ +extern int orderedTestFixtureCWrapper(void); + +#ifdef __cplusplus } +#endif + +#endif /* ORDEREDTESTTEST_H */ diff --git a/tests/CppUTestExt/OrderedTestTest_c.c b/tests/CppUTestExt/OrderedTestTest_c.c new file mode 100644 index 000000000..8158fd89e --- /dev/null +++ b/tests/CppUTestExt/OrderedTestTest_c.c @@ -0,0 +1,17 @@ +#include "CppUTest/TestHarness_c.h" +#include "OrderedTestTest.h" + +TEST_C(TestOrderedTestMacros, Test11) +{ + CHECK_C(orderedTestFixtureCWrapper() == 13); +} + +TEST_C(TestOrderedTestMacros, Test7) +{ + CHECK_C(orderedTestFixtureCWrapper() == 9); +} + +TEST_C(TestOrderedTestMacros, Test9) +{ + CHECK_C(orderedTestFixtureCWrapper() == 11); +} diff --git a/tests/DummyUTestPlatform/DummyUTestPlatform.cpp b/tests/DummyUTestPlatform/DummyUTestPlatform.cpp new file mode 100644 index 000000000..948c85dbe --- /dev/null +++ b/tests/DummyUTestPlatform/DummyUTestPlatform.cpp @@ -0,0 +1,140 @@ +#include + +typedef char jmp_buf[200]; + +TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() +{ + return TestOutput::eclipse; +} + +void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) = NULLPTR; +int (*PlatformSpecificFork)(void) = NULLPTR; +int (*PlatformSpecificWaitPid)(int pid, int* status, int options) = NULLPTR; + +static jmp_buf test_exit_jmp_buf[10]; +static int jmp_buf_index = 0; + +extern "C" int setjmp(jmp_buf); +static int fakeSetJmp(void (*function)(void* data), void* data) +{ + if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { + jmp_buf_index++; + function(data); + jmp_buf_index--; + return 1; + } + return 0; +} +int (*PlatformSpecificSetJmp)(void (*function)(void*), void* data) = fakeSetJmp; + +extern "C" void longjmp(jmp_buf, int); +static void fakeLongJmp(void) +{ + jmp_buf_index--; + longjmp(test_exit_jmp_buf[jmp_buf_index], 1); +} +void (*PlatformSpecificLongJmp)(void) = fakeLongJmp; + +static void fakeRestoreJumpBuffer() +{ + jmp_buf_index--; +} +void (*PlatformSpecificRestoreJumpBuffer)(void) = fakeRestoreJumpBuffer; + +static unsigned long fakeTimeInMillis(void) +{ + return 0; +} +unsigned long (*GetPlatformSpecificTimeInMillis)(void) = fakeTimeInMillis; + +static const char* fakeTimeString(void) +{ + return ""; +} +const char* (*GetPlatformSpecificTimeString)() = fakeTimeString; + +extern "C" int vsnprintf(char*, size_t, const char*, va_list); +int (*PlatformSpecificVSNprintf)(char* str, size_t size, const char* format, va_list va_args_list) = vsnprintf; + +extern "C" double fabs(double); +double (*PlatformSpecificFabs)(double d) = fabs; + +static int fakeIsNan(double d) +{ + return d != d; +} +int (*PlatformSpecificIsNan)(double d) = fakeIsNan; + +static int fakeIsInf(double d) +{ + return !fakeIsNan(d) && fakeIsNan(d - d); +} +int (*PlatformSpecificIsInf)(double d) = fakeIsInf; + +extern "C" int atexit(void (*func)(void)); +int (*PlatformSpecificAtExit)(void (*func)(void)) = atexit; + +extern "C" void* stdout; +PlatformSpecificFile PlatformSpecificStdOut = stdout; + +extern "C" void* fopen(const char*, const char*); +PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = fopen; + +extern "C" int fputs(const char*, void*); +static void fakeFPuts(const char* str, PlatformSpecificFile file) +{ + fputs(str, file); +} +void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = fakeFPuts; + +extern "C" int fclose(void* stream); +static void fakeFClose(PlatformSpecificFile file) +{ + fclose(file); +} +void (*PlatformSpecificFClose)(PlatformSpecificFile file) = fakeFClose; + +extern "C" int fflush(void* stream); +static void fakeFlush(void) +{ + fflush(stdout); +} +void (*PlatformSpecificFlush)(void) = fakeFlush; + +static void fakeSrand(unsigned int){}; +void (*PlatformSpecificSrand)(unsigned int) = fakeSrand; + +static int fakeRand(void) +{ + return 0; +} +int (*PlatformSpecificRand)(void) = fakeRand; + +extern "C" void* malloc(size_t); +void* (*PlatformSpecificMalloc)(size_t) = malloc; + +extern "C" void* realloc(void* ptr, size_t new_size); +void* (*PlatformSpecificRealloc)(void* memory, size_t size) = realloc; + +extern "C" void free(void*); +void (*PlatformSpecificFree)(void* memory) = free; + +extern "C" void* memcpy(void* dest, const void* src, size_t count); +void* (*PlatformSpecificMemCpy)(void* s1, const void* s2, size_t size) = memcpy; + +extern "C" void* memset(void* dest, int ch, size_t count); +void* (*PlatformSpecificMemset)(void* mem, int c, size_t size) = memset; + +static PlatformSpecificMutex fakeMutexCreate(void) +{ + return 0; +} +PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = fakeMutexCreate; + +static void fakeMutexFunc(PlatformSpecificMutex) {} +void (*PlatformSpecificMutexLock)(PlatformSpecificMutex mtx) = fakeMutexFunc; +void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex mtx) = fakeMutexFunc; +void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex mtx) = fakeMutexFunc; + +extern "C" void abort(void); +void (*PlatformSpecificAbort)(void) = abort; diff --git a/tests/RunAllTests.sh b/tests/RunAllTests.sh deleted file mode 100755 index 3d756a540..000000000 --- a/tests/RunAllTests.sh +++ /dev/null @@ -1,4 +0,0 @@ -#/bin/bash -#put any pre-test execution commands here. -echo Running all tests -./AllTests $1 diff --git a/tests/TestHarness_cTest.cpp b/tests/TestHarness_cTest.cpp deleted file mode 100644 index 531c0b0b2..000000000 --- a/tests/TestHarness_cTest.cpp +++ /dev/null @@ -1,371 +0,0 @@ -/* - * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "CppUTest/TestHarness_c.h" - -#include "CppUTest/TestHarness.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTest/TestOutput.h" -#include "CppUTest/TestTestingFixture.h" -#include "CppUTest/PlatformSpecificFunctions.h" - - -extern "C" int setup_teardown_was_called_in_test_group_in_C; -extern "C" int test_was_called_in_test_group_in_C; -int setup_teardown_was_called_in_test_group_in_C = 0; -int test_was_called_in_test_group_in_C = 0; - -TEST_GROUP_C_WRAPPER(TestGroupInC) -{ - TEST_GROUP_C_SETUP_WRAPPER(TestGroupInC) - TEST_GROUP_C_TEARDOWN_WRAPPER(TestGroupInC) -}; - -TEST_C_WRAPPER(TestGroupInC, checkThatTheTestHasRun) - -/* - * This test is a bit strange. They use the fact that you can do -r2 for repeating the same run. - * When you do so, the same statics will be shared and therefore we can test whether the setup/teardown is run - * correctly. - */ - -TEST(TestGroupInC, setupHasBeenCalled) -{ - test_was_called_in_test_group_in_C++; - /* Increased in setup, decreased in teardown. So at this point it must be 1 also on a multiple run */ - LONGS_EQUAL(1, setup_teardown_was_called_in_test_group_in_C); -} - -static bool hasDestructorOfTheDestructorCheckedBeenCalled; - -class HasTheDestructorBeenCalledChecker -{ -public: - HasTheDestructorBeenCalledChecker(){} - ~HasTheDestructorBeenCalledChecker() { hasDestructorOfTheDestructorCheckedBeenCalled = true; } -}; - -TEST_GROUP(TestHarness_c) -{ - TestTestingFixture* fixture; - TEST_SETUP() - { - hasDestructorOfTheDestructorCheckedBeenCalled = false; - fixture = new TestTestingFixture(); - } - TEST_TEARDOWN() - { - delete fixture; - } -}; - -static void _failIntMethod() -{ - HasTheDestructorBeenCalledChecker checker; - CHECK_EQUAL_C_INT(1, 2); -} // LCOV_EXCL_LINE - -TEST(TestHarness_c, checkInt) -{ - CHECK_EQUAL_C_INT(2, 2); - fixture->setTestFunction(_failIntMethod); - fixture->runAllTests(); - fixture->assertPrintContains("expected <1 0x1>\n but was <2 0x2>"); - fixture->assertPrintContains("arness_c"); - CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled) -} - -static void _failRealMethod() -{ - HasTheDestructorBeenCalledChecker checker; - CHECK_EQUAL_C_REAL(1.0, 2.0, 0.5); -} // LCOV_EXCL_LINE - -TEST(TestHarness_c, checkReal) -{ - CHECK_EQUAL_C_REAL(1.0, 1.1, 0.5); - fixture->setTestFunction(_failRealMethod); - fixture->runAllTests(); - fixture->assertPrintContains("expected <1>\n but was <2>"); - fixture->assertPrintContains("arness_c"); - CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled) -} - -static void _failCharMethod() -{ - HasTheDestructorBeenCalledChecker checker; - CHECK_EQUAL_C_CHAR('a', 'c'); -} - -TEST(TestHarness_c, checkChar) -{ - CHECK_EQUAL_C_CHAR('a', 'a'); - fixture->setTestFunction(_failCharMethod); - fixture->runAllTests(); - fixture->assertPrintContains("expected \n but was "); - fixture->assertPrintContains("arness_c"); - CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled) -} - -static void _failUnsignedByteMethod() -{ - HasTheDestructorBeenCalledChecker checker; - CHECK_EQUAL_C_UBYTE(254, 253); -} - -TEST(TestHarness_c, checkUnsignedByte) -{ - CHECK_EQUAL_C_UBYTE(254, 254); - fixture->setTestFunction(_failUnsignedByteMethod); - fixture->runAllTests(); - fixture->assertPrintContains("expected <254>\n but was <253>"); - fixture->assertPrintContains("arness_c"); - CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled) -} - -static void _failSignedByteMethod() -{ - HasTheDestructorBeenCalledChecker checker; - CHECK_EQUAL_C_SBYTE(-3, -5); -} - -TEST(TestHarness_c, checkSignedByte) -{ - CHECK_EQUAL_C_SBYTE(-3, -3); - fixture->setTestFunction(_failSignedByteMethod); - fixture->runAllTests(); - fixture->assertPrintContains("expected <-3>\n but was <-5>"); - fixture->assertPrintContains("arness_c"); - CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled) -} - -static void _failStringMethod() -{ - HasTheDestructorBeenCalledChecker checker; - CHECK_EQUAL_C_STRING("Hello", "Hello World"); -} // LCOV_EXCL_LINE - -TEST(TestHarness_c, checkString) -{ - CHECK_EQUAL_C_STRING("Hello", "Hello"); - fixture->setTestFunction(_failStringMethod); - fixture->runAllTests(); - - StringEqualFailure failure(UtestShell::getCurrent(), "file", 1, "Hello", "Hello World", ""); - fixture->assertPrintContains(failure.getMessage()); - fixture->assertPrintContains("arness_c"); - CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled) -} - -static void _failPointerMethod() -{ - HasTheDestructorBeenCalledChecker checker; - CHECK_EQUAL_C_POINTER(NULL, (void *)0x1); -} - -TEST(TestHarness_c, checkPointer) -{ - CHECK_EQUAL_C_POINTER(NULL, NULL); - fixture->setTestFunction(_failPointerMethod); - fixture->runAllTests(); - fixture->assertPrintContains("expected <0x0>\n but was <0x1>"); - fixture->assertPrintContains("arness_c"); - CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled) -} - -static void _failBitsMethod() -{ - HasTheDestructorBeenCalledChecker checker; - CHECK_EQUAL_C_BITS(0x0001, (unsigned short)0x0003, 0xFFFF); -} - -TEST(TestHarness_c, checkBits) -{ - CHECK_EQUAL_C_POINTER(NULL, NULL); - fixture->setTestFunction(_failBitsMethod); - fixture->runAllTests(); - fixture->assertPrintContains("expected <00000000 00000001>\n\tbut was <00000000 00000011>"); - fixture->assertPrintContains("arness_c"); - CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled) -} - -static void _failTextMethod() -{ - HasTheDestructorBeenCalledChecker checker; - FAIL_TEXT_C("Booo"); -} // LCOV_EXCL_LINE - -TEST(TestHarness_c, checkFailText) -{ - fixture->setTestFunction(_failTextMethod); - fixture->runAllTests(); - fixture->assertPrintContains("Booo"); - fixture->assertPrintContains("arness_c"); - CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled) -} - -static void _failMethod() -{ - HasTheDestructorBeenCalledChecker checker; - FAIL_C(); -} // LCOV_EXCL_LINE - -TEST(TestHarness_c, checkFail) -{ - fixture->setTestFunction(_failMethod); - fixture->runAllTests(); - LONGS_EQUAL(1, fixture->getFailureCount()); - fixture->assertPrintContains("arness_c"); - CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled) -} - -static void _CheckMethod() -{ - HasTheDestructorBeenCalledChecker checker; - CHECK_C(false); -} // LCOV_EXCL_LINE - -TEST(TestHarness_c, checkCheck) -{ - CHECK_C(true); - fixture->setTestFunction(_CheckMethod); - fixture->runAllTests(); - LONGS_EQUAL(1, fixture->getFailureCount()); - CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled) -} - -#if CPPUTEST_USE_MEM_LEAK_DETECTION - -TEST(TestHarness_c, cpputest_malloc_out_of_memory) -{ - cpputest_malloc_set_out_of_memory(); - CHECK(0 == cpputest_malloc(100)); - - cpputest_malloc_set_not_out_of_memory(); - void * mem = cpputest_malloc(100); - CHECK(0 != mem); - cpputest_free(mem); -} - -TEST(TestHarness_c, cpputest_malloc_out_of_memory_after_n_mallocs) -{ - cpputest_malloc_set_out_of_memory_countdown(3); - void * m1 = cpputest_malloc(10); - void * m2 = cpputest_malloc(11); - void * m3 = cpputest_malloc(12); - CHECK(m1); - CHECK(m2); - POINTERS_EQUAL(0, m3); - cpputest_malloc_set_not_out_of_memory(); - cpputest_free(m1); - cpputest_free(m2); -} - -TEST(TestHarness_c, cpputest_malloc_out_of_memory_after_0_mallocs) -{ - cpputest_malloc_set_out_of_memory_countdown(0); - void * m1 = cpputest_malloc(10); - CHECK(m1 == 0); - cpputest_malloc_set_not_out_of_memory(); -} - -TEST(TestHarness_c, count_mallocs) -{ - cpputest_malloc_count_reset(); - void * m1 = cpputest_malloc(10); - void * m2 = cpputest_malloc(11); - void * m3 = cpputest_malloc(12); - cpputest_free(m1); - cpputest_free(m2); - cpputest_free(m3); - LONGS_EQUAL(3, cpputest_malloc_get_count()); -} - -TEST(TestHarness_c, cpputest_calloc) -{ - void * mem = cpputest_calloc(10, 10); - CHECK(0 != mem); - cpputest_free(mem); -} - -TEST(TestHarness_c, cpputest_realloc_larger) -{ - const char* number_string = "123456789"; - - char* mem1 = (char*) cpputest_malloc(10); - - SimpleString::StrNCpy(mem1, number_string, 10); - - CHECK(mem1 != 0); - - char* mem2 = (char*) cpputest_realloc(mem1, 1000); - - CHECK(mem2 != 0); - STRCMP_EQUAL(number_string, mem2); - - cpputest_free(mem2); -} - -#include "CppUTest/MemoryLeakDetector.h" - -TEST(TestHarness_c, macros) -{ -#if CPPUTEST_USE_MALLOC_MACROS - MemoryLeakDetector* memLeakDetector = MemoryLeakWarningPlugin::getGlobalDetector(); - int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); -#endif - void* mem1 = malloc(10); - void* mem2 = calloc(10, 20); - void* mem3 = realloc(mem2, 100); -#if CPPUTEST_USE_MALLOC_MACROS - LONGS_EQUAL(memLeaks + 2, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); -#endif - free(mem1); - free(mem3); -#if CPPUTEST_USE_MALLOC_MACROS - LONGS_EQUAL(memLeaks, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); -#endif - -} - -TEST(TestHarness_c, callocInitializedToZero) -{ - char* mem = (char*) calloc(20, sizeof(char)); - for (int i = 0; i < 20; i++) - CHECK(mem[i] == 0); - free(mem); -} - -TEST(TestHarness_c, callocShouldReturnNULLWhenOutOfMeory) -{ - cpputest_malloc_set_out_of_memory_countdown(0); - void * m = cpputest_calloc(1, 1); - CHECK(m == 0); - cpputest_malloc_set_not_out_of_memory(); -} -#endif - diff --git a/tests/TestMemoryAllocatorTest.cpp b/tests/TestMemoryAllocatorTest.cpp deleted file mode 100644 index 7c6017f36..000000000 --- a/tests/TestMemoryAllocatorTest.cpp +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "CppUTest/TestHarness.h" -#include "CppUTest/TestMemoryAllocator.h" -#include "CppUTest/PlatformSpecificFunctions.h" - -TEST_GROUP(TestMemoryAllocatorTest) -{ - TestMemoryAllocator* allocator; - - void setup() - { - allocator = NULL; - } - - void teardown() - { - delete allocator; - } -}; - -TEST(TestMemoryAllocatorTest, SetCurrentNewAllocator) -{ - allocator = new TestMemoryAllocator("new allocator for test"); - setCurrentNewAllocator(allocator); - POINTERS_EQUAL(allocator, getCurrentNewAllocator()); - setCurrentNewAllocatorToDefault(); - POINTERS_EQUAL(defaultNewAllocator(), getCurrentNewAllocator()); -} - -TEST(TestMemoryAllocatorTest, SetCurrentNewArrayAllocator) -{ - allocator = new TestMemoryAllocator("new array allocator for test"); - setCurrentNewArrayAllocator(allocator); - POINTERS_EQUAL(allocator, getCurrentNewArrayAllocator()); - setCurrentNewArrayAllocatorToDefault(); - POINTERS_EQUAL(defaultNewArrayAllocator(), getCurrentNewArrayAllocator()); -} - -TEST(TestMemoryAllocatorTest, SetCurrentMallocAllocator) -{ - allocator = new TestMemoryAllocator("malloc_allocator"); - setCurrentMallocAllocator(allocator); - POINTERS_EQUAL(allocator, getCurrentMallocAllocator()); - setCurrentMallocAllocatorToDefault(); - POINTERS_EQUAL(defaultMallocAllocator(), getCurrentMallocAllocator()); -} - -TEST(TestMemoryAllocatorTest, MemoryAllocation) -{ - allocator = new TestMemoryAllocator(); - allocator->free_memory(allocator->alloc_memory(100, "file", 1), "file", 1); -} - -TEST(TestMemoryAllocatorTest, MallocNames) -{ - STRCMP_EQUAL("Standard Malloc Allocator", defaultMallocAllocator()->name()); - STRCMP_EQUAL("malloc", defaultMallocAllocator()->alloc_name()); - STRCMP_EQUAL("free", defaultMallocAllocator()->free_name()); -} - -TEST(TestMemoryAllocatorTest, NewNames) -{ - STRCMP_EQUAL("Standard New Allocator", defaultNewAllocator()->name()); - STRCMP_EQUAL("new", defaultNewAllocator()->alloc_name()); - STRCMP_EQUAL("delete", defaultNewAllocator()->free_name()); -} - -TEST(TestMemoryAllocatorTest, NewArrayNames) -{ - STRCMP_EQUAL("Standard New [] Allocator", defaultNewArrayAllocator()->name()); - STRCMP_EQUAL("new []", defaultNewArrayAllocator()->alloc_name()); - STRCMP_EQUAL("delete []", defaultNewArrayAllocator()->free_name()); -} - -TEST(TestMemoryAllocatorTest, NullUnknownAllocation) -{ - allocator = new NullUnknownAllocator; - allocator->free_memory(allocator->alloc_memory(100, "file", 1), "file", 1); -} - -TEST(TestMemoryAllocatorTest, NullUnknownNames) -{ - allocator = new NullUnknownAllocator; - STRCMP_EQUAL("Null Allocator", allocator->name()); - STRCMP_EQUAL("unknown", allocator->alloc_name()); - STRCMP_EQUAL("unknown", allocator->free_name()); -} - -#define MAX_SIZE_FOR_ALLOC ((size_t) -1 > (unsigned short)-1) ? (size_t) -97 : (size_t) -1 - -static void failTryingToAllocateTooMuchMemory(void) -{ - TestMemoryAllocator allocator; - allocator.alloc_memory(MAX_SIZE_FOR_ALLOC, "file", 1); -} // LCOV_EXCL_LINE - -#include "CppUTest/TestTestingFixture.h" - -TEST(TestMemoryAllocatorTest, TryingToAllocateTooMuchFailsTest) -{ - TestTestingFixture fixture; - fixture.setTestFunction(&failTryingToAllocateTooMuchMemory); - fixture.runAllTests(); - fixture.assertPrintContains("malloc returned null pointer"); -} - -#if CPPUTEST_USE_MEM_LEAK_DETECTION -#if CPPUTEST_USE_MALLOC_MACROS - -// FailableMemoryAllocator must be global. Otherwise, it does not exist when memory leak detector -// reports memory leaks. -static FailableMemoryAllocator failableMallocAllocator("Failable Malloc Allocator", "malloc", "free"); - - -TEST_GROUP(FailableMemoryAllocator) -{ - TestTestingFixture *fixture; - void setup() - { - fixture = new TestTestingFixture; - failableMallocAllocator.clearFailedAllocs(); - setCurrentMallocAllocator(&failableMallocAllocator); - } - void teardown() - { - failableMallocAllocator.checkAllFailedAllocsWereDone(); - setCurrentMallocAllocatorToDefault(); - delete fixture; - } -}; - -TEST(FailableMemoryAllocator, MallocWorksNormallyIfNotAskedToFail) -{ - int *memory = (int*)malloc(sizeof(int)); - CHECK(memory != NULL); - free(memory); -} - -TEST(FailableMemoryAllocator, FailFirstMalloc) -{ - failableMallocAllocator.failAllocNumber(1); - POINTERS_EQUAL(NULL, (int*)malloc(sizeof(int))); -} - -TEST(FailableMemoryAllocator, FailSecondAndFourthMalloc) -{ - failableMallocAllocator.failAllocNumber(2); - failableMallocAllocator.failAllocNumber(4); - int *memory1 = (int*)malloc(sizeof(int)); - int *memory2 = (int*)malloc(sizeof(int)); - int *memory3 = (int*)malloc(sizeof(int)); - int *memory4 = (int*)malloc(sizeof(int)); - - CHECK(NULL != memory1); - POINTERS_EQUAL(NULL, memory2); - CHECK(NULL != memory3); - POINTERS_EQUAL(NULL, memory4); - - free(memory1); - free(memory3); -} - -static void _failingAllocIsNeverDone() -{ - failableMallocAllocator.failAllocNumber(1); - failableMallocAllocator.failAllocNumber(2); - failableMallocAllocator.failAllocNumber(3); - malloc(sizeof(int)); - malloc(sizeof(int)); - failableMallocAllocator.checkAllFailedAllocsWereDone(); -} - -TEST(FailableMemoryAllocator, CheckAllFailingAllocsWereDone) -{ - fixture->setTestFunction(_failingAllocIsNeverDone); - - fixture->runAllTests(); - - LONGS_EQUAL(1, fixture->getFailureCount()); - fixture->assertPrintContains("Expected allocation number 3 was never done"); - failableMallocAllocator.clearFailedAllocs(); -} - -TEST(FailableMemoryAllocator, FailFirstAllocationAtGivenLine) -{ - failableMallocAllocator.failNthAllocAt(1, __FILE__, __LINE__ + 2); - - POINTERS_EQUAL(NULL, malloc(sizeof(int))); -} - -TEST(FailableMemoryAllocator, FailThirdAllocationAtGivenLine) -{ - int *memory[10]; - int allocation; - failableMallocAllocator.failNthAllocAt(3, __FILE__, __LINE__ + 4); - - for (allocation = 1; allocation <= 10; allocation++) - { - memory[allocation - 1] = (int *)malloc(sizeof(int)); - if (memory[allocation - 1] == NULL) - break; - } - - LONGS_EQUAL(3, allocation); - free(memory[0]); free(memory[1]); -} - -static void _failingLocationAllocIsNeverDone() -{ - failableMallocAllocator.failNthAllocAt(1, "TestMemoryAllocatorTest.cpp", __LINE__); - failableMallocAllocator.checkAllFailedAllocsWereDone(); -} - -TEST(FailableMemoryAllocator, CheckAllFailingLocationAllocsWereDone) -{ - fixture->setTestFunction(_failingLocationAllocIsNeverDone); - - fixture->runAllTests(); - - LONGS_EQUAL(1, fixture->getFailureCount()); - fixture->assertPrintContains("Expected failing alloc at TestMemoryAllocatorTest.cpp:"); - fixture->assertPrintContains("was never done"); - failableMallocAllocator.clearFailedAllocs(); -} - -#endif -#endif diff --git a/tests/UtestTest.cpp b/tests/UtestTest.cpp deleted file mode 100644 index 64bcbbf6e..000000000 --- a/tests/UtestTest.cpp +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "CppUTest/TestHarness.h" -#include "CppUTest/TestOutput.h" -#include "CppUTest/TestTestingFixture.h" -#include "CppUTest/PlatformSpecificFunctions.h" - -TEST_GROUP(UtestShell) -{ - TestTestingFixture fixture; -}; - -static void _failMethod() -{ - FAIL("This test fails"); -} - -static void _passingTestMethod() -{ - CHECK(true); -} - -static void _passingCheckEqualTestMethod() -{ - CHECK_EQUAL(1, 1); -} - -static void _exitTestMethod() -{ - TEST_EXIT; - FAIL("Should not get here"); -} - -TEST(UtestShell, compareDoubles) -{ - double zero = 0.0; - double not_a_number = zero / zero; - double infinity = 1 / zero; - CHECK(doubles_equal(1.0, 1.001, 0.01)); - CHECK(!doubles_equal(not_a_number, 1.001, 0.01)); - CHECK(!doubles_equal(1.0, not_a_number, 0.01)); - CHECK(!doubles_equal(1.0, 1.001, not_a_number)); - CHECK(!doubles_equal(1.0, 1.1, 0.05)); - CHECK(!doubles_equal(infinity, 1.0, 0.01)); - CHECK(!doubles_equal(1.0, infinity, 0.01)); - CHECK(doubles_equal(1.0, -1.0, infinity)); - CHECK(doubles_equal(infinity, infinity, 0.01)); - CHECK(doubles_equal(infinity, infinity, infinity)); - double a = 1.2345678; - CHECK(doubles_equal(a, a, 0.000000001)); -} - -TEST(UtestShell, FailWillIncreaseTheAmountOfChecks) -{ - fixture.setTestFunction(_failMethod); - fixture.runAllTests(); - LONGS_EQUAL(1, fixture.getCheckCount()); -} - -TEST(UtestShell, PassedCheckEqualWillIncreaseTheAmountOfChecks) -{ - fixture.setTestFunction(_passingCheckEqualTestMethod); - fixture.runAllTests(); - LONGS_EQUAL(1, fixture.getCheckCount()); -} - -IGNORE_TEST(UtestShell, IgnoreTestAccessingFixture) -{ - CHECK(&fixture != NULL); -} - -TEST(UtestShell, MacrosUsedInSetup) -{ - IGNORE_ALL_LEAKS_IN_TEST(); - fixture.setSetup(_failMethod); - fixture.setTestFunction(_passingTestMethod); - fixture.runAllTests(); - LONGS_EQUAL(1, fixture.getFailureCount()); -} - -TEST(UtestShell, MacrosUsedInTearDown) -{ - IGNORE_ALL_LEAKS_IN_TEST(); - fixture.setTeardown(_failMethod); - fixture.setTestFunction(_passingTestMethod); - fixture.runAllTests(); - LONGS_EQUAL(1, fixture.getFailureCount()); -} - -TEST(UtestShell, ExitLeavesQuietly) -{ - fixture.setTestFunction(_exitTestMethod); - fixture.runAllTests(); - LONGS_EQUAL(0, fixture.getFailureCount()); -} - - - -static int teardownCalled = 0; - -static void _teardownMethod() -{ - teardownCalled++; -} - -TEST(UtestShell, TeardownCalledAfterTestFailure) -{ - teardownCalled = 0; - IGNORE_ALL_LEAKS_IN_TEST(); - fixture.setTeardown(_teardownMethod); - fixture.setTestFunction(_failMethod); - fixture.runAllTests(); - LONGS_EQUAL(1, fixture.getFailureCount()); - LONGS_EQUAL(1, teardownCalled); -} - -static int stopAfterFailure = 0; -static void _stopAfterFailureMethod() -{ - FAIL("fail"); - stopAfterFailure++; -} - -TEST(UtestShell, TestStopsAfterTestFailure) -{ - IGNORE_ALL_LEAKS_IN_TEST(); - stopAfterFailure = 0; - fixture.setTestFunction(_stopAfterFailureMethod); - fixture.runAllTests(); - CHECK(fixture.hasTestFailed()); - LONGS_EQUAL(1, fixture.getFailureCount()); - LONGS_EQUAL(0, stopAfterFailure); -} - -TEST(UtestShell, TestStopsAfterSetupFailure) -{ - stopAfterFailure = 0; - fixture.setSetup(_stopAfterFailureMethod); - fixture.setTeardown(_stopAfterFailureMethod); - fixture.setTestFunction(_failMethod); - fixture.runAllTests(); - LONGS_EQUAL(2, fixture.getFailureCount()); - LONGS_EQUAL(0, stopAfterFailure); -} - -class defaultUtestShell: public UtestShell -{ -}; - -TEST(UtestShell, this_test_covers_the_UtestShell_createTest_and_Utest_testBody_methods) -{ - defaultUtestShell shell; - fixture.addTest(&shell); - fixture.runAllTests(); - LONGS_EQUAL(2, fixture.result_->getTestCount()); -} - -static void StubPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result) -{ - result->addFailure(TestFailure(shell, "Failed in separate process")); -} - -TEST(UtestShell, RunInSeparateProcessTest) -{ - UT_PTR_SET(PlatformSpecificRunTestInASeperateProcess, StubPlatformSpecificRunTestInASeperateProcess); - fixture.registry_->setRunTestsInSeperateProcess(); - fixture.runAllTests(); - fixture.assertPrintContains("Failed in separate process"); -} - -#ifndef CPPUTEST_HAVE_FORK - -IGNORE_TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) {} - -#else - -TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) -{ - fixture.setTestFunction(UtestShell::crash); - fixture.registry_->setRunTestsInSeperateProcess(); - fixture.runAllTests(); - fixture.assertPrintContains("Failed in separate process - killed by signal"); - - /* Signal 11 usually happens, but with clang3.7 on Linux, it produced signal 4 */ - CHECK(fixture.getOutput().contains("signal 11") || fixture.getOutput().contains("signal 4")); -} - -#endif - -#if CPPUTEST_USE_STD_CPP_LIB - -static bool destructorWasCalledOnFailedTest = false; - -static void _destructorCalledForLocalObjects() -{ - SetBooleanOnDestructorCall pleaseCallTheDestructor(destructorWasCalledOnFailedTest); - destructorWasCalledOnFailedTest = false; - FAIL("fail"); -} - -TEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails) -{ - fixture.setTestFunction(_destructorCalledForLocalObjects); - fixture.runAllTests(); - CHECK(destructorWasCalledOnFailedTest); -} - -#endif - -TEST_GROUP(IgnoredUtestShell) -{ - TestTestingFixture fixture; - IgnoredUtestShell ignoredTest; - ExecFunctionTestShell normalUtestShell; - - void setup() _override - { - fixture.addTest(&ignoredTest); - fixture.addTest(&normalUtestShell); - } -}; - -TEST(IgnoredUtestShell, doesIgnoreCount) -{ - fixture.runAllTests(); - LONGS_EQUAL(1, fixture.getIgnoreCount()); -} - -TEST(IgnoredUtestShell, printsIGNORE_TESTwhenVerbose) -{ - fixture.output_->verbose(); - fixture.runAllTests(); - fixture.assertPrintContains("IGNORE_TEST"); -} - -TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenIncreaseRunCount) -{ - ignoredTest.setRunIgnored(); - fixture.runAllTests(); - LONGS_EQUAL(3, fixture.getRunCount()); - LONGS_EQUAL(0, fixture.getIgnoreCount()); -} - -TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenIncreaseIgnoredCount) -{ - fixture.runAllTests(); - LONGS_EQUAL(2, fixture.getRunCount()); - LONGS_EQUAL(1, fixture.getIgnoreCount()); -} - -TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedWillNotInfluenceNormalTestCount) -{ - normalUtestShell.setRunIgnored(); - fixture.runAllTests(); - LONGS_EQUAL(2, fixture.getRunCount()); - LONGS_EQUAL(1, fixture.getIgnoreCount()); -} - -TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenReturnTESTInFormattedName) -{ - ignoredTest.setGroupName("TestGroup"); - ignoredTest.setTestName("TestName"); - ignoredTest.setRunIgnored(); - fixture.runAllTests(); - STRCMP_EQUAL("TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString()); -} - -TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenReturnIGNORETESTInFormattedName) -{ - ignoredTest.setGroupName("TestGroup"); - ignoredTest.setTestName("TestName"); - fixture.runAllTests(); - STRCMP_EQUAL("IGNORE_TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString()); -} - -TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenWillRunReturnFalse) -{ - CHECK_FALSE(ignoredTest.willRun()); -} - -TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenWillRunReturnTrue) -{ - ignoredTest.setRunIgnored(); - CHECK_TRUE(ignoredTest.willRun()); -} - -TEST_BASE(MyOwnTest) -{ - MyOwnTest() : - inTest(false) - { - } - bool inTest; - - void setup() - { - CHECK(!inTest); - inTest = true; - } - void teardown() - { - CHECK(inTest); - inTest = false; - } -}; - -TEST_GROUP_BASE(UtestMyOwn, MyOwnTest) -{ -}; - -TEST(UtestMyOwn, test) -{ - CHECK(inTest); -} - -class NullParameterTest: public UtestShell -{ -}; - -TEST(UtestMyOwn, NullParameters) -{ - NullParameterTest nullTest; /* Bug fix tests for creating a test without a name, fix in SimpleString */ - TestFilter emptyFilter; - CHECK(nullTest.shouldRun(&emptyFilter, &emptyFilter)); -} - -class AllocateAndDeallocateInConstructorAndDestructor -{ - char* memory_; - char* morememory_; -public: - AllocateAndDeallocateInConstructorAndDestructor() - { - memory_ = new char[100]; - morememory_ = NULL; - } - void allocateMoreMemory() - { - morememory_ = new char[123]; - } - - ~AllocateAndDeallocateInConstructorAndDestructor() - { - delete [] memory_; - delete [] morememory_; - } -}; - -TEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks) -{ - AllocateAndDeallocateInConstructorAndDestructor dummy; -}; - -TEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName) -{ - dummy.allocateMoreMemory(); -} -