From e674cfe759b20c6b78becbc50d8f9f644d32ea8a Mon Sep 17 00:00:00 2001 From: Bas Vodde Date: Wed, 7 May 2014 15:39:43 +0800 Subject: [PATCH] Fix the line endings --- CppUTest.dsw | 88 +- CppUTest.vcproj | 974 ++++++------- CppUTest.vcxproj | 418 +++--- CppUTest_VS2008.sln | 58 +- build/StaticLibMakefile | 20 +- build/alltests.mmp | 102 +- build/bld.inf | 98 +- examples/AllTests/AllTests.cpp | 114 +- examples/AllTests/CircularBufferTest.cpp | 520 +++---- examples/AllTests/HelloTest.cpp | 120 +- examples/ApplicationLib/CircularBuffer.cpp | 200 +-- examples/ApplicationLib/CircularBuffer.h | 144 +- examples/ApplicationLib/hello.c | 72 +- examples/ApplicationLib/hello.h | 86 +- examples/CppUTestExample.dsw | 88 +- include/CppUTestExt/OrderedTest.h | 164 +-- include/Platforms/Gcc/Platform.h | 62 +- include/Platforms/StarterKit/Platform.h | 62 +- lib/NoteOnVisualStudio.txt | 8 +- makeVS2008.bat | 18 +- makeVS2010.bat | 16 +- makeVc6.bat | 32 +- scripts/CppUnitTemplates/ClassName.cpp | 20 +- scripts/CppUnitTemplates/ClassName.h | 46 +- scripts/CppUnitTemplates/ClassNameC.c | 32 +- scripts/CppUnitTemplates/ClassNameC.h | 24 +- .../ClassNameCMultipleInstance.c | 46 +- .../ClassNameCMultipleInstance.h | 32 +- .../ClassNameCMultipleInstanceTest.cpp | 82 +- .../CppUnitTemplates/ClassNameCPolymorphic.c | 46 +- .../CppUnitTemplates/ClassNameCPolymorphic.h | 36 +- scripts/CppUnitTemplates/ClassNameCTest.cpp | 50 +- scripts/CppUnitTemplates/ClassNameTest.cpp | 66 +- scripts/CppUnitTemplates/InterfaceCTest.cpp | 48 +- scripts/CppUnitTemplates/InterfaceTest.cpp | 68 +- scripts/CppUnitTemplates/MockClassName.h | 58 +- scripts/CppUnitTemplates/MockClassNameC.c | 32 +- scripts/CppUnitTemplates/MockClassNameC.h | 26 +- .../ProjectTemplate/tests/AllTests.cpp | 16 +- .../UnityTemplates/ClassNameCIoDriverTest.cpp | 56 +- .../ClassNameCMultipleInstanceTest.cpp | 56 +- scripts/UnityTemplates/ClassNameCTest.cpp | 52 +- scripts/UnityTemplates/FunctionNameCTest.cpp | 48 +- scripts/UnityTemplates/InterfaceCTest.cpp | 50 +- scripts/squeeze.sh | 4 +- scripts/templates/ClassName.cpp | 20 +- scripts/templates/ClassName.h | 46 +- scripts/templates/ClassNameC.c | 22 +- scripts/templates/ClassNameC.h | 26 +- scripts/templates/ClassNameCIoDriverTest.cpp | 54 +- .../templates/ClassNameCMultipleInstance.c | 42 +- .../templates/ClassNameCMultipleInstance.h | 28 +- .../ClassNameCMultipleInstanceTest.cpp | 54 +- scripts/templates/ClassNameCPolymorphic.c | 44 +- scripts/templates/ClassNameCPolymorphic.h | 32 +- scripts/templates/ClassNameCTest.cpp | 50 +- scripts/templates/ClassNameTest.cpp | 48 +- scripts/templates/FunctionNameC.c | 10 +- scripts/templates/FunctionNameC.h | 24 +- scripts/templates/FunctionNameCTest.cpp | 46 +- scripts/templates/InterfaceCTest.cpp | 50 +- scripts/templates/InterfaceTest.cpp | 50 +- scripts/templates/MockClassName.h | 58 +- scripts/templates/MockClassNameC.c | 22 +- scripts/templates/MockClassNameC.h | 26 +- .../ProjectTemplate/tests/AllTests.cpp | 16 +- src/CppUTest/CommandLineArguments.cpp | 386 ++--- src/CppUTest/CommandLineTestRunner.cpp | 292 ++-- src/CppUTest/JUnitTestOutput.cpp | 560 ++++---- src/CppUTest/MemoryLeakDetector.cpp | 1242 ++++++++--------- src/CppUTest/MemoryLeakWarningPlugin.cpp | 908 ++++++------ src/CppUTest/SimpleString.cpp | 1030 +++++++------- src/CppUTest/TestFailure.cpp | 504 +++---- src/CppUTest/TestHarness_c.cpp | 326 ++--- src/CppUTest/TestMemoryAllocator.cpp | 408 +++--- src/CppUTest/TestOutput.cpp | 506 +++---- src/CppUTest/TestPlugin.cpp | 346 ++--- src/CppUTest/TestRegistry.cpp | 432 +++--- src/CppUTest/TestResult.cpp | 284 ++-- src/CppUTestExt/OrderedTest.cpp | 264 ++-- src/Platforms/Gcc/UtestPlatform.cpp | 552 ++++---- src/Platforms/GccNoStdC/UtestPlatform.cpp | 542 +++---- src/Platforms/Iar/UtestPlatform.cpp | 458 +++--- .../StarterKit/StarterMemoryLeakWarning.cpp | 450 +++--- src/Platforms/StarterKit/UtestPlatform.cpp | 154 +- src/Platforms/Symbian/UtestPlatform.cpp | 386 ++--- src/Platforms/VisualCpp/UtestPlatform.cpp | 474 +++---- tests/AllTests.cpp | 76 +- tests/AllTests.h | 86 +- tests/AllTests.vcproj | 822 +++++------ tests/AllTests.vcxproj | 392 +++--- tests/CommandLineTestRunnerTest.cpp | 192 +-- tests/CppUTestExt/AllTests.cpp | 122 +- tests/CppUTestExt/OrderedTestTest.cpp | 366 ++--- tests/JUnitOutputTest.cpp | 1182 ++++++++-------- tests/MemoryLeakDetectorTest.cpp | 1104 +++++++-------- tests/NullTestTest.cpp | 118 +- tests/PluginTest.cpp | 364 ++--- tests/SetPluginTest.cpp | 266 ++-- tests/SimpleStringTest.cpp | 1226 ++++++++-------- tests/TestFailureNaNTest.cpp | 156 +-- tests/TestFailureTest.cpp | 398 +++--- tests/TestHarness_cTest.cpp | 612 ++++---- tests/TestInstallerTest.cpp | 126 +- tests/TestMemoryAllocatorTest.cpp | 226 +-- tests/TestRegistryTest.cpp | 570 ++++---- tests/TestResultTest.cpp | 134 +- tests/UtestTest.cpp | 486 +++---- 108 files changed, 12377 insertions(+), 12377 deletions(-) diff --git a/CppUTest.dsw b/CppUTest.dsw index 75236ece5..cab2e26f9 100644 --- a/CppUTest.dsw +++ b/CppUTest.dsw @@ -1,44 +1,44 @@ -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> -{{{ -}}} - -############################################################################### - +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.vcproj b/CppUTest.vcproj index ac4622dde..781f8dc20 100644 --- a/CppUTest.vcproj +++ b/CppUTest.vcproj @@ -1,487 +1,487 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CppUTest.vcxproj b/CppUTest.vcxproj index 2b7ae74cb..e60107bc5 100644 --- a/CppUTest.vcxproj +++ b/CppUTest.vcxproj @@ -1,210 +1,210 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {F468F539-27BD-468E-BE64-DDE641400B51} - - - - StaticLibrary - false - MultiByte - - - StaticLibrary - false - MultiByte - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.30319.1 - .\Debug\ - .\Debug\ - .\Release\ - .\Release\ - $(ProjectName)d - - - - Disabled - .\include;.\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) - _LIB;WIN32;_DEBUG;%(PreprocessorDefinitions) - EnableFastChecks - MultiThreadedDebugDLL - .\Debug/CppUTestd.pch - .\Debug/ - .\Debug/ - .\Debug/ - Level3 - true - EditAndContinue - ..\include\Platforms\VisualCpp\Platform.h;..\include\CppUTest\MemoryLeakDetectorMallocMacros.h;%(ForcedIncludeFiles) - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - - - $(OutDir)CppUTestd.lib - true - winmm.lib;%(AdditionalDependencies) - - - true - .\Debug/CppUTestd.bsc - - - - - - - copy $(OutDir)CppUTestd.lib lib\vs2010 -copy $(OutDir)CppUTestd.lib lib\CppUTestd.lib -copy $(OutDir)vc100.pdb lib\vs2010 - - - - true - - - - - MaxSpeed - .\include;.\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) - OnlyExplicitInline - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - true - MultiThreaded - true - .\Release/CppUTest.pch - .\Release/ - .\Release/ - .\Release/ - Level3 - true - ..\include\Platforms\VisualCpp\Platform.h;..\include\CppUTest\MemoryLeakDetectorMallocMacros.h;%(ForcedIncludeFiles) - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - - - $(OutDir)CppUTest.lib - true - winmm.lib;%(AdditionalDependencies) - - - true - .\Release/CppUTest.bsc - - - - - - - copy $(OutDir)CppUTest.lib lib\vs2010 -copy $(OutDir)CppUTest.lib lib\CppUTest.lib - - - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - %(AdditionalIncludeDirectories) - %(PreprocessorDefinitions) - %(PreprocessorDefinitions) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + + {F468F539-27BD-468E-BE64-DDE641400B51} + + + + StaticLibrary + false + MultiByte + + + StaticLibrary + false + MultiByte + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + .\Debug\ + .\Debug\ + .\Release\ + .\Release\ + $(ProjectName)d + + + + Disabled + .\include;.\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) + _LIB;WIN32;_DEBUG;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + .\Debug/CppUTestd.pch + .\Debug/ + .\Debug/ + .\Debug/ + Level3 + true + EditAndContinue + ..\include\Platforms\VisualCpp\Platform.h;..\include\CppUTest\MemoryLeakDetectorMallocMacros.h;%(ForcedIncludeFiles) + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)CppUTestd.lib + true + winmm.lib;%(AdditionalDependencies) + + + true + .\Debug/CppUTestd.bsc + + + + + + + copy $(OutDir)CppUTestd.lib lib\vs2010 +copy $(OutDir)CppUTestd.lib lib\CppUTestd.lib +copy $(OutDir)vc100.pdb lib\vs2010 + + + + true + + + + + MaxSpeed + .\include;.\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) + OnlyExplicitInline + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + true + MultiThreaded + true + .\Release/CppUTest.pch + .\Release/ + .\Release/ + .\Release/ + Level3 + true + ..\include\Platforms\VisualCpp\Platform.h;..\include\CppUTest\MemoryLeakDetectorMallocMacros.h;%(ForcedIncludeFiles) + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)CppUTest.lib + true + winmm.lib;%(AdditionalDependencies) + + + true + .\Release/CppUTest.bsc + + + + + + + copy $(OutDir)CppUTest.lib lib\vs2010 +copy $(OutDir)CppUTest.lib lib\CppUTest.lib + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CppUTest_VS2008.sln b/CppUTest_VS2008.sln index 0f0c34da1..f4589297d 100644 --- a/CppUTest_VS2008.sln +++ b/CppUTest_VS2008.sln @@ -1,29 +1,29 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual C++ Express 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AllTests", "tests\AllTests.vcproj", "{913088F6-37C0-4195-80E9-548C7C5303CB}" - ProjectSection(ProjectDependencies) = postProject - {F468F539-27BD-468E-BE64-DDE641400B51} = {F468F539-27BD-468E-BE64-DDE641400B51} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CppUTest", "CppUTest.vcproj", "{F468F539-27BD-468E-BE64-DDE641400B51}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - 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}.Release|Win32.ActiveCfg = Release|Win32 - {913088F6-37C0-4195-80E9-548C7C5303CB}.Release|Win32.Build.0 = Release|Win32 - {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}.Release|Win32.ActiveCfg = Release|Win32 - {F468F539-27BD-468E-BE64-DDE641400B51}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual C++ Express 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AllTests", "tests\AllTests.vcproj", "{913088F6-37C0-4195-80E9-548C7C5303CB}" + ProjectSection(ProjectDependencies) = postProject + {F468F539-27BD-468E-BE64-DDE641400B51} = {F468F539-27BD-468E-BE64-DDE641400B51} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CppUTest", "CppUTest.vcproj", "{F468F539-27BD-468E-BE64-DDE641400B51}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + 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}.Release|Win32.ActiveCfg = Release|Win32 + {913088F6-37C0-4195-80E9-548C7C5303CB}.Release|Win32.Build.0 = Release|Win32 + {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}.Release|Win32.ActiveCfg = Release|Win32 + {F468F539-27BD-468E-BE64-DDE641400B51}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/build/StaticLibMakefile b/build/StaticLibMakefile index 9f31b0766..cb4ff0b9c 100644 --- a/build/StaticLibMakefile +++ b/build/StaticLibMakefile @@ -1,10 +1,10 @@ - -$(CPPUTEST_TARGET) : $(OBJS) - ar -rc $@ $(OBJS) - $(RANLIB) $@ - if [ "$(LIBDIR)" != "." ]; then\ - mv $@ $(LIBDIR) ; \ - fi - -all: $(CPPUTEST_TARGET) - + +$(CPPUTEST_TARGET) : $(OBJS) + ar -rc $@ $(OBJS) + $(RANLIB) $@ + if [ "$(LIBDIR)" != "." ]; then\ + mv $@ $(LIBDIR) ; \ + fi + +all: $(CPPUTEST_TARGET) + diff --git a/build/alltests.mmp b/build/alltests.mmp index be3d1b69b..3f13ea08a 100644 --- a/build/alltests.mmp +++ b/build/alltests.mmp @@ -1,51 +1,51 @@ -/* - * Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde and Timo Puronen - * 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. - */ - -TARGET cpputest.exe -TARGETTYPE exe -UID 0x00000000 0x03A6305A - -USERINCLUDE ..\include ..\include\CppUTest ..\include\Platforms\Symbian ..\tests -SYSTEMINCLUDE \epoc32\include \epoc32\include\stdapis - -STATICLIBRARY libcrt0.lib -STATICLIBRARY cpputest.lib - -LIBRARY euser.lib libc.lib libm.lib libpthread.lib - - -SOURCEPATH ..\tests -SOURCE FailureTest.cpp MemoryLeakWarningTest.cpp NullTestTest.cpp -SOURCE SimpleStringTest.cpp TestInstallerTest.cpp -SOURCE TestOutputTest.cpp TestRegistryTest.cpp UtestTest.cpp CommandLineTestRunnerTest.cpp JUnitOutputTest.cpp -SOURCE TestHarness_cTest.cpp - -SOURCEPATH ..\tests -SOURCE AllTests.cpp TestResultTest.cpp PluginTest.cpp SetPluginTest.cpp - -MACRO UT_NEW_MACROS_DISABLED -MACRO UT_NEW_OVERRIDES_DISABLED +/* + * Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde and Timo Puronen + * 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. + */ + +TARGET cpputest.exe +TARGETTYPE exe +UID 0x00000000 0x03A6305A + +USERINCLUDE ..\include ..\include\CppUTest ..\include\Platforms\Symbian ..\tests +SYSTEMINCLUDE \epoc32\include \epoc32\include\stdapis + +STATICLIBRARY libcrt0.lib +STATICLIBRARY cpputest.lib + +LIBRARY euser.lib libc.lib libm.lib libpthread.lib + + +SOURCEPATH ..\tests +SOURCE FailureTest.cpp MemoryLeakWarningTest.cpp NullTestTest.cpp +SOURCE SimpleStringTest.cpp TestInstallerTest.cpp +SOURCE TestOutputTest.cpp TestRegistryTest.cpp UtestTest.cpp CommandLineTestRunnerTest.cpp JUnitOutputTest.cpp +SOURCE TestHarness_cTest.cpp + +SOURCEPATH ..\tests +SOURCE AllTests.cpp TestResultTest.cpp PluginTest.cpp SetPluginTest.cpp + +MACRO UT_NEW_MACROS_DISABLED +MACRO UT_NEW_OVERRIDES_DISABLED diff --git a/build/bld.inf b/build/bld.inf index f9ca450ed..7894587e7 100644 --- a/build/bld.inf +++ b/build/bld.inf @@ -1,49 +1,49 @@ -/* - * Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde and Timo Puronen - * 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. - */ - -PRJ_PLATFORMS -DEFAULT - -PRJ_EXPORTS -..\include\CppUTest\TestHarness.h \epoc32\include\CppUTest\TestHarness.h -..\include\CppUTest\Utest.h \epoc32\include\CppUTest\Utest.h -..\include\CppUTest\UtestMacros.h \epoc32\include\CppUTest\UtestMacros.h -..\include\CppUTest\TestResult.h \epoc32\include\CppUTest\TestResult.h -..\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\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 -..\include\CppUTest\TestPlugin.h \epoc32\include\CppUTest\TestPlugin.h -..\include\CppUTest\PlatformSpecificFunctions.h \epoc32\include\CppUTest\PlatformSpecificFunctions.h - -PRJ_MMPFILES -cpputest.mmp - -PRJ_TESTMMPFILES -alltests.mmp +/* + * Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde and Timo Puronen + * 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. + */ + +PRJ_PLATFORMS +DEFAULT + +PRJ_EXPORTS +..\include\CppUTest\TestHarness.h \epoc32\include\CppUTest\TestHarness.h +..\include\CppUTest\Utest.h \epoc32\include\CppUTest\Utest.h +..\include\CppUTest\UtestMacros.h \epoc32\include\CppUTest\UtestMacros.h +..\include\CppUTest\TestResult.h \epoc32\include\CppUTest\TestResult.h +..\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\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 +..\include\CppUTest\TestPlugin.h \epoc32\include\CppUTest\TestPlugin.h +..\include\CppUTest\PlatformSpecificFunctions.h \epoc32\include\CppUTest\PlatformSpecificFunctions.h + +PRJ_MMPFILES +cpputest.mmp + +PRJ_TESTMMPFILES +alltests.mmp diff --git a/examples/AllTests/AllTests.cpp b/examples/AllTests/AllTests.cpp index 88516e816..ca57e8567 100644 --- a/examples/AllTests/AllTests.cpp +++ b/examples/AllTests/AllTests.cpp @@ -1,57 +1,57 @@ -/* - * 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/TestPlugin.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTestExt/MockSupportPlugin.h" - -class MyDummyComparator : public MockNamedValueComparator -{ -public: - virtual bool isEqual(const void* object1, const void* object2) - { - return object1 == object2; - } - - virtual SimpleString valueToString(const void* object) - { - return StringFrom(object); - } -}; - -int main(int ac, char** av) -{ - MyDummyComparator dummyComparator; - MockSupportPlugin mockPlugin; - - mockPlugin.installComparator("MyDummyType", dummyComparator); - TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin); - return CommandLineTestRunner::RunAllTests(ac, av); -} - -#include "AllTests.h" +/* + * 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/TestPlugin.h" +#include "CppUTest/TestRegistry.h" +#include "CppUTestExt/MockSupportPlugin.h" + +class MyDummyComparator : public MockNamedValueComparator +{ +public: + virtual bool isEqual(const void* object1, const void* object2) + { + return object1 == object2; + } + + virtual SimpleString valueToString(const void* object) + { + return StringFrom(object); + } +}; + +int main(int ac, char** av) +{ + MyDummyComparator dummyComparator; + MockSupportPlugin mockPlugin; + + mockPlugin.installComparator("MyDummyType", dummyComparator); + TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin); + return CommandLineTestRunner::RunAllTests(ac, av); +} + +#include "AllTests.h" diff --git a/examples/AllTests/CircularBufferTest.cpp b/examples/AllTests/CircularBufferTest.cpp index 3d880b60f..ac9a55248 100644 --- a/examples/AllTests/CircularBufferTest.cpp +++ b/examples/AllTests/CircularBufferTest.cpp @@ -1,260 +1,260 @@ -/* - * 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 "MockPrinter.h" -#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(); -} -}; - -TEST(CircularBuffer, EmptyAfterCreation) -{ - CHECK(buffer->IsEmpty()); -} - -TEST(CircularBuffer, NotEmpty) -{ - buffer->Put(10046); - CHECK(!buffer->IsEmpty()); -} - -TEST(CircularBuffer, NotEmptyThenEmpty) -{ - buffer->Put(4567); - CHECK(!buffer->IsEmpty()); - buffer->Get(); - CHECK(buffer->IsEmpty()); -} - -TEST(CircularBuffer, GetPutOneValue) -{ - buffer->Put(4567); - LONGS_EQUAL(4567, buffer->Get()); -} - -TEST(CircularBuffer, GetPutAFew) -{ - buffer->Put(1); - buffer->Put(2); - buffer->Put(3); - LONGS_EQUAL(1, buffer->Get()); - LONGS_EQUAL(2, buffer->Get()); - LONGS_EQUAL(3, buffer->Get()); -} - -TEST(CircularBuffer, Capacity) -{ - CircularBuffer b(2); - LONGS_EQUAL(2, b.Capacity()); -} - -TEST(CircularBuffer, IsFull) -{ - fillTheQueue(0, buffer->Capacity()); - CHECK(buffer->IsFull()); -} - -TEST(CircularBuffer, EmptyToFullToEmpty) -{ - fillTheQueue(100, buffer->Capacity()); - - CHECK(buffer->IsFull()); - - removeFromQueue(buffer->Capacity()); - - CHECK(buffer->IsEmpty()); -} - -TEST(CircularBuffer, WrapAround) -{ - fillTheQueue(100, buffer->Capacity()); - - CHECK(buffer->IsFull()); - LONGS_EQUAL(100, buffer->Get()); - CHECK(!buffer->IsFull()); - buffer->Put(1000); - CHECK(buffer->IsFull()); - - removeFromQueue(buffer->Capacity() - 1); - - LONGS_EQUAL(1000, buffer->Get()); - CHECK(buffer->IsEmpty()); -} - -TEST(CircularBuffer, PutToFull) -{ - int capacity = buffer->Capacity(); - fillTheQueue(900, capacity); - buffer->Put(9999); - - for (int i = 0; i < buffer->Capacity() - 1; i++) - 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 - - -TEST(CircularBuffer, GetFromEmpty) -{ - LONGS_EQUAL(-1, buffer->Get()); - CHECK(buffer->IsEmpty()); -} - -/* - * the next tests demonstrate using a mock object for - * capturing output - * - */ - -TEST(CircularBuffer, PrintEmpty) -{ - MockPrinter mock; - Printer* p = &mock; - - buffer->Print(p); - STRCMP_EQUAL("Circular buffer content:\n<>\n", - mock.getOutput().c_str()); -} - -TEST(CircularBuffer, PrintAfterOnePut) -{ - MockPrinter mock; - - buffer->Put(1); - buffer->Print(&mock); - STRCMP_EQUAL("Circular buffer content:\n<1>\n", - mock.getOutput().c_str()); -} - -TEST(CircularBuffer, PrintNotYetWrappedOrFull) -{ - MockPrinter mock; - - buffer->Put(1); - buffer->Put(2); - buffer->Put(3); - buffer->Print(&mock); - STRCMP_EQUAL("Circular buffer content:\n<1, 2, 3>\n", - mock.getOutput().c_str()); -} - -TEST(CircularBuffer, PrintNotYetWrappedAndIsFull) -{ - MockPrinter mock; - - fillTheQueue(200, buffer->Capacity()); - - buffer->Print(&mock); - const char* expected = "Circular buffer content:\n" - "<200, 201, 202, 203, 204>\n"; - - STRCMP_EQUAL(expected, mock.getOutput().c_str()); -} - -TEST(CircularBuffer, PrintWrappedAndIsFullOldestToNewest) -{ - MockPrinter mock; - - fillTheQueue(200, buffer->Capacity()); - buffer->Get(); - buffer->Put(999); - - buffer->Print(&mock); - const char* expected = "Circular buffer content:\n" - "<201, 202, 203, 204, 999>\n"; - - STRCMP_EQUAL(expected, mock.getOutput().c_str()); -} - -TEST(CircularBuffer, PrintWrappedAndFullOverwriteOldest) -{ - MockPrinter mock; - - fillTheQueue(200, buffer->Capacity()); - buffer->Put(9999); - - buffer->Print(&mock); - const char* expected = "Circular buffer content:\n" - "<201, 202, 203, 204, 9999>\n"; - - STRCMP_EQUAL(expected, mock.getOutput().c_str()); -} - -TEST(CircularBuffer, PrintBoundary) -{ - MockPrinter mock; - - fillTheQueue(200, buffer->Capacity()); - removeFromQueue(buffer->Capacity() - 2); - buffer->Put(888); - fillTheQueue(300, buffer->Capacity() - 1); - - buffer->Print(&mock); - const char* expected = "Circular buffer content:\n" - "<888, 300, 301, 302, 303>\n"; - - STRCMP_EQUAL(expected, mock.getOutput().c_str()); -} - -TEST(CircularBuffer, FillEmptyThenPrint) -{ - MockPrinter mock; - - fillTheQueue(200, buffer->Capacity()); - removeFromQueue(buffer->Capacity()); - buffer->Print(&mock); - const char* expected = "Circular buffer content:\n" - "<>\n"; - - STRCMP_EQUAL(expected, mock.getOutput().c_str()); -} +/* + * 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 "MockPrinter.h" +#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(); +} +}; + +TEST(CircularBuffer, EmptyAfterCreation) +{ + CHECK(buffer->IsEmpty()); +} + +TEST(CircularBuffer, NotEmpty) +{ + buffer->Put(10046); + CHECK(!buffer->IsEmpty()); +} + +TEST(CircularBuffer, NotEmptyThenEmpty) +{ + buffer->Put(4567); + CHECK(!buffer->IsEmpty()); + buffer->Get(); + CHECK(buffer->IsEmpty()); +} + +TEST(CircularBuffer, GetPutOneValue) +{ + buffer->Put(4567); + LONGS_EQUAL(4567, buffer->Get()); +} + +TEST(CircularBuffer, GetPutAFew) +{ + buffer->Put(1); + buffer->Put(2); + buffer->Put(3); + LONGS_EQUAL(1, buffer->Get()); + LONGS_EQUAL(2, buffer->Get()); + LONGS_EQUAL(3, buffer->Get()); +} + +TEST(CircularBuffer, Capacity) +{ + CircularBuffer b(2); + LONGS_EQUAL(2, b.Capacity()); +} + +TEST(CircularBuffer, IsFull) +{ + fillTheQueue(0, buffer->Capacity()); + CHECK(buffer->IsFull()); +} + +TEST(CircularBuffer, EmptyToFullToEmpty) +{ + fillTheQueue(100, buffer->Capacity()); + + CHECK(buffer->IsFull()); + + removeFromQueue(buffer->Capacity()); + + CHECK(buffer->IsEmpty()); +} + +TEST(CircularBuffer, WrapAround) +{ + fillTheQueue(100, buffer->Capacity()); + + CHECK(buffer->IsFull()); + LONGS_EQUAL(100, buffer->Get()); + CHECK(!buffer->IsFull()); + buffer->Put(1000); + CHECK(buffer->IsFull()); + + removeFromQueue(buffer->Capacity() - 1); + + LONGS_EQUAL(1000, buffer->Get()); + CHECK(buffer->IsEmpty()); +} + +TEST(CircularBuffer, PutToFull) +{ + int capacity = buffer->Capacity(); + fillTheQueue(900, capacity); + buffer->Put(9999); + + for (int i = 0; i < buffer->Capacity() - 1; i++) + 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 + + +TEST(CircularBuffer, GetFromEmpty) +{ + LONGS_EQUAL(-1, buffer->Get()); + CHECK(buffer->IsEmpty()); +} + +/* + * the next tests demonstrate using a mock object for + * capturing output + * + */ + +TEST(CircularBuffer, PrintEmpty) +{ + MockPrinter mock; + Printer* p = &mock; + + buffer->Print(p); + STRCMP_EQUAL("Circular buffer content:\n<>\n", + mock.getOutput().c_str()); +} + +TEST(CircularBuffer, PrintAfterOnePut) +{ + MockPrinter mock; + + buffer->Put(1); + buffer->Print(&mock); + STRCMP_EQUAL("Circular buffer content:\n<1>\n", + mock.getOutput().c_str()); +} + +TEST(CircularBuffer, PrintNotYetWrappedOrFull) +{ + MockPrinter mock; + + buffer->Put(1); + buffer->Put(2); + buffer->Put(3); + buffer->Print(&mock); + STRCMP_EQUAL("Circular buffer content:\n<1, 2, 3>\n", + mock.getOutput().c_str()); +} + +TEST(CircularBuffer, PrintNotYetWrappedAndIsFull) +{ + MockPrinter mock; + + fillTheQueue(200, buffer->Capacity()); + + buffer->Print(&mock); + const char* expected = "Circular buffer content:\n" + "<200, 201, 202, 203, 204>\n"; + + STRCMP_EQUAL(expected, mock.getOutput().c_str()); +} + +TEST(CircularBuffer, PrintWrappedAndIsFullOldestToNewest) +{ + MockPrinter mock; + + fillTheQueue(200, buffer->Capacity()); + buffer->Get(); + buffer->Put(999); + + buffer->Print(&mock); + const char* expected = "Circular buffer content:\n" + "<201, 202, 203, 204, 999>\n"; + + STRCMP_EQUAL(expected, mock.getOutput().c_str()); +} + +TEST(CircularBuffer, PrintWrappedAndFullOverwriteOldest) +{ + MockPrinter mock; + + fillTheQueue(200, buffer->Capacity()); + buffer->Put(9999); + + buffer->Print(&mock); + const char* expected = "Circular buffer content:\n" + "<201, 202, 203, 204, 9999>\n"; + + STRCMP_EQUAL(expected, mock.getOutput().c_str()); +} + +TEST(CircularBuffer, PrintBoundary) +{ + MockPrinter mock; + + fillTheQueue(200, buffer->Capacity()); + removeFromQueue(buffer->Capacity() - 2); + buffer->Put(888); + fillTheQueue(300, buffer->Capacity() - 1); + + buffer->Print(&mock); + const char* expected = "Circular buffer content:\n" + "<888, 300, 301, 302, 303>\n"; + + STRCMP_EQUAL(expected, mock.getOutput().c_str()); +} + +TEST(CircularBuffer, FillEmptyThenPrint) +{ + MockPrinter mock; + + fillTheQueue(200, buffer->Capacity()); + removeFromQueue(buffer->Capacity()); + buffer->Print(&mock); + const char* expected = "Circular buffer content:\n" + "<>\n"; + + STRCMP_EQUAL(expected, mock.getOutput().c_str()); +} diff --git a/examples/AllTests/HelloTest.cpp b/examples/AllTests/HelloTest.cpp index 6b9baceb2..dcc996071 100644 --- a/examples/AllTests/HelloTest.cpp +++ b/examples/AllTests/HelloTest.cpp @@ -1,60 +1,60 @@ -/* - * 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 "hello.h" - -#include -#include -#include "CppUTest/TestHarness.h" - -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; -} -}; - -TEST(HelloWorld, PrintOk) -{ - printHelloWorld(); - STRCMP_EQUAL("Hello World!\n", buffer->asCharString()); -} +/* + * 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 "hello.h" + +#include +#include +#include "CppUTest/TestHarness.h" + +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; +} +}; + +TEST(HelloWorld, PrintOk) +{ + printHelloWorld(); + STRCMP_EQUAL("Hello World!\n", buffer->asCharString()); +} diff --git a/examples/ApplicationLib/CircularBuffer.cpp b/examples/ApplicationLib/CircularBuffer.cpp index 6d72b8b57..9aefcb4e1 100644 --- a/examples/ApplicationLib/CircularBuffer.cpp +++ b/examples/ApplicationLib/CircularBuffer.cpp @@ -1,100 +1,100 @@ -/* - * 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 "CircularBuffer.h" -#include "Printer.h" - -CircularBuffer::CircularBuffer(int _capacity) : - index(0), outdex(0), capacity(_capacity), empty(true), full(false) -{ - buffer = new int[this->capacity]; -} - -CircularBuffer::~CircularBuffer() -{ - delete[] buffer; -} - -bool CircularBuffer::IsEmpty() -{ - return empty; -} - -bool CircularBuffer::IsFull() -{ - return full; -} - -void CircularBuffer::Put(int i) -{ - empty = false; - buffer[index] = i; - index = Next(index); - if (full) outdex = Next(outdex); - else if (index == outdex) full = true; -} - -int CircularBuffer::Get() -{ - int result = -1; - full = false; - - if (!empty) { - result = buffer[outdex]; - outdex = Next(outdex); - if (outdex == index) empty = true; - } - return result; -} - -int CircularBuffer::Capacity() -{ - return capacity; -} - -int CircularBuffer::Next(int i) -{ - if (++i >= capacity) i = 0; - return i; -} - -void CircularBuffer::Print(Printer* p) -{ - p->Print("Circular buffer content:\n<"); - - int printIndex = outdex; - int count = index - outdex; - - 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(", "); - } - p->Print(">\n"); -} +/* + * 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 "CircularBuffer.h" +#include "Printer.h" + +CircularBuffer::CircularBuffer(int _capacity) : + index(0), outdex(0), capacity(_capacity), empty(true), full(false) +{ + buffer = new int[this->capacity]; +} + +CircularBuffer::~CircularBuffer() +{ + delete[] buffer; +} + +bool CircularBuffer::IsEmpty() +{ + return empty; +} + +bool CircularBuffer::IsFull() +{ + return full; +} + +void CircularBuffer::Put(int i) +{ + empty = false; + buffer[index] = i; + index = Next(index); + if (full) outdex = Next(outdex); + else if (index == outdex) full = true; +} + +int CircularBuffer::Get() +{ + int result = -1; + full = false; + + if (!empty) { + result = buffer[outdex]; + outdex = Next(outdex); + if (outdex == index) empty = true; + } + return result; +} + +int CircularBuffer::Capacity() +{ + return capacity; +} + +int CircularBuffer::Next(int i) +{ + if (++i >= capacity) i = 0; + return i; +} + +void CircularBuffer::Print(Printer* p) +{ + p->Print("Circular buffer content:\n<"); + + int printIndex = outdex; + int count = index - outdex; + + 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(", "); + } + p->Print(">\n"); +} diff --git a/examples/ApplicationLib/CircularBuffer.h b/examples/ApplicationLib/CircularBuffer.h index 7139f2593..0ed8a2a05 100644 --- a/examples/ApplicationLib/CircularBuffer.h +++ b/examples/ApplicationLib/CircularBuffer.h @@ -1,72 +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. - */ - -#ifndef D_CircularBuffer_H -#define D_CircularBuffer_H - -/////////////////////////////////////////////////////////////////////////////// -// -// CircularBuffer.h -// -// CircularBuffer is responsible for ... -// -/////////////////////////////////////////////////////////////////////////////// -class Printer; - -class CircularBuffer -{ -public: - explicit CircularBuffer(int capacity = CAPACITY); - virtual ~CircularBuffer(); - - void Put(int); - int Get(); - bool IsEmpty(); - bool IsFull(); - int Capacity(); - int Next(int i); - void Print(Printer*); - -private: - - int index; - int outdex; - int* buffer; - int capacity; - enum - { - CAPACITY = 5 - }; - bool empty; - bool full; - - CircularBuffer(const CircularBuffer&); - CircularBuffer& operator=(const CircularBuffer&); - -}; - -#endif // D_CircularBuffer_H +/* + * 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_CircularBuffer_H +#define D_CircularBuffer_H + +/////////////////////////////////////////////////////////////////////////////// +// +// CircularBuffer.h +// +// CircularBuffer is responsible for ... +// +/////////////////////////////////////////////////////////////////////////////// +class Printer; + +class CircularBuffer +{ +public: + explicit CircularBuffer(int capacity = CAPACITY); + virtual ~CircularBuffer(); + + void Put(int); + int Get(); + bool IsEmpty(); + bool IsFull(); + int Capacity(); + int Next(int i); + void Print(Printer*); + +private: + + int index; + int outdex; + int* buffer; + int capacity; + enum + { + CAPACITY = 5 + }; + bool empty; + bool full; + + CircularBuffer(const CircularBuffer&); + CircularBuffer& operator=(const CircularBuffer&); + +}; + +#endif // D_CircularBuffer_H diff --git a/examples/ApplicationLib/hello.c b/examples/ApplicationLib/hello.c index 822298519..4ca63c33b 100644 --- a/examples/ApplicationLib/hello.c +++ b/examples/ApplicationLib/hello.c @@ -1,36 +1,36 @@ -/* - * 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 "hello.h" - -void printHelloWorld() -{ - PrintFormated("Hello World!\n"); -} - -int (*PrintFormated)(const char*, ...) = printf; +/* + * 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 "hello.h" + +void printHelloWorld() +{ + PrintFormated("Hello World!\n"); +} + +int (*PrintFormated)(const char*, ...) = printf; diff --git a/examples/ApplicationLib/hello.h b/examples/ApplicationLib/hello.h index 0745ca04e..5154b3cf1 100644 --- a/examples/ApplicationLib/hello.h +++ b/examples/ApplicationLib/hello.h @@ -1,43 +1,43 @@ -/* - * 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 HELLO_H_ -#define HELLO_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -extern void printHelloWorld(void); - -extern int (*PrintFormated)(const char*, ...); - -#ifdef __cplusplus -} -#endif - -#endif /*HELLO_H_*/ +/* + * 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 HELLO_H_ +#define HELLO_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +extern void printHelloWorld(void); + +extern int (*PrintFormated)(const char*, ...); + +#ifdef __cplusplus +} +#endif + +#endif /*HELLO_H_*/ diff --git a/examples/CppUTestExample.dsw b/examples/CppUTestExample.dsw index ce851bf09..98f732660 100644 --- a/examples/CppUTestExample.dsw +++ b/examples/CppUTestExample.dsw @@ -1,44 +1,44 @@ -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> -{{{ -}}} - -############################################################################### - +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/include/CppUTestExt/OrderedTest.h b/include/CppUTestExt/OrderedTest.h index 8114a9d9d..a8779c712 100644 --- a/include/CppUTestExt/OrderedTest.h +++ b/include/CppUTestExt/OrderedTest.h @@ -1,82 +1,82 @@ -/* - * 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_OrderedTest_h -#define D_OrderedTest_h - -class OrderedTestShell : public UtestShell -{ -public: - OrderedTestShell(); - virtual ~OrderedTestShell(); - - virtual OrderedTestShell* addOrderedTest(OrderedTestShell* test); - virtual OrderedTestShell* getNextOrderedTest(); - - int getLevel(); - void setLevel(int level); - - static void addOrderedTestToHead(OrderedTestShell* test); - static OrderedTestShell* getOrderedTestHead(); - static bool firstOrderedTest(); - - static void setOrderedTestHead(OrderedTestShell* test); -private: - static OrderedTestShell* _orderedTestsHead; - OrderedTestShell* _nextOrderedTest; - - int _level; - -}; - -class OrderedTestInstaller -{ - public: - explicit OrderedTestInstaller(OrderedTestShell& test, const char* groupName, const char* testName, const char* fileName, int lineNumber, int level); - virtual ~OrderedTestInstaller(); - - private: - void addOrderedTestInOrder(OrderedTestShell* test); - void addOrderedTestInOrderNotAtHeadPosition(OrderedTestShell* test); - -}; - -#define TEST_ORDERED(testGroup, testName, testLevel) \ - /* declarations for compilers */ \ - class TEST_##testGroup##_##testName##_TestShell; \ - 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(); }; \ - class TEST_##testGroup##_##testName##_TestShell : public OrderedTestShell { \ - virtual Utest* createTest() _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 - +/* + * 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_OrderedTest_h +#define D_OrderedTest_h + +class OrderedTestShell : public UtestShell +{ +public: + OrderedTestShell(); + virtual ~OrderedTestShell(); + + virtual OrderedTestShell* addOrderedTest(OrderedTestShell* test); + virtual OrderedTestShell* getNextOrderedTest(); + + int getLevel(); + void setLevel(int level); + + static void addOrderedTestToHead(OrderedTestShell* test); + static OrderedTestShell* getOrderedTestHead(); + static bool firstOrderedTest(); + + static void setOrderedTestHead(OrderedTestShell* test); +private: + static OrderedTestShell* _orderedTestsHead; + OrderedTestShell* _nextOrderedTest; + + int _level; + +}; + +class OrderedTestInstaller +{ + public: + explicit OrderedTestInstaller(OrderedTestShell& test, const char* groupName, const char* testName, const char* fileName, int lineNumber, int level); + virtual ~OrderedTestInstaller(); + + private: + void addOrderedTestInOrder(OrderedTestShell* test); + void addOrderedTestInOrderNotAtHeadPosition(OrderedTestShell* test); + +}; + +#define TEST_ORDERED(testGroup, testName, testLevel) \ + /* declarations for compilers */ \ + class TEST_##testGroup##_##testName##_TestShell; \ + 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(); }; \ + class TEST_##testGroup##_##testName##_TestShell : public OrderedTestShell { \ + virtual Utest* createTest() _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 + diff --git a/include/Platforms/Gcc/Platform.h b/include/Platforms/Gcc/Platform.h index 8e2eb0c9b..6dc0dc285 100644 --- a/include/Platforms/Gcc/Platform.h +++ b/include/Platforms/Gcc/Platform.h @@ -1,31 +1,31 @@ -/* - * 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_Gcc_Platform_H -#define D_Gcc_Platform_H - -#endif +/* + * 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_Gcc_Platform_H +#define D_Gcc_Platform_H + +#endif diff --git a/include/Platforms/StarterKit/Platform.h b/include/Platforms/StarterKit/Platform.h index 8e2eb0c9b..6dc0dc285 100644 --- a/include/Platforms/StarterKit/Platform.h +++ b/include/Platforms/StarterKit/Platform.h @@ -1,31 +1,31 @@ -/* - * 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_Gcc_Platform_H -#define D_Gcc_Platform_H - -#endif +/* + * 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_Gcc_Platform_H +#define D_Gcc_Platform_H + +#endif diff --git a/lib/NoteOnVisualStudio.txt b/lib/NoteOnVisualStudio.txt index 1b9e6f1e6..70026cc05 100644 --- a/lib/NoteOnVisualStudio.txt +++ b/lib/NoteOnVisualStudio.txt @@ -1,4 +1,4 @@ -This directory will contain the last lib created by any of the visual studion builds. - -In case you simultaneously use more than one VS version, there are subdirectories -for each supported VS version where CppUTest.lib and the associated pdb file are copied. +This directory will contain the last lib created by any of the visual studion builds. + +In case you simultaneously use more than one VS version, there are subdirectories +for each supported VS version where CppUTest.lib and the associated pdb file are copied. diff --git a/makeVS2008.bat b/makeVS2008.bat index b5f0838fe..29f742735 100644 --- a/makeVS2008.bat +++ b/makeVS2008.bat @@ -1,9 +1,9 @@ -rem **** -rem * Command line build - For CppUTest - Run from CppUTest directory -rem * -rem * this path works on my machine -rem ****PATH=C:\Windows\Microsoft.NET\Framework\v3.5;c:\windows;c:\windows\system32 - -msbuild /t:rebuild /verbosity:quiet CppUTest_VS2008.sln -set test_exe=tests\Debug\AllTests.exe -if exist %test_exe% %test_exe% -v +rem **** +rem * Command line build - For CppUTest - Run from CppUTest directory +rem * +rem * this path works on my machine +rem ****PATH=C:\Windows\Microsoft.NET\Framework\v3.5;c:\windows;c:\windows\system32 + +msbuild /t:rebuild /verbosity:quiet CppUTest_VS2008.sln +set test_exe=tests\Debug\AllTests.exe +if exist %test_exe% %test_exe% -v diff --git a/makeVS2010.bat b/makeVS2010.bat index a3d14c4d3..2bbb4fba5 100644 --- a/makeVS2010.bat +++ b/makeVS2010.bat @@ -1,8 +1,8 @@ -rem **** -rem * Command line build - For CppUTest - Run from CppUTest directory -rem * -rem * this path works on my machine -rem ****PATH=C:\Windows\Microsoft.NET\Framework\v4.0.30319;c:\windows\system32;c:\windows -msbuild /t:rebuild /verbosity:quiet CppUTest_VS2010.sln -set test_exe=tests\Debug\AllTests.exe -if exist %test_exe% %test_exe% -v +rem **** +rem * Command line build - For CppUTest - Run from CppUTest directory +rem * +rem * this path works on my machine +rem ****PATH=C:\Windows\Microsoft.NET\Framework\v4.0.30319;c:\windows\system32;c:\windows +msbuild /t:rebuild /verbosity:quiet CppUTest_VS2010.sln +set test_exe=tests\Debug\AllTests.exe +if exist %test_exe% %test_exe% -v diff --git a/makeVc6.bat b/makeVc6.bat index 7aa11e3b9..d60d91830 100644 --- a/makeVc6.bat +++ b/makeVc6.bat @@ -1,16 +1,16 @@ -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 +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/scripts/CppUnitTemplates/ClassName.cpp b/scripts/CppUnitTemplates/ClassName.cpp index f8a84ff2a..c80207946 100644 --- a/scripts/CppUnitTemplates/ClassName.cpp +++ b/scripts/CppUnitTemplates/ClassName.cpp @@ -1,10 +1,10 @@ -#include "ClassName.h" - -ClassName::ClassName() -{ -} - -ClassName::~ClassName() -{ -} - +#include "ClassName.h" + +ClassName::ClassName() +{ +} + +ClassName::~ClassName() +{ +} + diff --git a/scripts/CppUnitTemplates/ClassName.h b/scripts/CppUnitTemplates/ClassName.h index 5c62217c2..88803e2ec 100644 --- a/scripts/CppUnitTemplates/ClassName.h +++ b/scripts/CppUnitTemplates/ClassName.h @@ -1,23 +1,23 @@ -#ifndef D_ClassName_H -#define D_ClassName_H - -/////////////////////////////////////////////////////////////////////////////// -// -// ClassName is responsible for ... -// -/////////////////////////////////////////////////////////////////////////////// - -class ClassName - { - public: - explicit ClassName(); - virtual ~ClassName(); - - private: - - ClassName(const ClassName&); - ClassName& operator=(const ClassName&); - - }; - -#endif // D_ClassName_H +#ifndef D_ClassName_H +#define D_ClassName_H + +/////////////////////////////////////////////////////////////////////////////// +// +// ClassName is responsible for ... +// +/////////////////////////////////////////////////////////////////////////////// + +class ClassName + { + public: + explicit ClassName(); + virtual ~ClassName(); + + private: + + ClassName(const ClassName&); + ClassName& operator=(const ClassName&); + + }; + +#endif // D_ClassName_H diff --git a/scripts/CppUnitTemplates/ClassNameC.c b/scripts/CppUnitTemplates/ClassNameC.c index 5f9f03d7b..eb0cae7cf 100644 --- a/scripts/CppUnitTemplates/ClassNameC.c +++ b/scripts/CppUnitTemplates/ClassNameC.c @@ -1,16 +1,16 @@ -#include "ClassName.h" -#include -#include - -//static local variables - - -void ClassName_Create(void) -{ -} - -void ClassName_Destroy(void) -{ -} - - +#include "ClassName.h" +#include +#include + +//static local variables + + +void ClassName_Create(void) +{ +} + +void ClassName_Destroy(void) +{ +} + + diff --git a/scripts/CppUnitTemplates/ClassNameC.h b/scripts/CppUnitTemplates/ClassNameC.h index fef763663..475355cb7 100644 --- a/scripts/CppUnitTemplates/ClassNameC.h +++ b/scripts/CppUnitTemplates/ClassNameC.h @@ -1,12 +1,12 @@ -#ifndef D_ClassName_H -#define D_ClassName_H - -/////////////////////////////////////////////////////////////////////////////// -// -// ClassName is responsible for ... -// -/////////////////////////////////////////////////////////////////////////////// -void ClassName_Create(void); -void ClassName_Destroy(void); - -#endif // D_ClassName_H +#ifndef D_ClassName_H +#define D_ClassName_H + +/////////////////////////////////////////////////////////////////////////////// +// +// ClassName is responsible for ... +// +/////////////////////////////////////////////////////////////////////////////// +void ClassName_Create(void); +void ClassName_Destroy(void); + +#endif // D_ClassName_H diff --git a/scripts/CppUnitTemplates/ClassNameCMultipleInstance.c b/scripts/CppUnitTemplates/ClassNameCMultipleInstance.c index bf0eca8e5..13d6941d3 100644 --- a/scripts/CppUnitTemplates/ClassNameCMultipleInstance.c +++ b/scripts/CppUnitTemplates/ClassNameCMultipleInstance.c @@ -1,23 +1,23 @@ -#include "ClassName.h" -#include -#include - -//static local variables -typedef struct _ClassName -{ - int placeHolderForHiddenStructElements; -}; - -ClassName* ClassName_Create(void) -{ - ClassName* self = malloc(sizeof(ClassName)); - memset(self, 0, sizeof(ClassName)); - return self; -} - -void ClassName_Destroy(ClassName* self) -{ - free(self); -} - - +#include "ClassName.h" +#include +#include + +//static local variables +typedef struct _ClassName +{ + int placeHolderForHiddenStructElements; +}; + +ClassName* ClassName_Create(void) +{ + ClassName* self = malloc(sizeof(ClassName)); + memset(self, 0, sizeof(ClassName)); + return self; +} + +void ClassName_Destroy(ClassName* self) +{ + free(self); +} + + diff --git a/scripts/CppUnitTemplates/ClassNameCMultipleInstance.h b/scripts/CppUnitTemplates/ClassNameCMultipleInstance.h index 2de5d9c14..01f27edaa 100644 --- a/scripts/CppUnitTemplates/ClassNameCMultipleInstance.h +++ b/scripts/CppUnitTemplates/ClassNameCMultipleInstance.h @@ -1,16 +1,16 @@ -#ifndef D_ClassName_H -#define D_ClassName_H - -/////////////////////////////////////////////////////////////////////////////// -// -// ClassName is responsible for ... -// -/////////////////////////////////////////////////////////////////////////////// - -typedef struct _ClassName Classname; - -ClassName* ClassName_Create(void); -void ClassName_Destroy(ClassName*); -void ClassName_VirtualFunction_impl(ClassName*); - -#endif // D_ClassName_H +#ifndef D_ClassName_H +#define D_ClassName_H + +/////////////////////////////////////////////////////////////////////////////// +// +// ClassName is responsible for ... +// +/////////////////////////////////////////////////////////////////////////////// + +typedef struct _ClassName Classname; + +ClassName* ClassName_Create(void); +void ClassName_Destroy(ClassName*); +void ClassName_VirtualFunction_impl(ClassName*); + +#endif // D_ClassName_H diff --git a/scripts/CppUnitTemplates/ClassNameCMultipleInstanceTest.cpp b/scripts/CppUnitTemplates/ClassNameCMultipleInstanceTest.cpp index 0ad16f71b..bbde2c413 100644 --- a/scripts/CppUnitTemplates/ClassNameCMultipleInstanceTest.cpp +++ b/scripts/CppUnitTemplates/ClassNameCMultipleInstanceTest.cpp @@ -1,41 +1,41 @@ -#include "CppUTest/TestHarness.h" - -static int fakeRan = 0; - -extern "C" -{ -#include "ClassName.h" - void virtualFunction_renameThis_fake(ClassName*) - { - fakeRan = 1; - } -} - -TEST_GROUP(ClassName) -{ - ClassName* aClassName; - - void setup() - { - aClassName = ClassName_Create(); - fakeRan = 0; - aClassName->virtualFunction_renameThis = virtualFunction_renameThis_fake; - } - - void teardown() - { - ClassName_Destroy(aClassName); - } -}; - -TEST(ClassName, Fake) -{ - aClassName->virtualFunction_renameThis(aClassName); - LONGS_EQUAL(1, fakeRan); -} - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} - +#include "CppUTest/TestHarness.h" + +static int fakeRan = 0; + +extern "C" +{ +#include "ClassName.h" + void virtualFunction_renameThis_fake(ClassName*) + { + fakeRan = 1; + } +} + +TEST_GROUP(ClassName) +{ + ClassName* aClassName; + + void setup() + { + aClassName = ClassName_Create(); + fakeRan = 0; + aClassName->virtualFunction_renameThis = virtualFunction_renameThis_fake; + } + + void teardown() + { + ClassName_Destroy(aClassName); + } +}; + +TEST(ClassName, Fake) +{ + aClassName->virtualFunction_renameThis(aClassName); + LONGS_EQUAL(1, fakeRan); +} + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} + diff --git a/scripts/CppUnitTemplates/ClassNameCPolymorphic.c b/scripts/CppUnitTemplates/ClassNameCPolymorphic.c index bf0eca8e5..13d6941d3 100644 --- a/scripts/CppUnitTemplates/ClassNameCPolymorphic.c +++ b/scripts/CppUnitTemplates/ClassNameCPolymorphic.c @@ -1,23 +1,23 @@ -#include "ClassName.h" -#include -#include - -//static local variables -typedef struct _ClassName -{ - int placeHolderForHiddenStructElements; -}; - -ClassName* ClassName_Create(void) -{ - ClassName* self = malloc(sizeof(ClassName)); - memset(self, 0, sizeof(ClassName)); - return self; -} - -void ClassName_Destroy(ClassName* self) -{ - free(self); -} - - +#include "ClassName.h" +#include +#include + +//static local variables +typedef struct _ClassName +{ + int placeHolderForHiddenStructElements; +}; + +ClassName* ClassName_Create(void) +{ + ClassName* self = malloc(sizeof(ClassName)); + memset(self, 0, sizeof(ClassName)); + return self; +} + +void ClassName_Destroy(ClassName* self) +{ + free(self); +} + + diff --git a/scripts/CppUnitTemplates/ClassNameCPolymorphic.h b/scripts/CppUnitTemplates/ClassNameCPolymorphic.h index 788119e57..2eba3275b 100644 --- a/scripts/CppUnitTemplates/ClassNameCPolymorphic.h +++ b/scripts/CppUnitTemplates/ClassNameCPolymorphic.h @@ -1,18 +1,18 @@ -#ifndef D_ClassName_H -#define D_ClassName_H - -/////////////////////////////////////////////////////////////////////////////// -// -// ClassName is responsible for ... -// -/////////////////////////////////////////////////////////////////////////////// - -typedef struct _ClassName ClassnamePiml; - - - -ClassName* ClassName_Create(void); -void ClassName_Destroy(ClassName*); -void ClassName_VirtualFunction_impl(ClassName*); - -#endif // D_ClassName_H +#ifndef D_ClassName_H +#define D_ClassName_H + +/////////////////////////////////////////////////////////////////////////////// +// +// ClassName is responsible for ... +// +/////////////////////////////////////////////////////////////////////////////// + +typedef struct _ClassName ClassnamePiml; + + + +ClassName* ClassName_Create(void); +void ClassName_Destroy(ClassName*); +void ClassName_VirtualFunction_impl(ClassName*); + +#endif // D_ClassName_H diff --git a/scripts/CppUnitTemplates/ClassNameCTest.cpp b/scripts/CppUnitTemplates/ClassNameCTest.cpp index 32d9947ae..be4f1f935 100644 --- a/scripts/CppUnitTemplates/ClassNameCTest.cpp +++ b/scripts/CppUnitTemplates/ClassNameCTest.cpp @@ -1,25 +1,25 @@ -#include "CppUTest/TestHarness.h" - -extern "C" -{ -#include "ClassName.h" -} - -TEST_GROUP(ClassName) -{ - void setup() - { - ClassName_Create(); - } - - void teardown() - { - ClassName_Destroy(); - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} - +#include "CppUTest/TestHarness.h" + +extern "C" +{ +#include "ClassName.h" +} + +TEST_GROUP(ClassName) +{ + void setup() + { + ClassName_Create(); + } + + void teardown() + { + ClassName_Destroy(); + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} + diff --git a/scripts/CppUnitTemplates/ClassNameTest.cpp b/scripts/CppUnitTemplates/ClassNameTest.cpp index 0835c09d6..d27f86ddc 100644 --- a/scripts/CppUnitTemplates/ClassNameTest.cpp +++ b/scripts/CppUnitTemplates/ClassNameTest.cpp @@ -1,33 +1,33 @@ -#include -#include -#include "ClassName.h" - -class ClassNameTest: public CPPUNIT_NS::TestFixture -{ - CPPUNIT_TEST_SUITE(ClassNameTest); - CPPUNIT_TEST(testCreate); - CPPUNIT_TEST_SUITE_END(); - - ClassName* aClassName; - -public: - - void setUp() - { - aClassName = new ClassName(); - } - - void tearDown() - { - delete aClassName; - } - - void testCreate() - { - CPPUNIT_FAIL("Start here"); - } -}; - -CPPUNIT_TEST_SUITE_REGISTRATION(ClassNameTest); - - +#include +#include +#include "ClassName.h" + +class ClassNameTest: public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE(ClassNameTest); + CPPUNIT_TEST(testCreate); + CPPUNIT_TEST_SUITE_END(); + + ClassName* aClassName; + +public: + + void setUp() + { + aClassName = new ClassName(); + } + + void tearDown() + { + delete aClassName; + } + + void testCreate() + { + CPPUNIT_FAIL("Start here"); + } +}; + +CPPUNIT_TEST_SUITE_REGISTRATION(ClassNameTest); + + diff --git a/scripts/CppUnitTemplates/InterfaceCTest.cpp b/scripts/CppUnitTemplates/InterfaceCTest.cpp index 6c5c6a8f7..b0b9906b8 100644 --- a/scripts/CppUnitTemplates/InterfaceCTest.cpp +++ b/scripts/CppUnitTemplates/InterfaceCTest.cpp @@ -1,24 +1,24 @@ -#include "CppUTest/TestHarness.h" - -extern "C" -{ -#include "FakeClassName.h" -} - -TEST_GROUP(FakeClassName) -{ - void setup() - { - ClassName_Create(); - } - - void teardown() - { - ClassName_Destroy(); - } -}; - -TEST(FakeClassName, Create) -{ - FAIL("Start here"); -} +#include "CppUTest/TestHarness.h" + +extern "C" +{ +#include "FakeClassName.h" +} + +TEST_GROUP(FakeClassName) +{ + void setup() + { + ClassName_Create(); + } + + void teardown() + { + ClassName_Destroy(); + } +}; + +TEST(FakeClassName, Create) +{ + FAIL("Start here"); +} diff --git a/scripts/CppUnitTemplates/InterfaceTest.cpp b/scripts/CppUnitTemplates/InterfaceTest.cpp index 3c7559258..a2b9362cc 100644 --- a/scripts/CppUnitTemplates/InterfaceTest.cpp +++ b/scripts/CppUnitTemplates/InterfaceTest.cpp @@ -1,34 +1,34 @@ -#include -#include -#include "ClassName.h" -#include "MockClassName.h" - -class MockClassNameTest: public CPPUNIT_NS::TestFixture -{ - CPPUNIT_TEST_SUITE(MockClassNameTest); - CPPUNIT_TEST(testCreate); - CPPUNIT_TEST_SUITE_END(); - - ClassName* aClassName; - MockClassName* mockClassName; - -public: - - void setUp() - { - mockClassName = new MockClassName(); - aClassName = mockClassName; - } - - void tearDown() - { - delete aClassName; - } - - void testCreate() - { - CPPUNIT_FAIL("Start here"); - } -}; - -CPPUNIT_TEST_SUITE_REGISTRATION(MockClassNameTest); +#include +#include +#include "ClassName.h" +#include "MockClassName.h" + +class MockClassNameTest: public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE(MockClassNameTest); + CPPUNIT_TEST(testCreate); + CPPUNIT_TEST_SUITE_END(); + + ClassName* aClassName; + MockClassName* mockClassName; + +public: + + void setUp() + { + mockClassName = new MockClassName(); + aClassName = mockClassName; + } + + void tearDown() + { + delete aClassName; + } + + void testCreate() + { + CPPUNIT_FAIL("Start here"); + } +}; + +CPPUNIT_TEST_SUITE_REGISTRATION(MockClassNameTest); diff --git a/scripts/CppUnitTemplates/MockClassName.h b/scripts/CppUnitTemplates/MockClassName.h index 8588b72a4..0e6778928 100644 --- a/scripts/CppUnitTemplates/MockClassName.h +++ b/scripts/CppUnitTemplates/MockClassName.h @@ -1,29 +1,29 @@ -#ifndef D_MockClassName_H -#define D_MockClassName_H - -/////////////////////////////////////////////////////////////////////////////// -// -// MockClassName.h -// -// MockClassName is responsible for providing a test stub for ClassName -// -/////////////////////////////////////////////////////////////////////////////// -#include "ClassName.h" - - -class MockClassName : public ClassName - { - public: - explicit MockClassName() - {} - virtual ~MockClassName() - {} - - private: - - MockClassName(const MockClassName&); - MockClassName& operator=(const MockClassName&); - - }; - -#endif // D_MockClassName_H +#ifndef D_MockClassName_H +#define D_MockClassName_H + +/////////////////////////////////////////////////////////////////////////////// +// +// MockClassName.h +// +// MockClassName is responsible for providing a test stub for ClassName +// +/////////////////////////////////////////////////////////////////////////////// +#include "ClassName.h" + + +class MockClassName : public ClassName + { + public: + explicit MockClassName() + {} + virtual ~MockClassName() + {} + + private: + + MockClassName(const MockClassName&); + MockClassName& operator=(const MockClassName&); + + }; + +#endif // D_MockClassName_H diff --git a/scripts/CppUnitTemplates/MockClassNameC.c b/scripts/CppUnitTemplates/MockClassNameC.c index 5f9f03d7b..eb0cae7cf 100644 --- a/scripts/CppUnitTemplates/MockClassNameC.c +++ b/scripts/CppUnitTemplates/MockClassNameC.c @@ -1,16 +1,16 @@ -#include "ClassName.h" -#include -#include - -//static local variables - - -void ClassName_Create(void) -{ -} - -void ClassName_Destroy(void) -{ -} - - +#include "ClassName.h" +#include +#include + +//static local variables + + +void ClassName_Create(void) +{ +} + +void ClassName_Destroy(void) +{ +} + + diff --git a/scripts/CppUnitTemplates/MockClassNameC.h b/scripts/CppUnitTemplates/MockClassNameC.h index ac1db292f..85146b645 100644 --- a/scripts/CppUnitTemplates/MockClassNameC.h +++ b/scripts/CppUnitTemplates/MockClassNameC.h @@ -1,13 +1,13 @@ -#ifndef D_FakeClassName_H -#define D_FakeClassName_H - -/////////////////////////////////////////////////////////////////////////////// -// -// FakeClassName.h -// -// FakeClassName is responsible for providing a test stub for ClassName -// -/////////////////////////////////////////////////////////////////////////////// -#include "ClassName.h" - -#endif // D_FakeClassName_H +#ifndef D_FakeClassName_H +#define D_FakeClassName_H + +/////////////////////////////////////////////////////////////////////////////// +// +// FakeClassName.h +// +// FakeClassName is responsible for providing a test stub for ClassName +// +/////////////////////////////////////////////////////////////////////////////// +#include "ClassName.h" + +#endif // D_FakeClassName_H diff --git a/scripts/CppUnitTemplates/ProjectTemplate/tests/AllTests.cpp b/scripts/CppUnitTemplates/ProjectTemplate/tests/AllTests.cpp index 31a390715..3932fd103 100644 --- a/scripts/CppUnitTemplates/ProjectTemplate/tests/AllTests.cpp +++ b/scripts/CppUnitTemplates/ProjectTemplate/tests/AllTests.cpp @@ -1,8 +1,8 @@ - -#include "CppUTest/CommandLineTestRunner.h" - -int main(int ac, char** av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - + +#include "CppUTest/CommandLineTestRunner.h" + +int main(int ac, char** av) +{ + return CommandLineTestRunner::RunAllTests(ac, av); +} + diff --git a/scripts/UnityTemplates/ClassNameCIoDriverTest.cpp b/scripts/UnityTemplates/ClassNameCIoDriverTest.cpp index 78588a5fd..b22ee7b12 100644 --- a/scripts/UnityTemplates/ClassNameCIoDriverTest.cpp +++ b/scripts/UnityTemplates/ClassNameCIoDriverTest.cpp @@ -1,28 +1,28 @@ -extern "C" { -#include "ClassName.h" -#include "MockIO.h" -} - -//CppUTest includes should be after your and system includes -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - void setup() - { - Reset_Mock_IO(); - ClassName_Create(); - } - - void teardown() - { - ClassName_Destroy(); - Assert_No_Unused_Expectations(); - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} - +extern "C" { +#include "ClassName.h" +#include "MockIO.h" +} + +//CppUTest includes should be after your and system includes +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + void setup() + { + Reset_Mock_IO(); + ClassName_Create(); + } + + void teardown() + { + ClassName_Destroy(); + Assert_No_Unused_Expectations(); + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} + diff --git a/scripts/UnityTemplates/ClassNameCMultipleInstanceTest.cpp b/scripts/UnityTemplates/ClassNameCMultipleInstanceTest.cpp index afc2423b3..77af385ed 100644 --- a/scripts/UnityTemplates/ClassNameCMultipleInstanceTest.cpp +++ b/scripts/UnityTemplates/ClassNameCMultipleInstanceTest.cpp @@ -1,28 +1,28 @@ -extern "C" -{ -#include "ClassName.h" -} - -//CppUTest includes should be after your and system includes -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - ClassName aClassName; - - void setup() - { - aClassName = ClassName_Create(); - } - - void teardown() - { - ClassName_Destroy(aClassName); - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} - +extern "C" +{ +#include "ClassName.h" +} + +//CppUTest includes should be after your and system includes +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + ClassName aClassName; + + void setup() + { + aClassName = ClassName_Create(); + } + + void teardown() + { + ClassName_Destroy(aClassName); + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} + diff --git a/scripts/UnityTemplates/ClassNameCTest.cpp b/scripts/UnityTemplates/ClassNameCTest.cpp index 745f99d78..9a64d058b 100644 --- a/scripts/UnityTemplates/ClassNameCTest.cpp +++ b/scripts/UnityTemplates/ClassNameCTest.cpp @@ -1,26 +1,26 @@ -extern "C" -{ -#include "ClassName.h" -} - -//CppUTest includes should be after your and system includes -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - void setup() - { - ClassName_Create(); - } - - void teardown() - { - ClassName_Destroy(); - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} - +extern "C" +{ +#include "ClassName.h" +} + +//CppUTest includes should be after your and system includes +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + void setup() + { + ClassName_Create(); + } + + void teardown() + { + ClassName_Destroy(); + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} + diff --git a/scripts/UnityTemplates/FunctionNameCTest.cpp b/scripts/UnityTemplates/FunctionNameCTest.cpp index 2538287d7..afa8db4c5 100644 --- a/scripts/UnityTemplates/FunctionNameCTest.cpp +++ b/scripts/UnityTemplates/FunctionNameCTest.cpp @@ -1,24 +1,24 @@ -extern "C" -{ -#include "ClassName.h" -} - -//CppUTest includes should be after your and system includes -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - void setup() - { - } - - void teardown() - { - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} - +extern "C" +{ +#include "ClassName.h" +} + +//CppUTest includes should be after your and system includes +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + void setup() + { + } + + void teardown() + { + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} + diff --git a/scripts/UnityTemplates/InterfaceCTest.cpp b/scripts/UnityTemplates/InterfaceCTest.cpp index 6e088115b..8052f8156 100644 --- a/scripts/UnityTemplates/InterfaceCTest.cpp +++ b/scripts/UnityTemplates/InterfaceCTest.cpp @@ -1,25 +1,25 @@ -extern "C" -{ -#include "FakeClassName.h" -} - -//CppUTest includes should be after your and system includes -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - void setup() - { - ClassName_Create(); - } - - void teardown() - { - ClassName_Destroy(); - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} +extern "C" +{ +#include "FakeClassName.h" +} + +//CppUTest includes should be after your and system includes +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + void setup() + { + ClassName_Create(); + } + + void teardown() + { + ClassName_Destroy(); + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} diff --git a/scripts/squeeze.sh b/scripts/squeeze.sh index b5ce43f2a..18a4153d5 100755 --- a/scripts/squeeze.sh +++ b/scripts/squeeze.sh @@ -1,2 +1,2 @@ -#!/bin/sed -f -s/[ ][ ]*/ /g +#!/bin/sed -f +s/[ ][ ]*/ /g diff --git a/scripts/templates/ClassName.cpp b/scripts/templates/ClassName.cpp index f8a84ff2a..c80207946 100644 --- a/scripts/templates/ClassName.cpp +++ b/scripts/templates/ClassName.cpp @@ -1,10 +1,10 @@ -#include "ClassName.h" - -ClassName::ClassName() -{ -} - -ClassName::~ClassName() -{ -} - +#include "ClassName.h" + +ClassName::ClassName() +{ +} + +ClassName::~ClassName() +{ +} + diff --git a/scripts/templates/ClassName.h b/scripts/templates/ClassName.h index 5c62217c2..88803e2ec 100644 --- a/scripts/templates/ClassName.h +++ b/scripts/templates/ClassName.h @@ -1,23 +1,23 @@ -#ifndef D_ClassName_H -#define D_ClassName_H - -/////////////////////////////////////////////////////////////////////////////// -// -// ClassName is responsible for ... -// -/////////////////////////////////////////////////////////////////////////////// - -class ClassName - { - public: - explicit ClassName(); - virtual ~ClassName(); - - private: - - ClassName(const ClassName&); - ClassName& operator=(const ClassName&); - - }; - -#endif // D_ClassName_H +#ifndef D_ClassName_H +#define D_ClassName_H + +/////////////////////////////////////////////////////////////////////////////// +// +// ClassName is responsible for ... +// +/////////////////////////////////////////////////////////////////////////////// + +class ClassName + { + public: + explicit ClassName(); + virtual ~ClassName(); + + private: + + ClassName(const ClassName&); + ClassName& operator=(const ClassName&); + + }; + +#endif // D_ClassName_H diff --git a/scripts/templates/ClassNameC.c b/scripts/templates/ClassNameC.c index 67d7174f1..ffde4228a 100644 --- a/scripts/templates/ClassNameC.c +++ b/scripts/templates/ClassNameC.c @@ -1,11 +1,11 @@ -#include "ClassName.h" - -void ClassName_Create(void) -{ -} - -void ClassName_Destroy(void) -{ -} - - +#include "ClassName.h" + +void ClassName_Create(void) +{ +} + +void ClassName_Destroy(void) +{ +} + + diff --git a/scripts/templates/ClassNameC.h b/scripts/templates/ClassNameC.h index da8b6805c..af39b2e37 100644 --- a/scripts/templates/ClassNameC.h +++ b/scripts/templates/ClassNameC.h @@ -1,13 +1,13 @@ -#ifndef D_ClassName_H -#define D_ClassName_H - -/********************************************************** - * - * ClassName is responsible for ... - * - **********************************************************/ - -void ClassName_Create(void); -void ClassName_Destroy(void); - -#endif /* D_FakeClassName_H */ +#ifndef D_ClassName_H +#define D_ClassName_H + +/********************************************************** + * + * ClassName is responsible for ... + * + **********************************************************/ + +void ClassName_Create(void); +void ClassName_Destroy(void); + +#endif /* D_FakeClassName_H */ diff --git a/scripts/templates/ClassNameCIoDriverTest.cpp b/scripts/templates/ClassNameCIoDriverTest.cpp index a97eecdfc..94bb01cad 100644 --- a/scripts/templates/ClassNameCIoDriverTest.cpp +++ b/scripts/templates/ClassNameCIoDriverTest.cpp @@ -1,27 +1,27 @@ -extern "C" { -#include "ClassName.h" -#include "MockIO.h" -} - -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - void setup() - { - Reset_Mock_IO(); - ClassName_Create(); - } - - void teardown() - { - ClassName_Destroy(); - Assert_No_Unused_Expectations(); - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} - +extern "C" { +#include "ClassName.h" +#include "MockIO.h" +} + +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + void setup() + { + Reset_Mock_IO(); + ClassName_Create(); + } + + void teardown() + { + ClassName_Destroy(); + Assert_No_Unused_Expectations(); + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} + diff --git a/scripts/templates/ClassNameCMultipleInstance.c b/scripts/templates/ClassNameCMultipleInstance.c index d25f13916..5cd99e784 100644 --- a/scripts/templates/ClassNameCMultipleInstance.c +++ b/scripts/templates/ClassNameCMultipleInstance.c @@ -1,21 +1,21 @@ -#include "ClassName.h" -#include -#include - -typedef struct ClassNameStruct -{ - int placeHolderForHiddenStructElements; -} ClassNameStruct; - -ClassName ClassName_Create(void) -{ - ClassName self = calloc(1, sizeof(ClassNameStruct)); - return self; -} - -void ClassName_Destroy(ClassName self) -{ - free(self); -} - - +#include "ClassName.h" +#include +#include + +typedef struct ClassNameStruct +{ + int placeHolderForHiddenStructElements; +} ClassNameStruct; + +ClassName ClassName_Create(void) +{ + ClassName self = calloc(1, sizeof(ClassNameStruct)); + return self; +} + +void ClassName_Destroy(ClassName self) +{ + free(self); +} + + diff --git a/scripts/templates/ClassNameCMultipleInstance.h b/scripts/templates/ClassNameCMultipleInstance.h index 701cd0ea7..c7103cc2f 100644 --- a/scripts/templates/ClassNameCMultipleInstance.h +++ b/scripts/templates/ClassNameCMultipleInstance.h @@ -1,15 +1,15 @@ -#ifndef D_ClassName_H -#define D_ClassName_H - -/********************************************************************** - * - * ClassName is responsible for ... +#ifndef D_ClassName_H +#define D_ClassName_H + +/********************************************************************** * - **********************************************************************/ - -typedef struct ClassNameStruct * ClassName; - -ClassName ClassName_Create(void); -void ClassName_Destroy(ClassName); - -#endif /* D_FakeClassName_H */ + * ClassName is responsible for ... + * + **********************************************************************/ + +typedef struct ClassNameStruct * ClassName; + +ClassName ClassName_Create(void); +void ClassName_Destroy(ClassName); + +#endif /* D_FakeClassName_H */ diff --git a/scripts/templates/ClassNameCMultipleInstanceTest.cpp b/scripts/templates/ClassNameCMultipleInstanceTest.cpp index 832ad2588..a061b3eed 100644 --- a/scripts/templates/ClassNameCMultipleInstanceTest.cpp +++ b/scripts/templates/ClassNameCMultipleInstanceTest.cpp @@ -1,27 +1,27 @@ -extern "C" -{ -#include "ClassName.h" -} - -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - ClassName aClassName; - - void setup() - { - aClassName = ClassName_Create(); - } - - void teardown() - { - ClassName_Destroy(aClassName); - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} - +extern "C" +{ +#include "ClassName.h" +} + +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + ClassName aClassName; + + void setup() + { + aClassName = ClassName_Create(); + } + + void teardown() + { + ClassName_Destroy(aClassName); + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} + diff --git a/scripts/templates/ClassNameCPolymorphic.c b/scripts/templates/ClassNameCPolymorphic.c index e2c245c47..cf839bf84 100644 --- a/scripts/templates/ClassNameCPolymorphic.c +++ b/scripts/templates/ClassNameCPolymorphic.c @@ -1,22 +1,22 @@ -#include "ClassName.h" -#include -#include - -typedef struct ClassName -{ - int placeHolderForHiddenStructElements; -}; - -ClassName* ClassName_Create(void) -{ - ClassName* self = malloc(sizeof(ClassName)); - memset(self, 0, sizeof(ClassName)); - return self; -} - -void ClassName_Destroy(ClassName* self) -{ - free(self); -} - - +#include "ClassName.h" +#include +#include + +typedef struct ClassName +{ + int placeHolderForHiddenStructElements; +}; + +ClassName* ClassName_Create(void) +{ + ClassName* self = malloc(sizeof(ClassName)); + memset(self, 0, sizeof(ClassName)); + return self; +} + +void ClassName_Destroy(ClassName* self) +{ + free(self); +} + + diff --git a/scripts/templates/ClassNameCPolymorphic.h b/scripts/templates/ClassNameCPolymorphic.h index bcbbdb23a..af24a141c 100644 --- a/scripts/templates/ClassNameCPolymorphic.h +++ b/scripts/templates/ClassNameCPolymorphic.h @@ -1,16 +1,16 @@ -#ifndef D_ClassName_H -#define D_ClassName_H - -/********************************************************** - * - * ClassName is responsible for ... - * - **********************************************************/ - -typedef struct ClassName ClassNamePiml; - -ClassName* ClassName_Create(void); -void ClassName_Destroy(ClassName*); -void ClassName_VirtualFunction_impl(ClassName*); - -#endif /* D_FakeClassName_H */ +#ifndef D_ClassName_H +#define D_ClassName_H + +/********************************************************** + * + * ClassName is responsible for ... + * + **********************************************************/ + +typedef struct ClassName ClassNamePiml; + +ClassName* ClassName_Create(void); +void ClassName_Destroy(ClassName*); +void ClassName_VirtualFunction_impl(ClassName*); + +#endif /* D_FakeClassName_H */ diff --git a/scripts/templates/ClassNameCTest.cpp b/scripts/templates/ClassNameCTest.cpp index edf38676b..49e8b48e9 100644 --- a/scripts/templates/ClassNameCTest.cpp +++ b/scripts/templates/ClassNameCTest.cpp @@ -1,25 +1,25 @@ -extern "C" -{ -#include "ClassName.h" -} - -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - void setup() - { - ClassName_Create(); - } - - void teardown() - { - ClassName_Destroy(); - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} - +extern "C" +{ +#include "ClassName.h" +} + +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + void setup() + { + ClassName_Create(); + } + + void teardown() + { + ClassName_Destroy(); + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} + diff --git a/scripts/templates/ClassNameTest.cpp b/scripts/templates/ClassNameTest.cpp index 444d503eb..5b0780150 100644 --- a/scripts/templates/ClassNameTest.cpp +++ b/scripts/templates/ClassNameTest.cpp @@ -1,24 +1,24 @@ -#include "ClassName.h" - -//CppUTest includes should be after your and system includes -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - ClassName* aClassName; - - void setup() - { - aClassName = new ClassName(); - } - void teardown() - { - delete aClassName; - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} - +#include "ClassName.h" + +//CppUTest includes should be after your and system includes +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + ClassName* aClassName; + + void setup() + { + aClassName = new ClassName(); + } + void teardown() + { + delete aClassName; + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} + diff --git a/scripts/templates/FunctionNameC.c b/scripts/templates/FunctionNameC.c index 26f148a76..6c8cc20d5 100644 --- a/scripts/templates/FunctionNameC.c +++ b/scripts/templates/FunctionNameC.c @@ -1,5 +1,5 @@ -#include "ClassName.h" - -void ClassName() -{ -} +#include "ClassName.h" + +void ClassName() +{ +} diff --git a/scripts/templates/FunctionNameC.h b/scripts/templates/FunctionNameC.h index 89b1d3dae..39cbf2f08 100644 --- a/scripts/templates/FunctionNameC.h +++ b/scripts/templates/FunctionNameC.h @@ -1,12 +1,12 @@ -#ifndef D_ClassName_H -#define D_ClassName_H - -/********************************************************** - * - * ClassName is responsible for ... - * - **********************************************************/ - -void ClassName(); - -#endif /* D_FakeClassName_H */ +#ifndef D_ClassName_H +#define D_ClassName_H + +/********************************************************** + * + * ClassName is responsible for ... + * + **********************************************************/ + +void ClassName(); + +#endif /* D_FakeClassName_H */ diff --git a/scripts/templates/FunctionNameCTest.cpp b/scripts/templates/FunctionNameCTest.cpp index d74900b36..07cc16428 100644 --- a/scripts/templates/FunctionNameCTest.cpp +++ b/scripts/templates/FunctionNameCTest.cpp @@ -1,23 +1,23 @@ -extern "C" -{ -#include "ClassName.h" -} - -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - void setup() - { - } - - void teardown() - { - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} - +extern "C" +{ +#include "ClassName.h" +} + +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + void setup() + { + } + + void teardown() + { + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} + diff --git a/scripts/templates/InterfaceCTest.cpp b/scripts/templates/InterfaceCTest.cpp index 6e088115b..8052f8156 100644 --- a/scripts/templates/InterfaceCTest.cpp +++ b/scripts/templates/InterfaceCTest.cpp @@ -1,25 +1,25 @@ -extern "C" -{ -#include "FakeClassName.h" -} - -//CppUTest includes should be after your and system includes -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - void setup() - { - ClassName_Create(); - } - - void teardown() - { - ClassName_Destroy(); - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} +extern "C" +{ +#include "FakeClassName.h" +} + +//CppUTest includes should be after your and system includes +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + void setup() + { + ClassName_Create(); + } + + void teardown() + { + ClassName_Destroy(); + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} diff --git a/scripts/templates/InterfaceTest.cpp b/scripts/templates/InterfaceTest.cpp index ab2272c0f..571336de9 100644 --- a/scripts/templates/InterfaceTest.cpp +++ b/scripts/templates/InterfaceTest.cpp @@ -1,25 +1,25 @@ -#include "ClassName.h" -#include "MockClassName.h" - -#include "CppUTest/TestHarness.h" - -TEST_GROUP(ClassName) -{ - ClassName* aClassName; - MockClassName* mockClassName; - - void setup() - { - mockClassName = new MockClassName(); - aClassName = mockClassName; - } - void teardown() - { - delete aClassName; - } -}; - -TEST(ClassName, Create) -{ - FAIL("Start here"); -} +#include "ClassName.h" +#include "MockClassName.h" + +#include "CppUTest/TestHarness.h" + +TEST_GROUP(ClassName) +{ + ClassName* aClassName; + MockClassName* mockClassName; + + void setup() + { + mockClassName = new MockClassName(); + aClassName = mockClassName; + } + void teardown() + { + delete aClassName; + } +}; + +TEST(ClassName, Create) +{ + FAIL("Start here"); +} diff --git a/scripts/templates/MockClassName.h b/scripts/templates/MockClassName.h index 8588b72a4..0e6778928 100644 --- a/scripts/templates/MockClassName.h +++ b/scripts/templates/MockClassName.h @@ -1,29 +1,29 @@ -#ifndef D_MockClassName_H -#define D_MockClassName_H - -/////////////////////////////////////////////////////////////////////////////// -// -// MockClassName.h -// -// MockClassName is responsible for providing a test stub for ClassName -// -/////////////////////////////////////////////////////////////////////////////// -#include "ClassName.h" - - -class MockClassName : public ClassName - { - public: - explicit MockClassName() - {} - virtual ~MockClassName() - {} - - private: - - MockClassName(const MockClassName&); - MockClassName& operator=(const MockClassName&); - - }; - -#endif // D_MockClassName_H +#ifndef D_MockClassName_H +#define D_MockClassName_H + +/////////////////////////////////////////////////////////////////////////////// +// +// MockClassName.h +// +// MockClassName is responsible for providing a test stub for ClassName +// +/////////////////////////////////////////////////////////////////////////////// +#include "ClassName.h" + + +class MockClassName : public ClassName + { + public: + explicit MockClassName() + {} + virtual ~MockClassName() + {} + + private: + + MockClassName(const MockClassName&); + MockClassName& operator=(const MockClassName&); + + }; + +#endif // D_MockClassName_H diff --git a/scripts/templates/MockClassNameC.c b/scripts/templates/MockClassNameC.c index 67d7174f1..ffde4228a 100644 --- a/scripts/templates/MockClassNameC.c +++ b/scripts/templates/MockClassNameC.c @@ -1,11 +1,11 @@ -#include "ClassName.h" - -void ClassName_Create(void) -{ -} - -void ClassName_Destroy(void) -{ -} - - +#include "ClassName.h" + +void ClassName_Create(void) +{ +} + +void ClassName_Destroy(void) +{ +} + + diff --git a/scripts/templates/MockClassNameC.h b/scripts/templates/MockClassNameC.h index e3d8dc144..a9059d83c 100644 --- a/scripts/templates/MockClassNameC.h +++ b/scripts/templates/MockClassNameC.h @@ -1,13 +1,13 @@ -#ifndef D_FakeClassName_H -#define D_FakeClassName_H - -/********************************************************** - * - * FakeClassName is responsible for providing a - * test stub for ClassName - * - **********************************************************/ - -#include "ClassName.h" - -#endif /* D_FakeClassName_H */ +#ifndef D_FakeClassName_H +#define D_FakeClassName_H + +/********************************************************** + * + * FakeClassName is responsible for providing a + * test stub for ClassName + * + **********************************************************/ + +#include "ClassName.h" + +#endif /* D_FakeClassName_H */ diff --git a/scripts/templates/ProjectTemplate/tests/AllTests.cpp b/scripts/templates/ProjectTemplate/tests/AllTests.cpp index 31a390715..3932fd103 100644 --- a/scripts/templates/ProjectTemplate/tests/AllTests.cpp +++ b/scripts/templates/ProjectTemplate/tests/AllTests.cpp @@ -1,8 +1,8 @@ - -#include "CppUTest/CommandLineTestRunner.h" - -int main(int ac, char** av) -{ - return CommandLineTestRunner::RunAllTests(ac, av); -} - + +#include "CppUTest/CommandLineTestRunner.h" + +int main(int ac, char** av) +{ + return CommandLineTestRunner::RunAllTests(ac, av); +} + diff --git a/src/CppUTest/CommandLineArguments.cpp b/src/CppUTest/CommandLineArguments.cpp index dc9887142..02e59245e 100644 --- a/src/CppUTest/CommandLineArguments.cpp +++ b/src/CppUTest/CommandLineArguments.cpp @@ -1,193 +1,193 @@ -/* - * 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/CommandLineArguments.h" -#include "CppUTest/PlatformSpecificFunctions.h" - -CommandLineArguments::CommandLineArguments(int ac, const char** av) : - ac_(ac), av_(av), verbose_(false), runTestsAsSeperateProcess_(false), repeat_(1), groupFilter_(""), nameFilter_(""), outputType_(OUTPUT_ECLIPSE), packageName_("") -{ -} - -CommandLineArguments::~CommandLineArguments() -{ -} - -bool CommandLineArguments::parse(TestPlugin* plugin) -{ - bool correctParameters = true; - for (int i = 1; i < ac_; i++) { - SimpleString argument = av_[i]; - if (argument == "-v") verbose_ = true; - else if (argument == "-p") runTestsAsSeperateProcess_ = true; - else if (argument.startsWith("-r")) SetRepeatCount(ac_, av_, i); - else if (argument.startsWith("-g")) SetGroupFilter(ac_, av_, i); - else if (argument.startsWith("-sg")) SetStrictGroupFilter(ac_, av_, i); - else if (argument.startsWith("-n")) SetNameFilter(ac_, av_, i); - else if (argument.startsWith("-sn")) SetStrictNameFilter(ac_, av_, i); - else if (argument.startsWith("TEST(")) SetTestToRunBasedOnVerboseOutput(ac_, av_, i, "TEST("); - else if (argument.startsWith("IGNORE_TEST(")) SetTestToRunBasedOnVerboseOutput(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 correctParameters = false; - - if (correctParameters == false) { - return false; - } - } - return true; -} - -const char* CommandLineArguments::usage() const -{ - return "usage [-v] [-r#] [-g|sg groupName] [-n|sn testName] [-o{normal, junit}] [-k packageName]\n"; -} - -bool CommandLineArguments::isVerbose() const -{ - return verbose_; -} - -bool CommandLineArguments::runTestsInSeperateProcess() const -{ - return runTestsAsSeperateProcess_; -} - - -int CommandLineArguments::getRepeatCount() const -{ - return repeat_; -} - -TestFilter CommandLineArguments::getGroupFilter() const -{ - return groupFilter_; -} - -TestFilter CommandLineArguments::getNameFilter() const -{ - return nameFilter_; -} - -void CommandLineArguments::SetRepeatCount(int ac, const char** av, int& i) -{ - repeat_ = 0; - - SimpleString repeatParameter(av[i]); - if (repeatParameter.size() > 2) repeat_ = PlatformSpecificAtoI(av[i] + 2); - else if (i + 1 < ac) { - repeat_ = PlatformSpecificAtoI(av[i + 1]); - if (repeat_ != 0) i++; - } - - if (0 == repeat_) repeat_ = 2; - -} - -SimpleString CommandLineArguments::getParameterField(int ac, const char** av, int& i, const SimpleString& parameterName) -{ - size_t parameterLength = parameterName.size(); - SimpleString parameter(av[i]); - if (parameter.size() > parameterLength) return av[i] + parameterLength; - else if (i + 1 < ac) return av[++i]; - return ""; -} - -void CommandLineArguments::SetGroupFilter(int ac, const char** av, int& i) -{ - groupFilter_ = TestFilter(getParameterField(ac, av, i, "-g")); -} - -void CommandLineArguments::SetStrictGroupFilter(int ac, const char** av, int& i) -{ - groupFilter_ = TestFilter(getParameterField(ac, av, i, "-sg")); - groupFilter_.strictMatching(); -} - -void CommandLineArguments::SetNameFilter(int ac, const char** av, int& i) -{ - nameFilter_ = getParameterField(ac, av, i, "-n"); -} - -void CommandLineArguments::SetStrictNameFilter(int ac, const char** av, int& index) -{ - nameFilter_ = getParameterField(ac, av, index, "-sn"); - nameFilter_.strictMatching(); -} - -void CommandLineArguments::SetTestToRunBasedOnVerboseOutput(int ac, const char** av, int& index, const char* parameterName) -{ - SimpleString wholename = getParameterField(ac, av, index, parameterName); - SimpleString testname = wholename.subStringFromTill(',', ')'); - testname = testname.subString(2, testname.size()); - groupFilter_ = wholename.subStringFromTill(wholename.at(0), ','); - nameFilter_ = testname; - nameFilter_.strictMatching(); - groupFilter_.strictMatching(); -} - -void CommandLineArguments::SetPackageName(int ac, const char** av, int& i) -{ - SimpleString packageName = getParameterField(ac, av, i, "-k"); - if (packageName.size() == 0) return; - - packageName_ = packageName; -} - -bool CommandLineArguments::SetOutputType(int ac, const char** av, int& i) -{ - SimpleString outputType = getParameterField(ac, av, i, "-o"); - if (outputType.size() == 0) return false; - - if (outputType == "normal" || outputType == "eclipse") { - outputType_ = OUTPUT_ECLIPSE; - return true; - } - if (outputType == "junit") { - outputType_ = OUTPUT_JUNIT; - return true; - } - return false; -} - -bool CommandLineArguments::isEclipseOutput() const -{ - return outputType_ == OUTPUT_ECLIPSE; -} - -bool CommandLineArguments::isJUnitOutput() const -{ - return outputType_ == OUTPUT_JUNIT; -} - -const SimpleString& CommandLineArguments::getPackageName() const -{ - return packageName_; -} - +/* + * 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/CommandLineArguments.h" +#include "CppUTest/PlatformSpecificFunctions.h" + +CommandLineArguments::CommandLineArguments(int ac, const char** av) : + ac_(ac), av_(av), verbose_(false), runTestsAsSeperateProcess_(false), repeat_(1), groupFilter_(""), nameFilter_(""), outputType_(OUTPUT_ECLIPSE), packageName_("") +{ +} + +CommandLineArguments::~CommandLineArguments() +{ +} + +bool CommandLineArguments::parse(TestPlugin* plugin) +{ + bool correctParameters = true; + for (int i = 1; i < ac_; i++) { + SimpleString argument = av_[i]; + if (argument == "-v") verbose_ = true; + else if (argument == "-p") runTestsAsSeperateProcess_ = true; + else if (argument.startsWith("-r")) SetRepeatCount(ac_, av_, i); + else if (argument.startsWith("-g")) SetGroupFilter(ac_, av_, i); + else if (argument.startsWith("-sg")) SetStrictGroupFilter(ac_, av_, i); + else if (argument.startsWith("-n")) SetNameFilter(ac_, av_, i); + else if (argument.startsWith("-sn")) SetStrictNameFilter(ac_, av_, i); + else if (argument.startsWith("TEST(")) SetTestToRunBasedOnVerboseOutput(ac_, av_, i, "TEST("); + else if (argument.startsWith("IGNORE_TEST(")) SetTestToRunBasedOnVerboseOutput(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 correctParameters = false; + + if (correctParameters == false) { + return false; + } + } + return true; +} + +const char* CommandLineArguments::usage() const +{ + return "usage [-v] [-r#] [-g|sg groupName] [-n|sn testName] [-o{normal, junit}] [-k packageName]\n"; +} + +bool CommandLineArguments::isVerbose() const +{ + return verbose_; +} + +bool CommandLineArguments::runTestsInSeperateProcess() const +{ + return runTestsAsSeperateProcess_; +} + + +int CommandLineArguments::getRepeatCount() const +{ + return repeat_; +} + +TestFilter CommandLineArguments::getGroupFilter() const +{ + return groupFilter_; +} + +TestFilter CommandLineArguments::getNameFilter() const +{ + return nameFilter_; +} + +void CommandLineArguments::SetRepeatCount(int ac, const char** av, int& i) +{ + repeat_ = 0; + + SimpleString repeatParameter(av[i]); + if (repeatParameter.size() > 2) repeat_ = PlatformSpecificAtoI(av[i] + 2); + else if (i + 1 < ac) { + repeat_ = PlatformSpecificAtoI(av[i + 1]); + if (repeat_ != 0) i++; + } + + if (0 == repeat_) repeat_ = 2; + +} + +SimpleString CommandLineArguments::getParameterField(int ac, const char** av, int& i, const SimpleString& parameterName) +{ + size_t parameterLength = parameterName.size(); + SimpleString parameter(av[i]); + if (parameter.size() > parameterLength) return av[i] + parameterLength; + else if (i + 1 < ac) return av[++i]; + return ""; +} + +void CommandLineArguments::SetGroupFilter(int ac, const char** av, int& i) +{ + groupFilter_ = TestFilter(getParameterField(ac, av, i, "-g")); +} + +void CommandLineArguments::SetStrictGroupFilter(int ac, const char** av, int& i) +{ + groupFilter_ = TestFilter(getParameterField(ac, av, i, "-sg")); + groupFilter_.strictMatching(); +} + +void CommandLineArguments::SetNameFilter(int ac, const char** av, int& i) +{ + nameFilter_ = getParameterField(ac, av, i, "-n"); +} + +void CommandLineArguments::SetStrictNameFilter(int ac, const char** av, int& index) +{ + nameFilter_ = getParameterField(ac, av, index, "-sn"); + nameFilter_.strictMatching(); +} + +void CommandLineArguments::SetTestToRunBasedOnVerboseOutput(int ac, const char** av, int& index, const char* parameterName) +{ + SimpleString wholename = getParameterField(ac, av, index, parameterName); + SimpleString testname = wholename.subStringFromTill(',', ')'); + testname = testname.subString(2, testname.size()); + groupFilter_ = wholename.subStringFromTill(wholename.at(0), ','); + nameFilter_ = testname; + nameFilter_.strictMatching(); + groupFilter_.strictMatching(); +} + +void CommandLineArguments::SetPackageName(int ac, const char** av, int& i) +{ + SimpleString packageName = getParameterField(ac, av, i, "-k"); + if (packageName.size() == 0) return; + + packageName_ = packageName; +} + +bool CommandLineArguments::SetOutputType(int ac, const char** av, int& i) +{ + SimpleString outputType = getParameterField(ac, av, i, "-o"); + if (outputType.size() == 0) return false; + + if (outputType == "normal" || outputType == "eclipse") { + outputType_ = OUTPUT_ECLIPSE; + return true; + } + if (outputType == "junit") { + outputType_ = OUTPUT_JUNIT; + return true; + } + return false; +} + +bool CommandLineArguments::isEclipseOutput() const +{ + return outputType_ == OUTPUT_ECLIPSE; +} + +bool CommandLineArguments::isJUnitOutput() const +{ + return outputType_ == OUTPUT_JUNIT; +} + +const SimpleString& CommandLineArguments::getPackageName() const +{ + return packageName_; +} + diff --git a/src/CppUTest/CommandLineTestRunner.cpp b/src/CppUTest/CommandLineTestRunner.cpp index 7d7433319..640b36877 100644 --- a/src/CppUTest/CommandLineTestRunner.cpp +++ b/src/CppUTest/CommandLineTestRunner.cpp @@ -1,146 +1,146 @@ -/* - * 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/CommandLineTestRunner.h" -#include "CppUTest/TestOutput.h" -#include "CppUTest/JUnitTestOutput.h" -#include "CppUTest/TestRegistry.h" - -CommandLineTestRunner::CommandLineTestRunner(int ac, const char** av, TestOutput* output, TestRegistry* registry) : - output_(output), jUnitOutput_(NULL), arguments_(NULL), registry_(registry) -{ - arguments_ = new CommandLineArguments(ac, av); -} - -CommandLineTestRunner::~CommandLineTestRunner() -{ - delete arguments_; - delete jUnitOutput_; -} - -int CommandLineTestRunner::RunAllTests(int ac, char** av) -{ - return RunAllTests(ac, const_cast (av)); -} - -int CommandLineTestRunner::RunAllTests(int ac, const char** av) -{ - int result = 0; - ConsoleTestOutput output; - - MemoryLeakWarningPlugin memLeakWarn(DEF_PLUGIN_MEM_LEAK); - memLeakWarn.destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(true); - TestRegistry::getCurrentRegistry()->installPlugin(&memLeakWarn); - - { - CommandLineTestRunner runner(ac, av, &output, TestRegistry::getCurrentRegistry()); - result = runner.runAllTestsMain(); - } - - if (result == 0) { - output << memLeakWarn.FinalReport(0); - } - TestRegistry::getCurrentRegistry()->removePluginByName(DEF_PLUGIN_MEM_LEAK); - return result; -} - -int CommandLineTestRunner::runAllTestsMain() -{ - int testResult = 0; - - SetPointerPlugin pPlugin(DEF_PLUGIN_SET_POINTER); - registry_->installPlugin(&pPlugin); - - if (parseArguments(registry_->getFirstPlugin())) - testResult = runAllTests(); - - registry_->removePluginByName(DEF_PLUGIN_SET_POINTER); - return testResult; -} - -void CommandLineTestRunner::initializeTestRun() -{ - registry_->groupFilter(arguments_->getGroupFilter()); - registry_->nameFilter(arguments_->getNameFilter()); - if (arguments_->isVerbose()) output_->verbose(); - if (arguments_->runTestsInSeperateProcess()) registry_->setRunTestsInSeperateProcess(); -} - -int CommandLineTestRunner::runAllTests() -{ - initializeTestRun(); - int loopCount = 0; - int failureCount = 0; - int repeat_ = arguments_->getRepeatCount(); - - while (loopCount++ < repeat_) { - output_->printTestRun(loopCount, repeat_); - TestResult tr(*output_); - registry_->runAllTests(tr); - failureCount += tr.getFailureCount(); - } - - return failureCount; -} - -bool CommandLineTestRunner::parseArguments(TestPlugin* plugin) -{ - if (arguments_->parse(plugin)) { - if (arguments_->isJUnitOutput()) { - output_ = jUnitOutput_ = new JUnitTestOutput; - if (jUnitOutput_ != NULL) { - jUnitOutput_->setPackageName(arguments_->getPackageName()); - } - } - return true; - } - else { - output_->print(arguments_->usage()); - return false; - } -} - -bool CommandLineTestRunner::isVerbose() -{ - return arguments_->isVerbose(); -} - -int CommandLineTestRunner::getRepeatCount() -{ - return arguments_->getRepeatCount(); -} - -TestFilter CommandLineTestRunner::getGroupFilter() -{ - return arguments_->getGroupFilter(); -} - -TestFilter CommandLineTestRunner::getNameFilter() -{ - return arguments_->getNameFilter(); -} +/* + * 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/CommandLineTestRunner.h" +#include "CppUTest/TestOutput.h" +#include "CppUTest/JUnitTestOutput.h" +#include "CppUTest/TestRegistry.h" + +CommandLineTestRunner::CommandLineTestRunner(int ac, const char** av, TestOutput* output, TestRegistry* registry) : + output_(output), jUnitOutput_(NULL), arguments_(NULL), registry_(registry) +{ + arguments_ = new CommandLineArguments(ac, av); +} + +CommandLineTestRunner::~CommandLineTestRunner() +{ + delete arguments_; + delete jUnitOutput_; +} + +int CommandLineTestRunner::RunAllTests(int ac, char** av) +{ + return RunAllTests(ac, const_cast (av)); +} + +int CommandLineTestRunner::RunAllTests(int ac, const char** av) +{ + int result = 0; + ConsoleTestOutput output; + + MemoryLeakWarningPlugin memLeakWarn(DEF_PLUGIN_MEM_LEAK); + memLeakWarn.destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(true); + TestRegistry::getCurrentRegistry()->installPlugin(&memLeakWarn); + + { + CommandLineTestRunner runner(ac, av, &output, TestRegistry::getCurrentRegistry()); + result = runner.runAllTestsMain(); + } + + if (result == 0) { + output << memLeakWarn.FinalReport(0); + } + TestRegistry::getCurrentRegistry()->removePluginByName(DEF_PLUGIN_MEM_LEAK); + return result; +} + +int CommandLineTestRunner::runAllTestsMain() +{ + int testResult = 0; + + SetPointerPlugin pPlugin(DEF_PLUGIN_SET_POINTER); + registry_->installPlugin(&pPlugin); + + if (parseArguments(registry_->getFirstPlugin())) + testResult = runAllTests(); + + registry_->removePluginByName(DEF_PLUGIN_SET_POINTER); + return testResult; +} + +void CommandLineTestRunner::initializeTestRun() +{ + registry_->groupFilter(arguments_->getGroupFilter()); + registry_->nameFilter(arguments_->getNameFilter()); + if (arguments_->isVerbose()) output_->verbose(); + if (arguments_->runTestsInSeperateProcess()) registry_->setRunTestsInSeperateProcess(); +} + +int CommandLineTestRunner::runAllTests() +{ + initializeTestRun(); + int loopCount = 0; + int failureCount = 0; + int repeat_ = arguments_->getRepeatCount(); + + while (loopCount++ < repeat_) { + output_->printTestRun(loopCount, repeat_); + TestResult tr(*output_); + registry_->runAllTests(tr); + failureCount += tr.getFailureCount(); + } + + return failureCount; +} + +bool CommandLineTestRunner::parseArguments(TestPlugin* plugin) +{ + if (arguments_->parse(plugin)) { + if (arguments_->isJUnitOutput()) { + output_ = jUnitOutput_ = new JUnitTestOutput; + if (jUnitOutput_ != NULL) { + jUnitOutput_->setPackageName(arguments_->getPackageName()); + } + } + return true; + } + else { + output_->print(arguments_->usage()); + return false; + } +} + +bool CommandLineTestRunner::isVerbose() +{ + return arguments_->isVerbose(); +} + +int CommandLineTestRunner::getRepeatCount() +{ + return arguments_->getRepeatCount(); +} + +TestFilter CommandLineTestRunner::getGroupFilter() +{ + return arguments_->getGroupFilter(); +} + +TestFilter CommandLineTestRunner::getNameFilter() +{ + return arguments_->getNameFilter(); +} diff --git a/src/CppUTest/JUnitTestOutput.cpp b/src/CppUTest/JUnitTestOutput.cpp index e5199263a..0eacf9c0f 100644 --- a/src/CppUTest/JUnitTestOutput.cpp +++ b/src/CppUTest/JUnitTestOutput.cpp @@ -1,280 +1,280 @@ -/* - * 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/JUnitTestOutput.h" -#include "CppUTest/TestResult.h" -#include "CppUTest/TestFailure.h" -#include "CppUTest/PlatformSpecificFunctions.h" - -struct JUnitTestCaseResultNode -{ - JUnitTestCaseResultNode() : - execTime_(0), failure_(0), next_(0) - { - } - - SimpleString name_; - long execTime_; - TestFailure* failure_; - JUnitTestCaseResultNode* next_; -}; - -struct JUnitTestGroupResult -{ - JUnitTestGroupResult() : - testCount_(0), failureCount_(0), startTime_(0), groupExecTime_(0), head_(0), tail_(0) - { - } - - int testCount_; - int failureCount_; - long startTime_; - long groupExecTime_; - SimpleString group_; - JUnitTestCaseResultNode* head_; - JUnitTestCaseResultNode* tail_; -}; - -struct JUnitTestOutputImpl -{ - JUnitTestGroupResult results_; - PlatformSpecificFile file_; - SimpleString package_; -}; - -JUnitTestOutput::JUnitTestOutput() : - impl_(new JUnitTestOutputImpl) -{ -} - -JUnitTestOutput::~JUnitTestOutput() -{ - resetTestGroupResult(); - delete impl_; -} - -void JUnitTestOutput::resetTestGroupResult() -{ - impl_->results_.testCount_ = 0; - impl_->results_.failureCount_ = 0; - impl_->results_.group_ = ""; - JUnitTestCaseResultNode* cur = impl_->results_.head_; - while (cur) { - JUnitTestCaseResultNode* tmp = cur->next_; - ; - if (cur->failure_) delete cur->failure_; - delete cur; - cur = tmp; - } - impl_->results_.head_ = 0; - impl_->results_.tail_ = 0; -} - -void JUnitTestOutput::printTestsStarted() -{ -} - -void JUnitTestOutput::printCurrentGroupStarted(const UtestShell& /*test*/) -{ -} - -void JUnitTestOutput::printCurrentTestEnded(const TestResult& result) -{ - impl_->results_.tail_->execTime_ - = result.getCurrentTestTotalExecutionTime(); -} - -void JUnitTestOutput::printTestsEnded(const TestResult& /*result*/) -{ -} - -void JUnitTestOutput::printCurrentGroupEnded(const TestResult& result) -{ - impl_->results_.groupExecTime_ = result.getCurrentGroupTotalExecutionTime(); - writeTestGroupToFile(); - resetTestGroupResult(); -} - -void JUnitTestOutput::printCurrentTestStarted(const UtestShell& test) -{ - impl_->results_.testCount_++; - impl_->results_.group_ = test.getGroup(); - impl_->results_.startTime_ = GetPlatformSpecificTimeInMillis(); - - if (impl_->results_.tail_ == 0) { - impl_->results_.head_ = impl_->results_.tail_ - = new JUnitTestCaseResultNode; - } - else { - impl_->results_.tail_->next_ = new JUnitTestCaseResultNode; - impl_->results_.tail_ = impl_->results_.tail_->next_; - } - impl_->results_.tail_->name_ = test.getName(); -} - -SimpleString JUnitTestOutput::createFileName(const SimpleString& group) -{ - SimpleString fileName = "cpputest_"; - fileName += group; - fileName.replace('/', '_'); - fileName += ".xml"; - return fileName; -} - -void JUnitTestOutput::setPackageName(const SimpleString& package) -{ - if (impl_ != NULL) { - impl_->package_ = package; - } -} - -void JUnitTestOutput::writeXmlHeader() -{ - writeToFile("\n"); -} - -void JUnitTestOutput::writeTestSuiteSummery() -{ - SimpleString - buf = - StringFromFormat( - "\n", - impl_->results_.failureCount_, - impl_->results_.group_.asCharString(), - impl_->results_.testCount_, - (int) (impl_->results_.groupExecTime_ / 1000), (int) (impl_->results_.groupExecTime_ % 1000), - GetPlatformSpecificTimeString()); - writeToFile(buf.asCharString()); -} - -void JUnitTestOutput::writeProperties() -{ - writeToFile("\n"); - writeToFile("\n"); -} - -void JUnitTestOutput::writeTestCases() -{ - JUnitTestCaseResultNode* cur = impl_->results_.head_; - while (cur) { - SimpleString buf = StringFromFormat( - "\n", - impl_->package_.asCharString(), - impl_->package_.isEmpty() == true ? "" : ".", - impl_->results_.group_.asCharString(), - cur->name_.asCharString(), (int) (cur->execTime_ / 1000), (int)(cur->execTime_ % 1000)); - writeToFile(buf.asCharString()); - - if (cur->failure_) { - writeFailure(cur); - } - writeToFile("\n"); - cur = cur->next_; - } -} - -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()); - writeToFile(buf.asCharString()); - writeToFile("\n"); -} - -void JUnitTestOutput::writeFileEnding() -{ - writeToFile("\n"); - writeToFile("\n"); - writeToFile(""); -} - -void JUnitTestOutput::writeTestGroupToFile() -{ - openFileForWrite(createFileName(impl_->results_.group_)); - writeXmlHeader(); - writeTestSuiteSummery(); - writeProperties(); - writeTestCases(); - writeFileEnding(); - closeFile(); -} - -void JUnitTestOutput::verbose() -{ -} - -void JUnitTestOutput::printBuffer(const char*) -{ -} - -void JUnitTestOutput::print(const char*) -{ -} - -void JUnitTestOutput::print(long) -{ -} - -void JUnitTestOutput::print(const TestFailure& failure) -{ - if (impl_->results_.tail_->failure_ == 0) { - impl_->results_.failureCount_++; - impl_->results_.tail_->failure_ = new TestFailure(failure); - } -} - -void JUnitTestOutput::printTestRun(int /*number*/, int /*total*/) -{ -} - -void JUnitTestOutput::flush() -{ -} - -void JUnitTestOutput::openFileForWrite(const SimpleString& fileName) -{ - impl_->file_ = PlatformSpecificFOpen(fileName.asCharString(), "w"); -} - -void JUnitTestOutput::writeToFile(const SimpleString& buffer) -{ - PlatformSpecificFPuts(buffer.asCharString(), impl_->file_); -} - -void JUnitTestOutput::closeFile() -{ - PlatformSpecificFClose(impl_->file_); -} +/* + * 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/JUnitTestOutput.h" +#include "CppUTest/TestResult.h" +#include "CppUTest/TestFailure.h" +#include "CppUTest/PlatformSpecificFunctions.h" + +struct JUnitTestCaseResultNode +{ + JUnitTestCaseResultNode() : + execTime_(0), failure_(0), next_(0) + { + } + + SimpleString name_; + long execTime_; + TestFailure* failure_; + JUnitTestCaseResultNode* next_; +}; + +struct JUnitTestGroupResult +{ + JUnitTestGroupResult() : + testCount_(0), failureCount_(0), startTime_(0), groupExecTime_(0), head_(0), tail_(0) + { + } + + int testCount_; + int failureCount_; + long startTime_; + long groupExecTime_; + SimpleString group_; + JUnitTestCaseResultNode* head_; + JUnitTestCaseResultNode* tail_; +}; + +struct JUnitTestOutputImpl +{ + JUnitTestGroupResult results_; + PlatformSpecificFile file_; + SimpleString package_; +}; + +JUnitTestOutput::JUnitTestOutput() : + impl_(new JUnitTestOutputImpl) +{ +} + +JUnitTestOutput::~JUnitTestOutput() +{ + resetTestGroupResult(); + delete impl_; +} + +void JUnitTestOutput::resetTestGroupResult() +{ + impl_->results_.testCount_ = 0; + impl_->results_.failureCount_ = 0; + impl_->results_.group_ = ""; + JUnitTestCaseResultNode* cur = impl_->results_.head_; + while (cur) { + JUnitTestCaseResultNode* tmp = cur->next_; + ; + if (cur->failure_) delete cur->failure_; + delete cur; + cur = tmp; + } + impl_->results_.head_ = 0; + impl_->results_.tail_ = 0; +} + +void JUnitTestOutput::printTestsStarted() +{ +} + +void JUnitTestOutput::printCurrentGroupStarted(const UtestShell& /*test*/) +{ +} + +void JUnitTestOutput::printCurrentTestEnded(const TestResult& result) +{ + impl_->results_.tail_->execTime_ + = result.getCurrentTestTotalExecutionTime(); +} + +void JUnitTestOutput::printTestsEnded(const TestResult& /*result*/) +{ +} + +void JUnitTestOutput::printCurrentGroupEnded(const TestResult& result) +{ + impl_->results_.groupExecTime_ = result.getCurrentGroupTotalExecutionTime(); + writeTestGroupToFile(); + resetTestGroupResult(); +} + +void JUnitTestOutput::printCurrentTestStarted(const UtestShell& test) +{ + impl_->results_.testCount_++; + impl_->results_.group_ = test.getGroup(); + impl_->results_.startTime_ = GetPlatformSpecificTimeInMillis(); + + if (impl_->results_.tail_ == 0) { + impl_->results_.head_ = impl_->results_.tail_ + = new JUnitTestCaseResultNode; + } + else { + impl_->results_.tail_->next_ = new JUnitTestCaseResultNode; + impl_->results_.tail_ = impl_->results_.tail_->next_; + } + impl_->results_.tail_->name_ = test.getName(); +} + +SimpleString JUnitTestOutput::createFileName(const SimpleString& group) +{ + SimpleString fileName = "cpputest_"; + fileName += group; + fileName.replace('/', '_'); + fileName += ".xml"; + return fileName; +} + +void JUnitTestOutput::setPackageName(const SimpleString& package) +{ + if (impl_ != NULL) { + impl_->package_ = package; + } +} + +void JUnitTestOutput::writeXmlHeader() +{ + writeToFile("\n"); +} + +void JUnitTestOutput::writeTestSuiteSummery() +{ + SimpleString + buf = + StringFromFormat( + "\n", + impl_->results_.failureCount_, + impl_->results_.group_.asCharString(), + impl_->results_.testCount_, + (int) (impl_->results_.groupExecTime_ / 1000), (int) (impl_->results_.groupExecTime_ % 1000), + GetPlatformSpecificTimeString()); + writeToFile(buf.asCharString()); +} + +void JUnitTestOutput::writeProperties() +{ + writeToFile("\n"); + writeToFile("\n"); +} + +void JUnitTestOutput::writeTestCases() +{ + JUnitTestCaseResultNode* cur = impl_->results_.head_; + while (cur) { + SimpleString buf = StringFromFormat( + "\n", + impl_->package_.asCharString(), + impl_->package_.isEmpty() == true ? "" : ".", + impl_->results_.group_.asCharString(), + cur->name_.asCharString(), (int) (cur->execTime_ / 1000), (int)(cur->execTime_ % 1000)); + writeToFile(buf.asCharString()); + + if (cur->failure_) { + writeFailure(cur); + } + writeToFile("\n"); + cur = cur->next_; + } +} + +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()); + writeToFile(buf.asCharString()); + writeToFile("\n"); +} + +void JUnitTestOutput::writeFileEnding() +{ + writeToFile("\n"); + writeToFile("\n"); + writeToFile(""); +} + +void JUnitTestOutput::writeTestGroupToFile() +{ + openFileForWrite(createFileName(impl_->results_.group_)); + writeXmlHeader(); + writeTestSuiteSummery(); + writeProperties(); + writeTestCases(); + writeFileEnding(); + closeFile(); +} + +void JUnitTestOutput::verbose() +{ +} + +void JUnitTestOutput::printBuffer(const char*) +{ +} + +void JUnitTestOutput::print(const char*) +{ +} + +void JUnitTestOutput::print(long) +{ +} + +void JUnitTestOutput::print(const TestFailure& failure) +{ + if (impl_->results_.tail_->failure_ == 0) { + impl_->results_.failureCount_++; + impl_->results_.tail_->failure_ = new TestFailure(failure); + } +} + +void JUnitTestOutput::printTestRun(int /*number*/, int /*total*/) +{ +} + +void JUnitTestOutput::flush() +{ +} + +void JUnitTestOutput::openFileForWrite(const SimpleString& fileName) +{ + impl_->file_ = PlatformSpecificFOpen(fileName.asCharString(), "w"); +} + +void JUnitTestOutput::writeToFile(const SimpleString& buffer) +{ + PlatformSpecificFPuts(buffer.asCharString(), impl_->file_); +} + +void JUnitTestOutput::closeFile() +{ + PlatformSpecificFClose(impl_->file_); +} diff --git a/src/CppUTest/MemoryLeakDetector.cpp b/src/CppUTest/MemoryLeakDetector.cpp index 075d45187..a5d66eaad 100644 --- a/src/CppUTest/MemoryLeakDetector.cpp +++ b/src/CppUTest/MemoryLeakDetector.cpp @@ -1,621 +1,621 @@ -/* - * 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 "CppUTest/TestMemoryAllocator.h" -#include "CppUTest/PlatformSpecificFunctions.h" - -#define UNKNOWN ((char*)("")) - -SimpleStringBuffer::SimpleStringBuffer() : - positions_filled_(0), write_limit_(SIMPLE_STRING_BUFFER_LEN-1) -{ -} - -void SimpleStringBuffer::clear() -{ - positions_filled_ = 0; - buffer_[0] = '\0'; -} - -void SimpleStringBuffer::add(const char* format, ...) -{ - int count = 0; - 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); - if (count > 0) positions_filled_ += (size_t) count; - if (positions_filled_ > write_limit_) positions_filled_ = write_limit_; - va_end(arguments); -} - -char* SimpleStringBuffer::toString() -{ - return buffer_; -} - -void SimpleStringBuffer::setWriteLimit(size_t write_limit) -{ - write_limit_ = write_limit; - if (write_limit_ > SIMPLE_STRING_BUFFER_LEN-1) - write_limit_ = SIMPLE_STRING_BUFFER_LEN-1; -} -void SimpleStringBuffer::resetWriteLimit() -{ - write_limit_ = SIMPLE_STRING_BUFFER_LEN-1; -} - -bool SimpleStringBuffer::reachedItsCapacity() -{ - return positions_filled_ >= write_limit_; -} - -//////////////////////// - -#define MEM_LEAK_TOO_MUCH "\netc etc etc etc. !!!! Too much memory leaks to report. Bailing out\n" -#define MEM_LEAK_FOOTER "Total number of leaks: " -#define MEM_LEAK_ADDITION_MALLOC_WARNING "NOTE:\n" \ - "\tMemory leak reports about malloc and free can be caused by allocating using the cpputest version of malloc,\n" \ - "\tbut deallocate using the standard free.\n" \ - "\tIf this is the case, check whether your malloc/free replacements are working (#define malloc cpputest_malloc etc).\n" - -MemoryLeakOutputStringBuffer::MemoryLeakOutputStringBuffer() - : total_leaks_(0), giveWarningOnUsingMalloc_(false) -{ -} - -void MemoryLeakOutputStringBuffer::addAllocationLocation(const char* allocationFile, int 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()); -} - -void MemoryLeakOutputStringBuffer::addDeallocationLocation(const char* freeFile, int freeLineNumber, TestMemoryAllocator* allocator) -{ - outputBuffer_.add(" deallocated at file: %s line: %d type: %s\n", freeFile, freeLineNumber, allocator->free_name()); -} - -void MemoryLeakOutputStringBuffer::addNoMemoryLeaksMessage() -{ - outputBuffer_.add("No memory leaks were detected."); -} - -void MemoryLeakOutputStringBuffer::startMemoryLeakReporting() -{ - giveWarningOnUsingMalloc_ = false; - total_leaks_ = 0; - - size_t memory_leak_normal_footer_size = sizeof(MEM_LEAK_FOOTER) + 10 + sizeof(MEM_LEAK_TOO_MUCH); /* the number of leaks */ - size_t memory_leak_foot_size_with_malloc_warning = memory_leak_normal_footer_size + sizeof(MEM_LEAK_ADDITION_MALLOC_WARNING); - - outputBuffer_.setWriteLimit(SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN - memory_leak_foot_size_with_malloc_warning); -} - -void MemoryLeakOutputStringBuffer::reportMemoryLeak(MemoryLeakDetectorNode* leak) -{ - if (total_leaks_ == 0) { - addMemoryLeakHeader(); - } - - total_leaks_++; - outputBuffer_.add("Alloc num (%u) Leak size: %lu Allocated at: %s and line: %d. Type: \"%s\"\n\t Memory: <%p> Content: \"%.15s\"\n", - leak->number_, (unsigned long) leak->size_, leak->file_, leak->line_, leak->allocator_->alloc_name(), leak->memory_, leak->memory_); - - if (PlatformSpecificStrCmp(leak->allocator_->alloc_name(), "malloc") == 0) - giveWarningOnUsingMalloc_ = true; -} - -void MemoryLeakOutputStringBuffer::stopMemoryLeakReporting() -{ - if (total_leaks_ == 0) { - addNoMemoryLeaksMessage(); - return; - } - - bool buffer_reached_its_capacity = outputBuffer_.reachedItsCapacity(); - outputBuffer_.resetWriteLimit(); - - if (buffer_reached_its_capacity) - addErrorMessageForTooMuchLeaks(); - - addMemoryLeakFooter(total_leaks_); - - if (giveWarningOnUsingMalloc_) - addWarningForUsingMalloc(); - -} - -void MemoryLeakOutputStringBuffer::addMemoryLeakHeader() -{ - outputBuffer_.add("Memory leak(s) found.\n"); -} - -void MemoryLeakOutputStringBuffer::addErrorMessageForTooMuchLeaks() -{ - outputBuffer_.add(MEM_LEAK_TOO_MUCH); -} - -void MemoryLeakOutputStringBuffer::addMemoryLeakFooter(int amountOfLeaks) -{ - outputBuffer_.add("%s %d\n", MEM_LEAK_FOOTER, amountOfLeaks); -} - -void MemoryLeakOutputStringBuffer::addWarningForUsingMalloc() -{ - outputBuffer_.add(MEM_LEAK_ADDITION_MALLOC_WARNING); -} - -void MemoryLeakOutputStringBuffer::reportDeallocateNonAllocatedMemoryFailure(const char* freeFile, int 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) -{ - 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) -{ - 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, - TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) -{ - outputBuffer_.add("%s", message); - addAllocationLocation(allocFile, allocLine, allocSize, allocAllocator); - addDeallocationLocation(freeFile, freeLine, freeAllocator); - reporter->fail(toString()); -} - - -char* MemoryLeakOutputStringBuffer::toString() -{ - return outputBuffer_.toString(); -} - -void MemoryLeakOutputStringBuffer::clear() -{ - outputBuffer_.clear(); -} - -//////////////////////// - -void MemoryLeakDetectorNode::init(char* memory, unsigned number, size_t size, TestMemoryAllocator* allocator, MemLeakPeriod period, const char* file, int line) -{ - number_ = number; - memory_ = memory; - size_ = size; - allocator_ = allocator; - period_ = period; - file_ = file; - line_ = line; -} - -/////////////////////// - -bool MemoryLeakDetectorList::isInPeriod(MemoryLeakDetectorNode* node, MemLeakPeriod period) -{ - return period == mem_leak_period_all || node->period_ == period || (node->period_ != mem_leak_period_disabled && period == mem_leak_period_enabled); -} - -void MemoryLeakDetectorList::clearAllAccounting(MemLeakPeriod period) -{ - MemoryLeakDetectorNode* cur = head_; - MemoryLeakDetectorNode* prev = 0; - - while (cur) { - if (isInPeriod(cur, period)) { - if (prev) { - prev->next_ = cur->next_; - cur = prev; - } - else { - head_ = cur->next_; - cur = head_; - continue; - } - } - prev = cur; - cur = cur->next_; - } -} - -void MemoryLeakDetectorList::addNewNode(MemoryLeakDetectorNode* node) -{ - node->next_ = head_; - head_ = node; -} - -MemoryLeakDetectorNode* MemoryLeakDetectorList::removeNode(char* memory) -{ - MemoryLeakDetectorNode* cur = head_; - MemoryLeakDetectorNode* prev = 0; - while (cur) { - if (cur->memory_ == memory) { - if (prev) { - prev->next_ = cur->next_; - return cur; - } - else { - head_ = cur->next_; - return cur; - } - } - prev = cur; - cur = cur->next_; - } - return 0; -} - -MemoryLeakDetectorNode* MemoryLeakDetectorList::retrieveNode(char* memory) -{ - MemoryLeakDetectorNode* cur = head_; - while (cur) { - if (cur->memory_ == memory) - return cur; - cur = cur->next_; - } - return NULL; -} - -MemoryLeakDetectorNode* MemoryLeakDetectorList::getLeakFrom(MemoryLeakDetectorNode* node, MemLeakPeriod period) -{ - for (MemoryLeakDetectorNode* cur = node; cur; cur = cur->next_) - if (isInPeriod(cur, period)) return cur; - return 0; -} - -MemoryLeakDetectorNode* MemoryLeakDetectorList::getFirstLeak(MemLeakPeriod period) -{ - return getLeakFrom(head_, period); -} - -MemoryLeakDetectorNode* MemoryLeakDetectorList::getNextLeak(MemoryLeakDetectorNode* node, MemLeakPeriod period) -{ - return getLeakFrom(node->next_, period); -} - -int MemoryLeakDetectorList::getTotalLeaks(MemLeakPeriod period) -{ - int total_leaks = 0; - for (MemoryLeakDetectorNode* node = head_; node; node = node->next_) { - if (isInPeriod(node, period)) total_leaks++; - } - return total_leaks; -} - -bool MemoryLeakDetectorList::hasLeaks(MemLeakPeriod period) -{ - for (MemoryLeakDetectorNode* node = head_; node; node = node->next_) - if (isInPeriod(node, period)) return true; - return false; -} - -///////////////////////////////////////////////////////////// - -unsigned long MemoryLeakDetectorTable::hash(char* memory) -{ - return (unsigned long)((size_t)memory % hash_prime); -} - -void MemoryLeakDetectorTable::clearAllAccounting(MemLeakPeriod period) -{ - for (int i = 0; i < hash_prime; i++) - table_[i].clearAllAccounting(period); -} - -void MemoryLeakDetectorTable::addNewNode(MemoryLeakDetectorNode* node) -{ - table_[hash(node->memory_)].addNewNode(node); -} - -MemoryLeakDetectorNode* MemoryLeakDetectorTable::removeNode(char* memory) -{ - return table_[hash(memory)].removeNode(memory); -} - -MemoryLeakDetectorNode* MemoryLeakDetectorTable::retrieveNode(char* memory) -{ - return table_[hash(memory)].retrieveNode(memory); -} - -bool MemoryLeakDetectorTable::hasLeaks(MemLeakPeriod period) -{ - for (int i = 0; i < hash_prime; i++) - if (table_[i].hasLeaks(period)) return true; - return false; -} - -int MemoryLeakDetectorTable::getTotalLeaks(MemLeakPeriod period) -{ - int total_leaks = 0; - for (int i = 0; i < hash_prime; i++) - total_leaks += table_[i].getTotalLeaks(period); - return total_leaks; -} - -MemoryLeakDetectorNode* MemoryLeakDetectorTable::getFirstLeak(MemLeakPeriod period) -{ - for (int i = 0; i < hash_prime; i++) { - MemoryLeakDetectorNode* node = table_[i].getFirstLeak(period); - if (node) return node; - } - return 0; -} - -MemoryLeakDetectorNode* MemoryLeakDetectorTable::getNextLeak(MemoryLeakDetectorNode* leak, MemLeakPeriod period) -{ - unsigned long i = hash(leak->memory_); - MemoryLeakDetectorNode* node = table_[i].getNextLeak(leak, period); - if (node) return node; - - for (++i; i < hash_prime; i++) { - node = table_[i].getFirstLeak(period); - if (node) return node; - } - return 0; -} - -///////////////////////////////////////////////////////////// - -MemoryLeakDetector::MemoryLeakDetector(MemoryLeakFailure* reporter) -{ - doAllocationTypeChecking_ = true; - allocationSequenceNumber_ = 1; - current_period_ = mem_leak_period_disabled; - reporter_ = reporter; - outputBuffer_ = MemoryLeakOutputStringBuffer(); - memoryTable_ = MemoryLeakDetectorTable(); -} - -void MemoryLeakDetector::clearAllAccounting(MemLeakPeriod period) -{ - memoryTable_.clearAllAccounting(period); -} - -void MemoryLeakDetector::startChecking() -{ - outputBuffer_.clear(); - current_period_ = mem_leak_period_checking; -} - -void MemoryLeakDetector::stopChecking() -{ - current_period_ = mem_leak_period_enabled; -} - -void MemoryLeakDetector::enable() -{ - current_period_ = mem_leak_period_enabled; -} - -void MemoryLeakDetector::disable() -{ - current_period_ = mem_leak_period_disabled; -} - -void MemoryLeakDetector::disableAllocationTypeChecking() -{ - doAllocationTypeChecking_ = false; -} - -void MemoryLeakDetector::enableAllocationTypeChecking() -{ - doAllocationTypeChecking_ = true; -} - -unsigned MemoryLeakDetector::getCurrentAllocationNumber() -{ - return allocationSequenceNumber_; -} - -static size_t calculateVoidPointerAlignedSize(size_t size) -{ - return (sizeof(void*) - (size % sizeof(void*))) + size; -} - -size_t MemoryLeakDetector::sizeOfMemoryWithCorruptionInfo(size_t size) -{ - return calculateVoidPointerAlignedSize(size + memory_corruption_buffer_size); -} - -MemoryLeakDetectorNode* MemoryLeakDetector::getNodeFromMemoryPointer(char* memory, size_t memory_size) -{ - 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) -{ - node->init(new_memory, allocationSequenceNumber_++, size, allocator, current_period_, 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* new_memory = reallocateMemoryWithAccountingInformation(allocator, memory, size, file, line, allocatNodesSeperately); - if (new_memory == NULL) return NULL; - - MemoryLeakDetectorNode *node = createMemoryLeakAccountingInformation(allocator, size, new_memory, allocatNodesSeperately); - storeLeakInformation(node, new_memory, size, allocator, file, line); - return node->memory_; -} - -void MemoryLeakDetector::invalidateMemory(char* memory) -{ - MemoryLeakDetectorNode* node = memoryTable_.retrieveNode(memory); - if (node) - PlatformSpecificMemset(memory, 0xCD, node->size_); -} - -void MemoryLeakDetector::addMemoryCorruptionInformation(char* memory) -{ - memory[0] = 'B'; - memory[1] = 'A'; - memory[2] = 'S'; -} - -bool MemoryLeakDetector::validMemoryCorruptionInformation(char* memory) -{ - return memory[0] == 'B' && memory[1] == 'A' && memory[2] == 'S'; -} - -bool MemoryLeakDetector::matchingAllocation(TestMemoryAllocator *alloc_allocator, TestMemoryAllocator *free_allocator) -{ - if (alloc_allocator == free_allocator) return true; - if (!doAllocationTypeChecking_) return true; - return free_allocator->isOfEqualType(alloc_allocator); -} - -void MemoryLeakDetector::checkForCorruption(MemoryLeakDetectorNode* node, const char* file, int line, TestMemoryAllocator* allocator, bool allocateNodesSeperately) -{ - if (!matchingAllocation(node->allocator_, allocator)) - outputBuffer_.reportAllocationDeallocationMismatchFailure(node, file, line, allocator, reporter_); - else if (!validMemoryCorruptionInformation(node->memory_ + node->size_)) - outputBuffer_.reportMemoryCorruptionFailure(node, file, line, allocator, reporter_); - else if (allocateNodesSeperately) - allocator->freeMemoryLeakNode((char*) node); -} - -char* MemoryLeakDetector::allocMemory(TestMemoryAllocator* allocator, size_t size, bool allocatNodesSeperately) -{ - return allocMemory(allocator, size, UNKNOWN, 0, allocatNodesSeperately); -} - -char* MemoryLeakDetector::allocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, size_t size, const char* file, int 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) -{ - if (allocatNodesSeperately) return (char*) PlatformSpecificRealloc(memory, sizeOfMemoryWithCorruptionInfo(size)); - else return (char*) PlatformSpecificRealloc(memory, sizeOfMemoryWithCorruptionInfo(size) + sizeof(MemoryLeakDetectorNode)); -} - -MemoryLeakDetectorNode* MemoryLeakDetector::createMemoryLeakAccountingInformation(TestMemoryAllocator* allocator, size_t size, char* memory, bool allocatNodesSeperately) -{ - if (allocatNodesSeperately) return (MemoryLeakDetectorNode*) (void*) allocator->allocMemoryLeakNode(sizeof(MemoryLeakDetectorNode)); - else return getNodeFromMemoryPointer(memory, size); -} - -char* MemoryLeakDetector::allocMemory(TestMemoryAllocator* allocator, size_t size, const char* file, int line, bool allocatNodesSeperately) -{ - /* 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 - * without the memory leak detector ever noticing it! - * So, for malloc, we'll allocate the memory separately so we can detect this and give a proper error. - */ - - char* memory = allocateMemoryWithAccountingInformation(allocator, size, file, line, allocatNodesSeperately); - if (memory == NULL) return NULL; - MemoryLeakDetectorNode* node = createMemoryLeakAccountingInformation(allocator, size, memory, allocatNodesSeperately); - - storeLeakInformation(node, memory, size, allocator, file, line); - return node->memory_; -} - -void MemoryLeakDetector::removeMemoryLeakInformationWithoutCheckingOrDeallocatingTheMemoryButDeallocatingTheAccountInformation(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately) -{ - MemoryLeakDetectorNode* node = memoryTable_.removeNode((char*) memory); - if (allocatNodesSeperately) allocator->freeMemoryLeakNode( (char*) node); -} - -void MemoryLeakDetector::deallocMemory(TestMemoryAllocator* allocator, void* memory, const char* file, int line, bool allocatNodesSeperately) -{ - if (memory == 0) return; - - MemoryLeakDetectorNode* node = memoryTable_.removeNode((char*) memory); - if (node == NULL) { - outputBuffer_.reportDeallocateNonAllocatedMemoryFailure(file, line, allocator, reporter_); - return; - } - if (!allocator->hasBeenDestroyed()) { - checkForCorruption(node, file, line, allocator, allocatNodesSeperately); - allocator->free_memory((char*) memory, file, line); - } -} - -void MemoryLeakDetector::deallocMemory(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately) -{ - deallocMemory(allocator, (char*) memory, UNKNOWN, 0, allocatNodesSeperately); -} - -char* MemoryLeakDetector::reallocMemory(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately) -{ - if (memory) { - MemoryLeakDetectorNode* node = memoryTable_.removeNode(memory); - if (node == NULL) { - outputBuffer_.reportDeallocateNonAllocatedMemoryFailure(file, line, allocator, reporter_); - return NULL; - } - checkForCorruption(node, file, line, allocator, allocatNodesSeperately); - } - return reallocateMemoryAndLeakInformation(allocator, memory, size, file, line, allocatNodesSeperately); -} - -void MemoryLeakDetector::ConstructMemoryLeakReport(MemLeakPeriod period) -{ - MemoryLeakDetectorNode* leak = memoryTable_.getFirstLeak(period); - - outputBuffer_.startMemoryLeakReporting(); - - while (leak) { - outputBuffer_.reportMemoryLeak(leak); - leak = memoryTable_.getNextLeak(leak, period); - } - - outputBuffer_.stopMemoryLeakReporting(); -} - -const char* MemoryLeakDetector::report(MemLeakPeriod period) -{ - outputBuffer_.clear(); - ConstructMemoryLeakReport(period); - - return outputBuffer_.toString(); -} - -void MemoryLeakDetector::markCheckingPeriodLeaksAsNonCheckingPeriod() -{ - MemoryLeakDetectorNode* leak = memoryTable_.getFirstLeak(mem_leak_period_checking); - while (leak) { - if (leak->period_ == mem_leak_period_checking) leak->period_ = mem_leak_period_enabled; - leak = memoryTable_.getNextLeak(leak, mem_leak_period_checking); - } -} - -int MemoryLeakDetector::totalMemoryLeaks(MemLeakPeriod period) -{ - return memoryTable_.getTotalLeaks(period); -} +/* + * 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 "CppUTest/TestMemoryAllocator.h" +#include "CppUTest/PlatformSpecificFunctions.h" + +#define UNKNOWN ((char*)("")) + +SimpleStringBuffer::SimpleStringBuffer() : + positions_filled_(0), write_limit_(SIMPLE_STRING_BUFFER_LEN-1) +{ +} + +void SimpleStringBuffer::clear() +{ + positions_filled_ = 0; + buffer_[0] = '\0'; +} + +void SimpleStringBuffer::add(const char* format, ...) +{ + int count = 0; + 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); + if (count > 0) positions_filled_ += (size_t) count; + if (positions_filled_ > write_limit_) positions_filled_ = write_limit_; + va_end(arguments); +} + +char* SimpleStringBuffer::toString() +{ + return buffer_; +} + +void SimpleStringBuffer::setWriteLimit(size_t write_limit) +{ + write_limit_ = write_limit; + if (write_limit_ > SIMPLE_STRING_BUFFER_LEN-1) + write_limit_ = SIMPLE_STRING_BUFFER_LEN-1; +} +void SimpleStringBuffer::resetWriteLimit() +{ + write_limit_ = SIMPLE_STRING_BUFFER_LEN-1; +} + +bool SimpleStringBuffer::reachedItsCapacity() +{ + return positions_filled_ >= write_limit_; +} + +//////////////////////// + +#define MEM_LEAK_TOO_MUCH "\netc etc etc etc. !!!! Too much memory leaks to report. Bailing out\n" +#define MEM_LEAK_FOOTER "Total number of leaks: " +#define MEM_LEAK_ADDITION_MALLOC_WARNING "NOTE:\n" \ + "\tMemory leak reports about malloc and free can be caused by allocating using the cpputest version of malloc,\n" \ + "\tbut deallocate using the standard free.\n" \ + "\tIf this is the case, check whether your malloc/free replacements are working (#define malloc cpputest_malloc etc).\n" + +MemoryLeakOutputStringBuffer::MemoryLeakOutputStringBuffer() + : total_leaks_(0), giveWarningOnUsingMalloc_(false) +{ +} + +void MemoryLeakOutputStringBuffer::addAllocationLocation(const char* allocationFile, int 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()); +} + +void MemoryLeakOutputStringBuffer::addDeallocationLocation(const char* freeFile, int freeLineNumber, TestMemoryAllocator* allocator) +{ + outputBuffer_.add(" deallocated at file: %s line: %d type: %s\n", freeFile, freeLineNumber, allocator->free_name()); +} + +void MemoryLeakOutputStringBuffer::addNoMemoryLeaksMessage() +{ + outputBuffer_.add("No memory leaks were detected."); +} + +void MemoryLeakOutputStringBuffer::startMemoryLeakReporting() +{ + giveWarningOnUsingMalloc_ = false; + total_leaks_ = 0; + + size_t memory_leak_normal_footer_size = sizeof(MEM_LEAK_FOOTER) + 10 + sizeof(MEM_LEAK_TOO_MUCH); /* the number of leaks */ + size_t memory_leak_foot_size_with_malloc_warning = memory_leak_normal_footer_size + sizeof(MEM_LEAK_ADDITION_MALLOC_WARNING); + + outputBuffer_.setWriteLimit(SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN - memory_leak_foot_size_with_malloc_warning); +} + +void MemoryLeakOutputStringBuffer::reportMemoryLeak(MemoryLeakDetectorNode* leak) +{ + if (total_leaks_ == 0) { + addMemoryLeakHeader(); + } + + total_leaks_++; + outputBuffer_.add("Alloc num (%u) Leak size: %lu Allocated at: %s and line: %d. Type: \"%s\"\n\t Memory: <%p> Content: \"%.15s\"\n", + leak->number_, (unsigned long) leak->size_, leak->file_, leak->line_, leak->allocator_->alloc_name(), leak->memory_, leak->memory_); + + if (PlatformSpecificStrCmp(leak->allocator_->alloc_name(), "malloc") == 0) + giveWarningOnUsingMalloc_ = true; +} + +void MemoryLeakOutputStringBuffer::stopMemoryLeakReporting() +{ + if (total_leaks_ == 0) { + addNoMemoryLeaksMessage(); + return; + } + + bool buffer_reached_its_capacity = outputBuffer_.reachedItsCapacity(); + outputBuffer_.resetWriteLimit(); + + if (buffer_reached_its_capacity) + addErrorMessageForTooMuchLeaks(); + + addMemoryLeakFooter(total_leaks_); + + if (giveWarningOnUsingMalloc_) + addWarningForUsingMalloc(); + +} + +void MemoryLeakOutputStringBuffer::addMemoryLeakHeader() +{ + outputBuffer_.add("Memory leak(s) found.\n"); +} + +void MemoryLeakOutputStringBuffer::addErrorMessageForTooMuchLeaks() +{ + outputBuffer_.add(MEM_LEAK_TOO_MUCH); +} + +void MemoryLeakOutputStringBuffer::addMemoryLeakFooter(int amountOfLeaks) +{ + outputBuffer_.add("%s %d\n", MEM_LEAK_FOOTER, amountOfLeaks); +} + +void MemoryLeakOutputStringBuffer::addWarningForUsingMalloc() +{ + outputBuffer_.add(MEM_LEAK_ADDITION_MALLOC_WARNING); +} + +void MemoryLeakOutputStringBuffer::reportDeallocateNonAllocatedMemoryFailure(const char* freeFile, int 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) +{ + 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) +{ + 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, + TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) +{ + outputBuffer_.add("%s", message); + addAllocationLocation(allocFile, allocLine, allocSize, allocAllocator); + addDeallocationLocation(freeFile, freeLine, freeAllocator); + reporter->fail(toString()); +} + + +char* MemoryLeakOutputStringBuffer::toString() +{ + return outputBuffer_.toString(); +} + +void MemoryLeakOutputStringBuffer::clear() +{ + outputBuffer_.clear(); +} + +//////////////////////// + +void MemoryLeakDetectorNode::init(char* memory, unsigned number, size_t size, TestMemoryAllocator* allocator, MemLeakPeriod period, const char* file, int line) +{ + number_ = number; + memory_ = memory; + size_ = size; + allocator_ = allocator; + period_ = period; + file_ = file; + line_ = line; +} + +/////////////////////// + +bool MemoryLeakDetectorList::isInPeriod(MemoryLeakDetectorNode* node, MemLeakPeriod period) +{ + return period == mem_leak_period_all || node->period_ == period || (node->period_ != mem_leak_period_disabled && period == mem_leak_period_enabled); +} + +void MemoryLeakDetectorList::clearAllAccounting(MemLeakPeriod period) +{ + MemoryLeakDetectorNode* cur = head_; + MemoryLeakDetectorNode* prev = 0; + + while (cur) { + if (isInPeriod(cur, period)) { + if (prev) { + prev->next_ = cur->next_; + cur = prev; + } + else { + head_ = cur->next_; + cur = head_; + continue; + } + } + prev = cur; + cur = cur->next_; + } +} + +void MemoryLeakDetectorList::addNewNode(MemoryLeakDetectorNode* node) +{ + node->next_ = head_; + head_ = node; +} + +MemoryLeakDetectorNode* MemoryLeakDetectorList::removeNode(char* memory) +{ + MemoryLeakDetectorNode* cur = head_; + MemoryLeakDetectorNode* prev = 0; + while (cur) { + if (cur->memory_ == memory) { + if (prev) { + prev->next_ = cur->next_; + return cur; + } + else { + head_ = cur->next_; + return cur; + } + } + prev = cur; + cur = cur->next_; + } + return 0; +} + +MemoryLeakDetectorNode* MemoryLeakDetectorList::retrieveNode(char* memory) +{ + MemoryLeakDetectorNode* cur = head_; + while (cur) { + if (cur->memory_ == memory) + return cur; + cur = cur->next_; + } + return NULL; +} + +MemoryLeakDetectorNode* MemoryLeakDetectorList::getLeakFrom(MemoryLeakDetectorNode* node, MemLeakPeriod period) +{ + for (MemoryLeakDetectorNode* cur = node; cur; cur = cur->next_) + if (isInPeriod(cur, period)) return cur; + return 0; +} + +MemoryLeakDetectorNode* MemoryLeakDetectorList::getFirstLeak(MemLeakPeriod period) +{ + return getLeakFrom(head_, period); +} + +MemoryLeakDetectorNode* MemoryLeakDetectorList::getNextLeak(MemoryLeakDetectorNode* node, MemLeakPeriod period) +{ + return getLeakFrom(node->next_, period); +} + +int MemoryLeakDetectorList::getTotalLeaks(MemLeakPeriod period) +{ + int total_leaks = 0; + for (MemoryLeakDetectorNode* node = head_; node; node = node->next_) { + if (isInPeriod(node, period)) total_leaks++; + } + return total_leaks; +} + +bool MemoryLeakDetectorList::hasLeaks(MemLeakPeriod period) +{ + for (MemoryLeakDetectorNode* node = head_; node; node = node->next_) + if (isInPeriod(node, period)) return true; + return false; +} + +///////////////////////////////////////////////////////////// + +unsigned long MemoryLeakDetectorTable::hash(char* memory) +{ + return (unsigned long)((size_t)memory % hash_prime); +} + +void MemoryLeakDetectorTable::clearAllAccounting(MemLeakPeriod period) +{ + for (int i = 0; i < hash_prime; i++) + table_[i].clearAllAccounting(period); +} + +void MemoryLeakDetectorTable::addNewNode(MemoryLeakDetectorNode* node) +{ + table_[hash(node->memory_)].addNewNode(node); +} + +MemoryLeakDetectorNode* MemoryLeakDetectorTable::removeNode(char* memory) +{ + return table_[hash(memory)].removeNode(memory); +} + +MemoryLeakDetectorNode* MemoryLeakDetectorTable::retrieveNode(char* memory) +{ + return table_[hash(memory)].retrieveNode(memory); +} + +bool MemoryLeakDetectorTable::hasLeaks(MemLeakPeriod period) +{ + for (int i = 0; i < hash_prime; i++) + if (table_[i].hasLeaks(period)) return true; + return false; +} + +int MemoryLeakDetectorTable::getTotalLeaks(MemLeakPeriod period) +{ + int total_leaks = 0; + for (int i = 0; i < hash_prime; i++) + total_leaks += table_[i].getTotalLeaks(period); + return total_leaks; +} + +MemoryLeakDetectorNode* MemoryLeakDetectorTable::getFirstLeak(MemLeakPeriod period) +{ + for (int i = 0; i < hash_prime; i++) { + MemoryLeakDetectorNode* node = table_[i].getFirstLeak(period); + if (node) return node; + } + return 0; +} + +MemoryLeakDetectorNode* MemoryLeakDetectorTable::getNextLeak(MemoryLeakDetectorNode* leak, MemLeakPeriod period) +{ + unsigned long i = hash(leak->memory_); + MemoryLeakDetectorNode* node = table_[i].getNextLeak(leak, period); + if (node) return node; + + for (++i; i < hash_prime; i++) { + node = table_[i].getFirstLeak(period); + if (node) return node; + } + return 0; +} + +///////////////////////////////////////////////////////////// + +MemoryLeakDetector::MemoryLeakDetector(MemoryLeakFailure* reporter) +{ + doAllocationTypeChecking_ = true; + allocationSequenceNumber_ = 1; + current_period_ = mem_leak_period_disabled; + reporter_ = reporter; + outputBuffer_ = MemoryLeakOutputStringBuffer(); + memoryTable_ = MemoryLeakDetectorTable(); +} + +void MemoryLeakDetector::clearAllAccounting(MemLeakPeriod period) +{ + memoryTable_.clearAllAccounting(period); +} + +void MemoryLeakDetector::startChecking() +{ + outputBuffer_.clear(); + current_period_ = mem_leak_period_checking; +} + +void MemoryLeakDetector::stopChecking() +{ + current_period_ = mem_leak_period_enabled; +} + +void MemoryLeakDetector::enable() +{ + current_period_ = mem_leak_period_enabled; +} + +void MemoryLeakDetector::disable() +{ + current_period_ = mem_leak_period_disabled; +} + +void MemoryLeakDetector::disableAllocationTypeChecking() +{ + doAllocationTypeChecking_ = false; +} + +void MemoryLeakDetector::enableAllocationTypeChecking() +{ + doAllocationTypeChecking_ = true; +} + +unsigned MemoryLeakDetector::getCurrentAllocationNumber() +{ + return allocationSequenceNumber_; +} + +static size_t calculateVoidPointerAlignedSize(size_t size) +{ + return (sizeof(void*) - (size % sizeof(void*))) + size; +} + +size_t MemoryLeakDetector::sizeOfMemoryWithCorruptionInfo(size_t size) +{ + return calculateVoidPointerAlignedSize(size + memory_corruption_buffer_size); +} + +MemoryLeakDetectorNode* MemoryLeakDetector::getNodeFromMemoryPointer(char* memory, size_t memory_size) +{ + 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) +{ + node->init(new_memory, allocationSequenceNumber_++, size, allocator, current_period_, 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* new_memory = reallocateMemoryWithAccountingInformation(allocator, memory, size, file, line, allocatNodesSeperately); + if (new_memory == NULL) return NULL; + + MemoryLeakDetectorNode *node = createMemoryLeakAccountingInformation(allocator, size, new_memory, allocatNodesSeperately); + storeLeakInformation(node, new_memory, size, allocator, file, line); + return node->memory_; +} + +void MemoryLeakDetector::invalidateMemory(char* memory) +{ + MemoryLeakDetectorNode* node = memoryTable_.retrieveNode(memory); + if (node) + PlatformSpecificMemset(memory, 0xCD, node->size_); +} + +void MemoryLeakDetector::addMemoryCorruptionInformation(char* memory) +{ + memory[0] = 'B'; + memory[1] = 'A'; + memory[2] = 'S'; +} + +bool MemoryLeakDetector::validMemoryCorruptionInformation(char* memory) +{ + return memory[0] == 'B' && memory[1] == 'A' && memory[2] == 'S'; +} + +bool MemoryLeakDetector::matchingAllocation(TestMemoryAllocator *alloc_allocator, TestMemoryAllocator *free_allocator) +{ + if (alloc_allocator == free_allocator) return true; + if (!doAllocationTypeChecking_) return true; + return free_allocator->isOfEqualType(alloc_allocator); +} + +void MemoryLeakDetector::checkForCorruption(MemoryLeakDetectorNode* node, const char* file, int line, TestMemoryAllocator* allocator, bool allocateNodesSeperately) +{ + if (!matchingAllocation(node->allocator_, allocator)) + outputBuffer_.reportAllocationDeallocationMismatchFailure(node, file, line, allocator, reporter_); + else if (!validMemoryCorruptionInformation(node->memory_ + node->size_)) + outputBuffer_.reportMemoryCorruptionFailure(node, file, line, allocator, reporter_); + else if (allocateNodesSeperately) + allocator->freeMemoryLeakNode((char*) node); +} + +char* MemoryLeakDetector::allocMemory(TestMemoryAllocator* allocator, size_t size, bool allocatNodesSeperately) +{ + return allocMemory(allocator, size, UNKNOWN, 0, allocatNodesSeperately); +} + +char* MemoryLeakDetector::allocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, size_t size, const char* file, int 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) +{ + if (allocatNodesSeperately) return (char*) PlatformSpecificRealloc(memory, sizeOfMemoryWithCorruptionInfo(size)); + else return (char*) PlatformSpecificRealloc(memory, sizeOfMemoryWithCorruptionInfo(size) + sizeof(MemoryLeakDetectorNode)); +} + +MemoryLeakDetectorNode* MemoryLeakDetector::createMemoryLeakAccountingInformation(TestMemoryAllocator* allocator, size_t size, char* memory, bool allocatNodesSeperately) +{ + if (allocatNodesSeperately) return (MemoryLeakDetectorNode*) (void*) allocator->allocMemoryLeakNode(sizeof(MemoryLeakDetectorNode)); + else return getNodeFromMemoryPointer(memory, size); +} + +char* MemoryLeakDetector::allocMemory(TestMemoryAllocator* allocator, size_t size, const char* file, int line, bool allocatNodesSeperately) +{ + /* 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 + * without the memory leak detector ever noticing it! + * So, for malloc, we'll allocate the memory separately so we can detect this and give a proper error. + */ + + char* memory = allocateMemoryWithAccountingInformation(allocator, size, file, line, allocatNodesSeperately); + if (memory == NULL) return NULL; + MemoryLeakDetectorNode* node = createMemoryLeakAccountingInformation(allocator, size, memory, allocatNodesSeperately); + + storeLeakInformation(node, memory, size, allocator, file, line); + return node->memory_; +} + +void MemoryLeakDetector::removeMemoryLeakInformationWithoutCheckingOrDeallocatingTheMemoryButDeallocatingTheAccountInformation(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately) +{ + MemoryLeakDetectorNode* node = memoryTable_.removeNode((char*) memory); + if (allocatNodesSeperately) allocator->freeMemoryLeakNode( (char*) node); +} + +void MemoryLeakDetector::deallocMemory(TestMemoryAllocator* allocator, void* memory, const char* file, int line, bool allocatNodesSeperately) +{ + if (memory == 0) return; + + MemoryLeakDetectorNode* node = memoryTable_.removeNode((char*) memory); + if (node == NULL) { + outputBuffer_.reportDeallocateNonAllocatedMemoryFailure(file, line, allocator, reporter_); + return; + } + if (!allocator->hasBeenDestroyed()) { + checkForCorruption(node, file, line, allocator, allocatNodesSeperately); + allocator->free_memory((char*) memory, file, line); + } +} + +void MemoryLeakDetector::deallocMemory(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately) +{ + deallocMemory(allocator, (char*) memory, UNKNOWN, 0, allocatNodesSeperately); +} + +char* MemoryLeakDetector::reallocMemory(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately) +{ + if (memory) { + MemoryLeakDetectorNode* node = memoryTable_.removeNode(memory); + if (node == NULL) { + outputBuffer_.reportDeallocateNonAllocatedMemoryFailure(file, line, allocator, reporter_); + return NULL; + } + checkForCorruption(node, file, line, allocator, allocatNodesSeperately); + } + return reallocateMemoryAndLeakInformation(allocator, memory, size, file, line, allocatNodesSeperately); +} + +void MemoryLeakDetector::ConstructMemoryLeakReport(MemLeakPeriod period) +{ + MemoryLeakDetectorNode* leak = memoryTable_.getFirstLeak(period); + + outputBuffer_.startMemoryLeakReporting(); + + while (leak) { + outputBuffer_.reportMemoryLeak(leak); + leak = memoryTable_.getNextLeak(leak, period); + } + + outputBuffer_.stopMemoryLeakReporting(); +} + +const char* MemoryLeakDetector::report(MemLeakPeriod period) +{ + outputBuffer_.clear(); + ConstructMemoryLeakReport(period); + + return outputBuffer_.toString(); +} + +void MemoryLeakDetector::markCheckingPeriodLeaksAsNonCheckingPeriod() +{ + MemoryLeakDetectorNode* leak = memoryTable_.getFirstLeak(mem_leak_period_checking); + while (leak) { + if (leak->period_ == mem_leak_period_checking) leak->period_ = mem_leak_period_enabled; + leak = memoryTable_.getNextLeak(leak, mem_leak_period_checking); + } +} + +int MemoryLeakDetector::totalMemoryLeaks(MemLeakPeriod period) +{ + return memoryTable_.getTotalLeaks(period); +} diff --git a/src/CppUTest/MemoryLeakWarningPlugin.cpp b/src/CppUTest/MemoryLeakWarningPlugin.cpp index cd00f9826..d202df940 100644 --- a/src/CppUTest/MemoryLeakWarningPlugin.cpp +++ b/src/CppUTest/MemoryLeakWarningPlugin.cpp @@ -1,454 +1,454 @@ -/* - * 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/MemoryLeakWarningPlugin.h" -#include "CppUTest/MemoryLeakDetector.h" -#include "CppUTest/TestMemoryAllocator.h" -#include "CppUTest/PlatformSpecificFunctions.h" - -/********** Enabling and disabling for C also *********/ - -#if CPPUTEST_USE_MEM_LEAK_DETECTION - -static void* mem_leak_malloc(size_t size, const char* file, int line) -{ - return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentMallocAllocator(), size, file, line, true); -} - -static void mem_leak_free(void* buffer, const char* file, int 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) -{ - return MemoryLeakWarningPlugin::getGlobalDetector()->reallocMemory(getCurrentMallocAllocator(), (char*) memory, size, file, line, true); -} - -#endif - -static void* normal_malloc(size_t size, const char*, int) -{ - return PlatformSpecificMalloc(size); -} - -static void* normal_realloc(void* memory, size_t size, const char*, int) -{ - return PlatformSpecificRealloc(memory, size); -} - -static void normal_free(void* buffer, const char*, int) -{ - 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; -#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; -#endif - -void* cpputest_malloc_location_with_leak_detection(size_t size, const char* file, int line) -{ - return malloc_fptr(size, file, line); -} - -void* cpputest_realloc_location_with_leak_detection(void* memory, size_t size, const char* file, int line) -{ - return realloc_fptr(memory, size, file, line); -} - -void cpputest_free_location_with_leak_detection(void* buffer, const char* file, int line) -{ - free_fptr(buffer, file, line); -} - -/********** C++ *************/ - -#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(); -#else -#define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) -#endif - -static void* mem_leak_operator_new (size_t size) UT_THROW(std::bad_alloc) -{ - void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size); - UT_THROW_BAD_ALLOC_WHEN_NULL(memory); - return memory; -} - -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) -{ - void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size, (char*) 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) -{ - void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size); - UT_THROW_BAD_ALLOC_WHEN_NULL(memory); - return memory; -} - -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) -{ - void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, (char*) file, line); - UT_THROW_BAD_ALLOC_WHEN_NULL(memory); - return memory; -} - -static void mem_leak_operator_delete (void* mem) UT_NOTHROW -{ - MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); - MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewAllocator(), (char*) mem); -} - -static void mem_leak_operator_delete_array (void* mem) UT_NOTHROW -{ - MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); - MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewArrayAllocator(), (char*) mem); -} - -static void* normal_operator_new (size_t size) UT_THROW(std::bad_alloc) -{ - void* memory = PlatformSpecificMalloc(size); - UT_THROW_BAD_ALLOC_WHEN_NULL(memory); - return memory; -} - -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) -{ - 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) -{ - void* memory = PlatformSpecificMalloc(size); - UT_THROW_BAD_ALLOC_WHEN_NULL(memory); - return memory; -} - -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) -{ - void* memory = PlatformSpecificMalloc(size); - UT_THROW_BAD_ALLOC_WHEN_NULL(memory); - return memory; -} - -static void normal_operator_delete (void* mem) UT_NOTHROW -{ - PlatformSpecificFree(mem); -} - -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_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_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_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) -{ - return operator_new_fptr(size); -} - -void* operator new(size_t size, const char* file, int line) UT_THROW(std::bad_alloc) -{ - return operator_new_debug_fptr(size, file, line); -} - -void operator delete(void* mem) UT_NOTHROW -{ - operator_delete_fptr(mem); -} - -void operator delete(void* mem, const char*, int) UT_NOTHROW -{ - operator_delete_fptr(mem); -} - -void* operator new[](size_t size) UT_THROW(std::bad_alloc) -{ - return operator_new_array_fptr(size); -} - -void* operator new [](size_t size, const char* file, int line) UT_THROW(std::bad_alloc) -{ - return operator_new_array_debug_fptr(size, file, line); -} - -void operator delete[](void* mem) UT_NOTHROW -{ - operator_delete_array_fptr(mem); -} - -void operator delete[](void* mem, const char*, int) UT_NOTHROW -{ - operator_delete_array_fptr(mem); -} - - -#if CPPUTEST_USE_STD_CPP_LIB - -void* operator new(size_t size, const std::nothrow_t&) UT_NOTHROW -{ - return operator_new_nothrow_fptr(size); -} - -void* operator new[](size_t size, const std::nothrow_t&) UT_NOTHROW -{ - return operator_new_array_nothrow_fptr(size); -} - -#else - -/* Have a similar method. This avoid unused operator_new_nothrow_fptr warning */ - -extern void* operator_new_nothrow(size_t size) UT_NOTHROW; -extern void* operator_new_array_nothrow(size_t size) UT_NOTHROW; - -void* operator_new_nothrow(size_t size) UT_NOTHROW -{ - return operator_new_nothrow_fptr(size); -} - -void* operator_new_array_nothrow(size_t size) UT_NOTHROW -{ - return operator_new_array_nothrow_fptr(size); -} - -#endif -#endif - -void MemoryLeakWarningPlugin::turnOffNewDeleteOverloads() -{ -#if CPPUTEST_USE_MEM_LEAK_DETECTION - operator_new_fptr = normal_operator_new; - operator_new_nothrow_fptr = normal_operator_new_nothrow; - operator_new_debug_fptr = normal_operator_new_debug; - operator_new_array_fptr = normal_operator_new_array; - operator_new_array_nothrow_fptr = normal_operator_new_array_nothrow; - operator_new_array_debug_fptr = normal_operator_new_array_debug; - operator_delete_fptr = normal_operator_delete; - operator_delete_array_fptr = normal_operator_delete_array; - malloc_fptr = normal_malloc; - realloc_fptr = normal_realloc; - free_fptr = normal_free; - -#endif -} - -void MemoryLeakWarningPlugin::turnOnNewDeleteOverloads() -{ -#if CPPUTEST_USE_MEM_LEAK_DETECTION - operator_new_fptr = mem_leak_operator_new; - operator_new_nothrow_fptr = mem_leak_operator_new_nothrow; - operator_new_debug_fptr = mem_leak_operator_new_debug; - operator_new_array_fptr = mem_leak_operator_new_array; - operator_new_array_nothrow_fptr = mem_leak_operator_new_array_nothrow; - operator_new_array_debug_fptr = mem_leak_operator_new_array_debug; - operator_delete_fptr = mem_leak_operator_delete; - operator_delete_array_fptr = mem_leak_operator_delete_array; - malloc_fptr = mem_leak_malloc; - realloc_fptr = mem_leak_realloc; - free_fptr = mem_leak_free; -#endif -} - -void crash_on_allocation_number(unsigned alloc_number) -{ - static CrashOnAllocationAllocator crashAllocator; - crashAllocator.setNumberToCrashOn(alloc_number); - setCurrentMallocAllocator(&crashAllocator); - setCurrentNewAllocator(&crashAllocator); - setCurrentNewArrayAllocator(&crashAllocator); -} - -class MemoryLeakWarningReporter: public MemoryLeakFailure -{ -public: - virtual ~MemoryLeakWarningReporter() - { - } - - virtual void fail(char* fail_string) - { - UtestShell* currentTest = UtestShell::getCurrent(); - currentTest->failWith(FailFailure(currentTest, currentTest->getName().asCharString(), currentTest->getLineNumber(), fail_string), TestTerminatorWithoutExceptions()); - } -}; - -static MemoryLeakFailure* globalReporter = 0; -static MemoryLeakDetector* globalDetector = 0; - -MemoryLeakDetector* MemoryLeakWarningPlugin::getGlobalDetector() -{ - if (globalDetector == 0) { - turnOffNewDeleteOverloads(); - - globalReporter = new MemoryLeakWarningReporter; - globalDetector = new MemoryLeakDetector(globalReporter); - - turnOnNewDeleteOverloads(); - } - return globalDetector; -} - -MemoryLeakFailure* MemoryLeakWarningPlugin::getGlobalFailureReporter() -{ - return globalReporter; -} - -void MemoryLeakWarningPlugin::destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(bool des) -{ - destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_ = des; -} - -void MemoryLeakWarningPlugin::setGlobalDetector(MemoryLeakDetector* detector, MemoryLeakFailure* reporter) -{ - globalDetector = detector; - globalReporter = reporter; -} - -void MemoryLeakWarningPlugin::destroyGlobalDetector() -{ - turnOffNewDeleteOverloads(); - delete globalDetector; - delete globalReporter; - globalDetector = NULL; -} - - -MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::firstPlugin_ = 0; - -MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::getFirstPlugin() -{ - return firstPlugin_; -} - -MemoryLeakDetector* MemoryLeakWarningPlugin::getMemoryLeakDetector() -{ - return memLeakDetector_; -} - -void MemoryLeakWarningPlugin::ignoreAllLeaksInTest() -{ - ignoreAllWarnings_ = true; -} - -void MemoryLeakWarningPlugin::expectLeaksInTest(int n) -{ - expectedLeaks_ = n; -} - -MemoryLeakWarningPlugin::MemoryLeakWarningPlugin(const SimpleString& name, MemoryLeakDetector* localDetector) : - TestPlugin(name), ignoreAllWarnings_(false), destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_(false), expectedLeaks_(0) -{ - if (firstPlugin_ == 0) firstPlugin_ = this; - - if (localDetector) memLeakDetector_ = localDetector; - else memLeakDetector_ = getGlobalDetector(); - - memLeakDetector_->enable(); -} - -MemoryLeakWarningPlugin::~MemoryLeakWarningPlugin() -{ - if (destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_) { - MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); - MemoryLeakWarningPlugin::destroyGlobalDetector(); - } -} - -void MemoryLeakWarningPlugin::preTestAction(UtestShell& /*test*/, TestResult& result) -{ - memLeakDetector_->startChecking(); - failureCount_ = result.getFailureCount(); -} - -void MemoryLeakWarningPlugin::postTestAction(UtestShell& test, TestResult& result) -{ - memLeakDetector_->stopChecking(); - int 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); - } - memLeakDetector_->markCheckingPeriodLeaksAsNonCheckingPeriod(); - ignoreAllWarnings_ = false; - expectedLeaks_ = 0; -} - -const char* MemoryLeakWarningPlugin::FinalReport(int toBeDeletedLeaks) -{ - int leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_enabled); - if (leaks != toBeDeletedLeaks) return memLeakDetector_->report(mem_leak_period_enabled); - return ""; -} - - +/* + * 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/MemoryLeakWarningPlugin.h" +#include "CppUTest/MemoryLeakDetector.h" +#include "CppUTest/TestMemoryAllocator.h" +#include "CppUTest/PlatformSpecificFunctions.h" + +/********** Enabling and disabling for C also *********/ + +#if CPPUTEST_USE_MEM_LEAK_DETECTION + +static void* mem_leak_malloc(size_t size, const char* file, int line) +{ + return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentMallocAllocator(), size, file, line, true); +} + +static void mem_leak_free(void* buffer, const char* file, int 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) +{ + return MemoryLeakWarningPlugin::getGlobalDetector()->reallocMemory(getCurrentMallocAllocator(), (char*) memory, size, file, line, true); +} + +#endif + +static void* normal_malloc(size_t size, const char*, int) +{ + return PlatformSpecificMalloc(size); +} + +static void* normal_realloc(void* memory, size_t size, const char*, int) +{ + return PlatformSpecificRealloc(memory, size); +} + +static void normal_free(void* buffer, const char*, int) +{ + 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; +#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; +#endif + +void* cpputest_malloc_location_with_leak_detection(size_t size, const char* file, int line) +{ + return malloc_fptr(size, file, line); +} + +void* cpputest_realloc_location_with_leak_detection(void* memory, size_t size, const char* file, int line) +{ + return realloc_fptr(memory, size, file, line); +} + +void cpputest_free_location_with_leak_detection(void* buffer, const char* file, int line) +{ + free_fptr(buffer, file, line); +} + +/********** C++ *************/ + +#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(); +#else +#define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) +#endif + +static void* mem_leak_operator_new (size_t size) UT_THROW(std::bad_alloc) +{ + void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size); + UT_THROW_BAD_ALLOC_WHEN_NULL(memory); + return memory; +} + +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) +{ + void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size, (char*) 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) +{ + void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size); + UT_THROW_BAD_ALLOC_WHEN_NULL(memory); + return memory; +} + +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) +{ + void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, (char*) file, line); + UT_THROW_BAD_ALLOC_WHEN_NULL(memory); + return memory; +} + +static void mem_leak_operator_delete (void* mem) UT_NOTHROW +{ + MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); + MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewAllocator(), (char*) mem); +} + +static void mem_leak_operator_delete_array (void* mem) UT_NOTHROW +{ + MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); + MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewArrayAllocator(), (char*) mem); +} + +static void* normal_operator_new (size_t size) UT_THROW(std::bad_alloc) +{ + void* memory = PlatformSpecificMalloc(size); + UT_THROW_BAD_ALLOC_WHEN_NULL(memory); + return memory; +} + +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) +{ + 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) +{ + void* memory = PlatformSpecificMalloc(size); + UT_THROW_BAD_ALLOC_WHEN_NULL(memory); + return memory; +} + +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) +{ + void* memory = PlatformSpecificMalloc(size); + UT_THROW_BAD_ALLOC_WHEN_NULL(memory); + return memory; +} + +static void normal_operator_delete (void* mem) UT_NOTHROW +{ + PlatformSpecificFree(mem); +} + +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_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_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_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) +{ + return operator_new_fptr(size); +} + +void* operator new(size_t size, const char* file, int line) UT_THROW(std::bad_alloc) +{ + return operator_new_debug_fptr(size, file, line); +} + +void operator delete(void* mem) UT_NOTHROW +{ + operator_delete_fptr(mem); +} + +void operator delete(void* mem, const char*, int) UT_NOTHROW +{ + operator_delete_fptr(mem); +} + +void* operator new[](size_t size) UT_THROW(std::bad_alloc) +{ + return operator_new_array_fptr(size); +} + +void* operator new [](size_t size, const char* file, int line) UT_THROW(std::bad_alloc) +{ + return operator_new_array_debug_fptr(size, file, line); +} + +void operator delete[](void* mem) UT_NOTHROW +{ + operator_delete_array_fptr(mem); +} + +void operator delete[](void* mem, const char*, int) UT_NOTHROW +{ + operator_delete_array_fptr(mem); +} + + +#if CPPUTEST_USE_STD_CPP_LIB + +void* operator new(size_t size, const std::nothrow_t&) UT_NOTHROW +{ + return operator_new_nothrow_fptr(size); +} + +void* operator new[](size_t size, const std::nothrow_t&) UT_NOTHROW +{ + return operator_new_array_nothrow_fptr(size); +} + +#else + +/* Have a similar method. This avoid unused operator_new_nothrow_fptr warning */ + +extern void* operator_new_nothrow(size_t size) UT_NOTHROW; +extern void* operator_new_array_nothrow(size_t size) UT_NOTHROW; + +void* operator_new_nothrow(size_t size) UT_NOTHROW +{ + return operator_new_nothrow_fptr(size); +} + +void* operator_new_array_nothrow(size_t size) UT_NOTHROW +{ + return operator_new_array_nothrow_fptr(size); +} + +#endif +#endif + +void MemoryLeakWarningPlugin::turnOffNewDeleteOverloads() +{ +#if CPPUTEST_USE_MEM_LEAK_DETECTION + operator_new_fptr = normal_operator_new; + operator_new_nothrow_fptr = normal_operator_new_nothrow; + operator_new_debug_fptr = normal_operator_new_debug; + operator_new_array_fptr = normal_operator_new_array; + operator_new_array_nothrow_fptr = normal_operator_new_array_nothrow; + operator_new_array_debug_fptr = normal_operator_new_array_debug; + operator_delete_fptr = normal_operator_delete; + operator_delete_array_fptr = normal_operator_delete_array; + malloc_fptr = normal_malloc; + realloc_fptr = normal_realloc; + free_fptr = normal_free; + +#endif +} + +void MemoryLeakWarningPlugin::turnOnNewDeleteOverloads() +{ +#if CPPUTEST_USE_MEM_LEAK_DETECTION + operator_new_fptr = mem_leak_operator_new; + operator_new_nothrow_fptr = mem_leak_operator_new_nothrow; + operator_new_debug_fptr = mem_leak_operator_new_debug; + operator_new_array_fptr = mem_leak_operator_new_array; + operator_new_array_nothrow_fptr = mem_leak_operator_new_array_nothrow; + operator_new_array_debug_fptr = mem_leak_operator_new_array_debug; + operator_delete_fptr = mem_leak_operator_delete; + operator_delete_array_fptr = mem_leak_operator_delete_array; + malloc_fptr = mem_leak_malloc; + realloc_fptr = mem_leak_realloc; + free_fptr = mem_leak_free; +#endif +} + +void crash_on_allocation_number(unsigned alloc_number) +{ + static CrashOnAllocationAllocator crashAllocator; + crashAllocator.setNumberToCrashOn(alloc_number); + setCurrentMallocAllocator(&crashAllocator); + setCurrentNewAllocator(&crashAllocator); + setCurrentNewArrayAllocator(&crashAllocator); +} + +class MemoryLeakWarningReporter: public MemoryLeakFailure +{ +public: + virtual ~MemoryLeakWarningReporter() + { + } + + virtual void fail(char* fail_string) + { + UtestShell* currentTest = UtestShell::getCurrent(); + currentTest->failWith(FailFailure(currentTest, currentTest->getName().asCharString(), currentTest->getLineNumber(), fail_string), TestTerminatorWithoutExceptions()); + } +}; + +static MemoryLeakFailure* globalReporter = 0; +static MemoryLeakDetector* globalDetector = 0; + +MemoryLeakDetector* MemoryLeakWarningPlugin::getGlobalDetector() +{ + if (globalDetector == 0) { + turnOffNewDeleteOverloads(); + + globalReporter = new MemoryLeakWarningReporter; + globalDetector = new MemoryLeakDetector(globalReporter); + + turnOnNewDeleteOverloads(); + } + return globalDetector; +} + +MemoryLeakFailure* MemoryLeakWarningPlugin::getGlobalFailureReporter() +{ + return globalReporter; +} + +void MemoryLeakWarningPlugin::destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(bool des) +{ + destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_ = des; +} + +void MemoryLeakWarningPlugin::setGlobalDetector(MemoryLeakDetector* detector, MemoryLeakFailure* reporter) +{ + globalDetector = detector; + globalReporter = reporter; +} + +void MemoryLeakWarningPlugin::destroyGlobalDetector() +{ + turnOffNewDeleteOverloads(); + delete globalDetector; + delete globalReporter; + globalDetector = NULL; +} + + +MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::firstPlugin_ = 0; + +MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::getFirstPlugin() +{ + return firstPlugin_; +} + +MemoryLeakDetector* MemoryLeakWarningPlugin::getMemoryLeakDetector() +{ + return memLeakDetector_; +} + +void MemoryLeakWarningPlugin::ignoreAllLeaksInTest() +{ + ignoreAllWarnings_ = true; +} + +void MemoryLeakWarningPlugin::expectLeaksInTest(int n) +{ + expectedLeaks_ = n; +} + +MemoryLeakWarningPlugin::MemoryLeakWarningPlugin(const SimpleString& name, MemoryLeakDetector* localDetector) : + TestPlugin(name), ignoreAllWarnings_(false), destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_(false), expectedLeaks_(0) +{ + if (firstPlugin_ == 0) firstPlugin_ = this; + + if (localDetector) memLeakDetector_ = localDetector; + else memLeakDetector_ = getGlobalDetector(); + + memLeakDetector_->enable(); +} + +MemoryLeakWarningPlugin::~MemoryLeakWarningPlugin() +{ + if (destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_) { + MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); + MemoryLeakWarningPlugin::destroyGlobalDetector(); + } +} + +void MemoryLeakWarningPlugin::preTestAction(UtestShell& /*test*/, TestResult& result) +{ + memLeakDetector_->startChecking(); + failureCount_ = result.getFailureCount(); +} + +void MemoryLeakWarningPlugin::postTestAction(UtestShell& test, TestResult& result) +{ + memLeakDetector_->stopChecking(); + int 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); + } + memLeakDetector_->markCheckingPeriodLeaksAsNonCheckingPeriod(); + ignoreAllWarnings_ = false; + expectedLeaks_ = 0; +} + +const char* MemoryLeakWarningPlugin::FinalReport(int toBeDeletedLeaks) +{ + int leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_enabled); + if (leaks != toBeDeletedLeaks) return memLeakDetector_->report(mem_leak_period_enabled); + return ""; +} + + diff --git a/src/CppUTest/SimpleString.cpp b/src/CppUTest/SimpleString.cpp index fa3135331..558b5236e 100644 --- a/src/CppUTest/SimpleString.cpp +++ b/src/CppUTest/SimpleString.cpp @@ -1,515 +1,515 @@ -/* - * 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/SimpleString.h" -#include "CppUTest/PlatformSpecificFunctions.h" -#include "CppUTest/TestMemoryAllocator.h" - - -TestMemoryAllocator* SimpleString::stringAllocator_ = NULL; - -TestMemoryAllocator* SimpleString::getStringAllocator() -{ - if (stringAllocator_ == NULL) - return defaultNewArrayAllocator(); - return stringAllocator_; -} - -void SimpleString::setStringAllocator(TestMemoryAllocator* allocator) -{ - stringAllocator_ = allocator; -} - -/* Avoid using the memory leak detector INSIDE SimpleString as its used inside the detector */ -char* SimpleString::allocStringBuffer(size_t _size) -{ - return getStringAllocator()->alloc_memory(_size, __FILE__, __LINE__); -} - -void SimpleString::deallocStringBuffer(char* str) -{ - getStringAllocator()->free_memory(str, __FILE__, __LINE__); -} - -char* SimpleString::getEmptyString() const -{ - char* empty = allocStringBuffer(1); - empty[0] = '\0'; - return empty; -} -SimpleString::SimpleString(const char *otherBuffer) -{ - if (otherBuffer == 0) { - buffer_ = getEmptyString(); - } - else { - size_t len = PlatformSpecificStrLen(otherBuffer) + 1; - buffer_ = allocStringBuffer(len); - PlatformSpecificStrCpy(buffer_, otherBuffer); - } -} - -SimpleString::SimpleString(const char *other, size_t repeatCount) -{ - size_t len = PlatformSpecificStrLen(other) * repeatCount + 1; - buffer_ = allocStringBuffer(len); - char* next = buffer_; - for (size_t i = 0; i < repeatCount; i++) { - PlatformSpecificStrCpy(next, other); - next += PlatformSpecificStrLen(other); - } - *next = 0; - -} -SimpleString::SimpleString(const SimpleString& other) -{ - size_t len = other.size() + 1; - buffer_ = allocStringBuffer(len); - PlatformSpecificStrCpy(buffer_, other.buffer_); -} - -SimpleString& SimpleString::operator=(const SimpleString& other) -{ - if (this != &other) { - deallocStringBuffer(buffer_); - size_t len = other.size() + 1; - buffer_ = allocStringBuffer(len); - PlatformSpecificStrCpy(buffer_, other.buffer_); - } - return *this; -} - -bool SimpleString::contains(const SimpleString& other) const -{ - //strstr on some machines does not handle "" - //the right way. "" should be found in any string - if (PlatformSpecificStrLen(other.buffer_) == 0) return true; - else if (PlatformSpecificStrLen(buffer_) == 0) return false; - else return PlatformSpecificStrStr(buffer_, other.buffer_) != 0; -} - -bool SimpleString::containsNoCase(const SimpleString& other) const -{ - return toLower().contains(other.toLower()); -} - - -bool SimpleString::startsWith(const SimpleString& other) const -{ - if (PlatformSpecificStrLen(other.buffer_) == 0) return true; - else if (PlatformSpecificStrLen(buffer_) == 0) return false; - else return PlatformSpecificStrStr(buffer_, other.buffer_) == buffer_; -} - -bool SimpleString::endsWith(const SimpleString& other) const -{ - size_t buffer_length = PlatformSpecificStrLen(buffer_); - size_t other_buffer_length = PlatformSpecificStrLen(other.buffer_); - if (other_buffer_length == 0) return true; - if (buffer_length == 0) return false; - if (buffer_length < other_buffer_length) return false; - return PlatformSpecificStrCmp(buffer_ + buffer_length - other_buffer_length, other.buffer_) == 0; -} - -size_t SimpleString::count(const SimpleString& substr) const -{ - size_t num = 0; - char* str = buffer_; - while ((str = PlatformSpecificStrStr(str, substr.buffer_))) { - num++; - str++; - } - return num; -} - -void SimpleString::split(const SimpleString& delimiter, SimpleStringCollection& col) const -{ - size_t num = count(delimiter); - size_t extraEndToken = (endsWith(delimiter)) ? 0 : 1U; - col.allocate(num + extraEndToken); - - char* str = buffer_; - char* prev; - for (size_t i = 0; i < num; ++i) { - prev = str; - str = PlatformSpecificStrStr(str, delimiter.buffer_) + 1; - size_t len = (size_t) (str - prev); - char* sub = allocStringBuffer(len + 1); - PlatformSpecificStrNCpy(sub, prev, len); - sub[len] = '\0'; - col[i] = sub; - deallocStringBuffer(sub); - } - if (extraEndToken) { - col[num] = str; - } -} - -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; - } -} - -void SimpleString::replace(const char* to, const char* with) -{ - size_t c = count(to); - size_t len = size(); - size_t tolen = PlatformSpecificStrLen(to); - size_t withlen = PlatformSpecificStrLen(with); - - size_t newsize = len + (withlen * c) - (tolen * c) + 1; - - if (newsize) { - char* newbuf = allocStringBuffer(newsize); - for (size_t i = 0, j = 0; i < len;) { - if (PlatformSpecificStrNCmp(&buffer_[i], to, tolen) == 0) { - PlatformSpecificStrNCpy(&newbuf[j], with, withlen); - j += withlen; - i += tolen; - } - else { - newbuf[j] = buffer_[i]; - j++; - i++; - } - } - deallocStringBuffer(buffer_); - buffer_ = newbuf; - buffer_[newsize - 1] = '\0'; - } - else { - buffer_ = getEmptyString(); - buffer_[0] = '\0'; - } -} - -SimpleString SimpleString::toLower() const -{ - SimpleString str(*this); - - size_t str_size = str.size(); - for (size_t i = 0; i < str_size; i++) - str.buffer_[i] = PlatformSpecificToLower(str.buffer_[i]); - - return str; -} - -const char *SimpleString::asCharString() const -{ - return buffer_; -} - -size_t SimpleString::size() const -{ - return PlatformSpecificStrLen(buffer_); -} - -bool SimpleString::isEmpty() const -{ - return size() == 0; -} - - - -SimpleString::~SimpleString() -{ - deallocStringBuffer(buffer_); -} - -bool operator==(const SimpleString& left, const SimpleString& right) -{ - return 0 == PlatformSpecificStrCmp(left.asCharString(), right.asCharString()); -} - -bool SimpleString::equalsNoCase(const SimpleString& str) const -{ - return toLower() == str.toLower(); -} - - -bool operator!=(const SimpleString& left, const SimpleString& right) -{ - return !(left == right); -} - -SimpleString SimpleString::operator+(const SimpleString& rhs) -{ - SimpleString t(buffer_); - t += rhs.buffer_; - return t; -} - -SimpleString& SimpleString::operator+=(const SimpleString& rhs) -{ - return operator+=(rhs.buffer_); -} - -SimpleString& SimpleString::operator+=(const char* rhs) -{ - size_t len = this->size() + PlatformSpecificStrLen(rhs) + 1; - char* tbuffer = allocStringBuffer(len); - PlatformSpecificStrCpy(tbuffer, this->buffer_); - PlatformSpecificStrCat(tbuffer, rhs); - deallocStringBuffer(buffer_); - buffer_ = tbuffer; - return *this; -} - -void SimpleString::padStringsToSameLength(SimpleString& str1, SimpleString& str2, char padCharacter) -{ - if (str1.size() > str2.size()) { - padStringsToSameLength(str2, str1, padCharacter); - return; - } - - char pad[2]; - pad[0] = padCharacter; - pad[1] = 0; - str1 = SimpleString(pad, str2.size() - str1.size()) + str1; -} - -SimpleString SimpleString::subString(size_t beginPos, size_t amount) const -{ - if (beginPos > size()-1) return ""; - - SimpleString newString = buffer_ + beginPos; - - if (newString.size() > amount) - newString.buffer_[amount] = '\0'; - - return newString; -} - -char SimpleString::at(int pos) const -{ - return buffer_[pos]; -} - -int SimpleString::find(char ch) const -{ - return findFrom(0, ch); -} - -int 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 (int) i; - return -1; -} - -SimpleString SimpleString::subStringFromTill(char startChar, char lastExcludedChar) const -{ - int beginPos = find(startChar); - if (beginPos < 0) return ""; - - int endPos = findFrom((size_t)beginPos, lastExcludedChar); - if (endPos == -1) return subString((size_t)beginPos, size()); - - return subString((size_t)beginPos, (size_t) (endPos - beginPos)); -} - - -void SimpleString::copyToBuffer(char* bufferToCopy, size_t bufferSize) const -{ - if (bufferToCopy == NULL || bufferSize == 0) return; - - size_t sizeToCopy = (bufferSize-1 < size()) ? bufferSize-1 : size(); - - PlatformSpecificStrNCpy(bufferToCopy, buffer_, sizeToCopy); - bufferToCopy[sizeToCopy] = '\0'; - -} - -SimpleString StringFrom(bool value) -{ - return SimpleString(StringFromFormat("%s", value ? "true" : "false")); -} - -SimpleString StringFrom(const char *value) -{ - return SimpleString(value); -} - -SimpleString StringFromOrNull(const char * expected) -{ - return (expected) ? StringFrom(expected) : "(null)"; -} - -SimpleString StringFrom(int value) -{ - return StringFromFormat("%d", value); -} - -SimpleString StringFrom(long value) -{ - return StringFromFormat("%ld", value); -} - -SimpleString StringFrom(const void* value) -{ - return SimpleString("0x") + HexStringFrom(value); -} - -SimpleString HexStringFrom(long value) -{ - return StringFromFormat("%lx", value); -} - -static long convertPointerToLongValue(const void* value) -{ - /* - * This way of converting also can convert a 64bit pointer in a 32bit integer by truncating. - * This isn't the right way to convert pointers values and need to change by implementing a - * proper portable way to convert pointers to strings. - */ - long* long_value = (long*) &value; - return *long_value; -} - -SimpleString HexStringFrom(const void* value) -{ - return StringFromFormat("%lx", convertPointerToLongValue(value)); -} - -SimpleString StringFrom(double value, int precision) -{ - return StringFromFormat("%.*g", precision, value); -} - -SimpleString StringFrom(char value) -{ - return StringFromFormat("%c", value); -} - -SimpleString StringFrom(const SimpleString& value) -{ - return SimpleString(value); -} - -SimpleString StringFromFormat(const char* format, ...) -{ - SimpleString resultString; - va_list arguments; - va_start(arguments, format); - - resultString = VStringFromFormat(format, arguments); - va_end(arguments); - return resultString; -} - -SimpleString StringFrom(unsigned int i) -{ - return StringFromFormat("%10u (0x%08x)", i, i); -} - -#if CPPUTEST_USE_STD_CPP_LIB - -#include - -SimpleString StringFrom(const std::string& value) -{ - return SimpleString(value.c_str()); -} - -SimpleString StringFrom(unsigned long i) -{ - return StringFromFormat("%lu (0x%lx)", i, i); -} - -#endif - -//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; - va_copy(argsCopy, args); - enum - { - sizeOfdefaultBuffer = 100 - }; - char defaultBuffer[sizeOfdefaultBuffer]; - SimpleString resultString; - - size_t size = (size_t)PlatformSpecificVSNprintf(defaultBuffer, sizeOfdefaultBuffer, format, args); - if (size < sizeOfdefaultBuffer) { - resultString = SimpleString(defaultBuffer); - } - else { - size_t newBufferSize = size + 1; - char* newBuffer = SimpleString::allocStringBuffer(newBufferSize); - PlatformSpecificVSNprintf(newBuffer, newBufferSize, format, argsCopy); - resultString = SimpleString(newBuffer); - - SimpleString::deallocStringBuffer(newBuffer); - } - va_end(argsCopy); - return resultString; -} - -SimpleStringCollection::SimpleStringCollection() -{ - collection_ = 0; - size_ = 0; -} - -void SimpleStringCollection::allocate(size_t _size) -{ - if (collection_) delete[] collection_; - - size_ = _size; - collection_ = new SimpleString[size_]; -} - -SimpleStringCollection::~SimpleStringCollection() -{ - delete[] (collection_); -} - -size_t SimpleStringCollection::size() const -{ - return size_; -} - -SimpleString& SimpleStringCollection::operator[](size_t index) -{ - if (index >= size_) { - empty_ = ""; - return empty_; - } - - return collection_[index]; -} - +/* + * 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/SimpleString.h" +#include "CppUTest/PlatformSpecificFunctions.h" +#include "CppUTest/TestMemoryAllocator.h" + + +TestMemoryAllocator* SimpleString::stringAllocator_ = NULL; + +TestMemoryAllocator* SimpleString::getStringAllocator() +{ + if (stringAllocator_ == NULL) + return defaultNewArrayAllocator(); + return stringAllocator_; +} + +void SimpleString::setStringAllocator(TestMemoryAllocator* allocator) +{ + stringAllocator_ = allocator; +} + +/* Avoid using the memory leak detector INSIDE SimpleString as its used inside the detector */ +char* SimpleString::allocStringBuffer(size_t _size) +{ + return getStringAllocator()->alloc_memory(_size, __FILE__, __LINE__); +} + +void SimpleString::deallocStringBuffer(char* str) +{ + getStringAllocator()->free_memory(str, __FILE__, __LINE__); +} + +char* SimpleString::getEmptyString() const +{ + char* empty = allocStringBuffer(1); + empty[0] = '\0'; + return empty; +} +SimpleString::SimpleString(const char *otherBuffer) +{ + if (otherBuffer == 0) { + buffer_ = getEmptyString(); + } + else { + size_t len = PlatformSpecificStrLen(otherBuffer) + 1; + buffer_ = allocStringBuffer(len); + PlatformSpecificStrCpy(buffer_, otherBuffer); + } +} + +SimpleString::SimpleString(const char *other, size_t repeatCount) +{ + size_t len = PlatformSpecificStrLen(other) * repeatCount + 1; + buffer_ = allocStringBuffer(len); + char* next = buffer_; + for (size_t i = 0; i < repeatCount; i++) { + PlatformSpecificStrCpy(next, other); + next += PlatformSpecificStrLen(other); + } + *next = 0; + +} +SimpleString::SimpleString(const SimpleString& other) +{ + size_t len = other.size() + 1; + buffer_ = allocStringBuffer(len); + PlatformSpecificStrCpy(buffer_, other.buffer_); +} + +SimpleString& SimpleString::operator=(const SimpleString& other) +{ + if (this != &other) { + deallocStringBuffer(buffer_); + size_t len = other.size() + 1; + buffer_ = allocStringBuffer(len); + PlatformSpecificStrCpy(buffer_, other.buffer_); + } + return *this; +} + +bool SimpleString::contains(const SimpleString& other) const +{ + //strstr on some machines does not handle "" + //the right way. "" should be found in any string + if (PlatformSpecificStrLen(other.buffer_) == 0) return true; + else if (PlatformSpecificStrLen(buffer_) == 0) return false; + else return PlatformSpecificStrStr(buffer_, other.buffer_) != 0; +} + +bool SimpleString::containsNoCase(const SimpleString& other) const +{ + return toLower().contains(other.toLower()); +} + + +bool SimpleString::startsWith(const SimpleString& other) const +{ + if (PlatformSpecificStrLen(other.buffer_) == 0) return true; + else if (PlatformSpecificStrLen(buffer_) == 0) return false; + else return PlatformSpecificStrStr(buffer_, other.buffer_) == buffer_; +} + +bool SimpleString::endsWith(const SimpleString& other) const +{ + size_t buffer_length = PlatformSpecificStrLen(buffer_); + size_t other_buffer_length = PlatformSpecificStrLen(other.buffer_); + if (other_buffer_length == 0) return true; + if (buffer_length == 0) return false; + if (buffer_length < other_buffer_length) return false; + return PlatformSpecificStrCmp(buffer_ + buffer_length - other_buffer_length, other.buffer_) == 0; +} + +size_t SimpleString::count(const SimpleString& substr) const +{ + size_t num = 0; + char* str = buffer_; + while ((str = PlatformSpecificStrStr(str, substr.buffer_))) { + num++; + str++; + } + return num; +} + +void SimpleString::split(const SimpleString& delimiter, SimpleStringCollection& col) const +{ + size_t num = count(delimiter); + size_t extraEndToken = (endsWith(delimiter)) ? 0 : 1U; + col.allocate(num + extraEndToken); + + char* str = buffer_; + char* prev; + for (size_t i = 0; i < num; ++i) { + prev = str; + str = PlatformSpecificStrStr(str, delimiter.buffer_) + 1; + size_t len = (size_t) (str - prev); + char* sub = allocStringBuffer(len + 1); + PlatformSpecificStrNCpy(sub, prev, len); + sub[len] = '\0'; + col[i] = sub; + deallocStringBuffer(sub); + } + if (extraEndToken) { + col[num] = str; + } +} + +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; + } +} + +void SimpleString::replace(const char* to, const char* with) +{ + size_t c = count(to); + size_t len = size(); + size_t tolen = PlatformSpecificStrLen(to); + size_t withlen = PlatformSpecificStrLen(with); + + size_t newsize = len + (withlen * c) - (tolen * c) + 1; + + if (newsize) { + char* newbuf = allocStringBuffer(newsize); + for (size_t i = 0, j = 0; i < len;) { + if (PlatformSpecificStrNCmp(&buffer_[i], to, tolen) == 0) { + PlatformSpecificStrNCpy(&newbuf[j], with, withlen); + j += withlen; + i += tolen; + } + else { + newbuf[j] = buffer_[i]; + j++; + i++; + } + } + deallocStringBuffer(buffer_); + buffer_ = newbuf; + buffer_[newsize - 1] = '\0'; + } + else { + buffer_ = getEmptyString(); + buffer_[0] = '\0'; + } +} + +SimpleString SimpleString::toLower() const +{ + SimpleString str(*this); + + size_t str_size = str.size(); + for (size_t i = 0; i < str_size; i++) + str.buffer_[i] = PlatformSpecificToLower(str.buffer_[i]); + + return str; +} + +const char *SimpleString::asCharString() const +{ + return buffer_; +} + +size_t SimpleString::size() const +{ + return PlatformSpecificStrLen(buffer_); +} + +bool SimpleString::isEmpty() const +{ + return size() == 0; +} + + + +SimpleString::~SimpleString() +{ + deallocStringBuffer(buffer_); +} + +bool operator==(const SimpleString& left, const SimpleString& right) +{ + return 0 == PlatformSpecificStrCmp(left.asCharString(), right.asCharString()); +} + +bool SimpleString::equalsNoCase(const SimpleString& str) const +{ + return toLower() == str.toLower(); +} + + +bool operator!=(const SimpleString& left, const SimpleString& right) +{ + return !(left == right); +} + +SimpleString SimpleString::operator+(const SimpleString& rhs) +{ + SimpleString t(buffer_); + t += rhs.buffer_; + return t; +} + +SimpleString& SimpleString::operator+=(const SimpleString& rhs) +{ + return operator+=(rhs.buffer_); +} + +SimpleString& SimpleString::operator+=(const char* rhs) +{ + size_t len = this->size() + PlatformSpecificStrLen(rhs) + 1; + char* tbuffer = allocStringBuffer(len); + PlatformSpecificStrCpy(tbuffer, this->buffer_); + PlatformSpecificStrCat(tbuffer, rhs); + deallocStringBuffer(buffer_); + buffer_ = tbuffer; + return *this; +} + +void SimpleString::padStringsToSameLength(SimpleString& str1, SimpleString& str2, char padCharacter) +{ + if (str1.size() > str2.size()) { + padStringsToSameLength(str2, str1, padCharacter); + return; + } + + char pad[2]; + pad[0] = padCharacter; + pad[1] = 0; + str1 = SimpleString(pad, str2.size() - str1.size()) + str1; +} + +SimpleString SimpleString::subString(size_t beginPos, size_t amount) const +{ + if (beginPos > size()-1) return ""; + + SimpleString newString = buffer_ + beginPos; + + if (newString.size() > amount) + newString.buffer_[amount] = '\0'; + + return newString; +} + +char SimpleString::at(int pos) const +{ + return buffer_[pos]; +} + +int SimpleString::find(char ch) const +{ + return findFrom(0, ch); +} + +int 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 (int) i; + return -1; +} + +SimpleString SimpleString::subStringFromTill(char startChar, char lastExcludedChar) const +{ + int beginPos = find(startChar); + if (beginPos < 0) return ""; + + int endPos = findFrom((size_t)beginPos, lastExcludedChar); + if (endPos == -1) return subString((size_t)beginPos, size()); + + return subString((size_t)beginPos, (size_t) (endPos - beginPos)); +} + + +void SimpleString::copyToBuffer(char* bufferToCopy, size_t bufferSize) const +{ + if (bufferToCopy == NULL || bufferSize == 0) return; + + size_t sizeToCopy = (bufferSize-1 < size()) ? bufferSize-1 : size(); + + PlatformSpecificStrNCpy(bufferToCopy, buffer_, sizeToCopy); + bufferToCopy[sizeToCopy] = '\0'; + +} + +SimpleString StringFrom(bool value) +{ + return SimpleString(StringFromFormat("%s", value ? "true" : "false")); +} + +SimpleString StringFrom(const char *value) +{ + return SimpleString(value); +} + +SimpleString StringFromOrNull(const char * expected) +{ + return (expected) ? StringFrom(expected) : "(null)"; +} + +SimpleString StringFrom(int value) +{ + return StringFromFormat("%d", value); +} + +SimpleString StringFrom(long value) +{ + return StringFromFormat("%ld", value); +} + +SimpleString StringFrom(const void* value) +{ + return SimpleString("0x") + HexStringFrom(value); +} + +SimpleString HexStringFrom(long value) +{ + return StringFromFormat("%lx", value); +} + +static long convertPointerToLongValue(const void* value) +{ + /* + * This way of converting also can convert a 64bit pointer in a 32bit integer by truncating. + * This isn't the right way to convert pointers values and need to change by implementing a + * proper portable way to convert pointers to strings. + */ + long* long_value = (long*) &value; + return *long_value; +} + +SimpleString HexStringFrom(const void* value) +{ + return StringFromFormat("%lx", convertPointerToLongValue(value)); +} + +SimpleString StringFrom(double value, int precision) +{ + return StringFromFormat("%.*g", precision, value); +} + +SimpleString StringFrom(char value) +{ + return StringFromFormat("%c", value); +} + +SimpleString StringFrom(const SimpleString& value) +{ + return SimpleString(value); +} + +SimpleString StringFromFormat(const char* format, ...) +{ + SimpleString resultString; + va_list arguments; + va_start(arguments, format); + + resultString = VStringFromFormat(format, arguments); + va_end(arguments); + return resultString; +} + +SimpleString StringFrom(unsigned int i) +{ + return StringFromFormat("%10u (0x%08x)", i, i); +} + +#if CPPUTEST_USE_STD_CPP_LIB + +#include + +SimpleString StringFrom(const std::string& value) +{ + return SimpleString(value.c_str()); +} + +SimpleString StringFrom(unsigned long i) +{ + return StringFromFormat("%lu (0x%lx)", i, i); +} + +#endif + +//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; + va_copy(argsCopy, args); + enum + { + sizeOfdefaultBuffer = 100 + }; + char defaultBuffer[sizeOfdefaultBuffer]; + SimpleString resultString; + + size_t size = (size_t)PlatformSpecificVSNprintf(defaultBuffer, sizeOfdefaultBuffer, format, args); + if (size < sizeOfdefaultBuffer) { + resultString = SimpleString(defaultBuffer); + } + else { + size_t newBufferSize = size + 1; + char* newBuffer = SimpleString::allocStringBuffer(newBufferSize); + PlatformSpecificVSNprintf(newBuffer, newBufferSize, format, argsCopy); + resultString = SimpleString(newBuffer); + + SimpleString::deallocStringBuffer(newBuffer); + } + va_end(argsCopy); + return resultString; +} + +SimpleStringCollection::SimpleStringCollection() +{ + collection_ = 0; + size_ = 0; +} + +void SimpleStringCollection::allocate(size_t _size) +{ + if (collection_) delete[] collection_; + + size_ = _size; + collection_ = new SimpleString[size_]; +} + +SimpleStringCollection::~SimpleStringCollection() +{ + delete[] (collection_); +} + +size_t SimpleStringCollection::size() const +{ + return size_; +} + +SimpleString& SimpleStringCollection::operator[](size_t index) +{ + if (index >= size_) { + empty_ = ""; + return empty_; + } + + return collection_[index]; +} + diff --git a/src/CppUTest/TestFailure.cpp b/src/CppUTest/TestFailure.cpp index cf06dade0..16ccffda0 100644 --- a/src/CppUTest/TestFailure.cpp +++ b/src/CppUTest/TestFailure.cpp @@ -1,252 +1,252 @@ -/* - * 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/TestFailure.h" -#include "CppUTest/TestOutput.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; -} - -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) : - testName_(test->getFormattedName()), fileName_(fileName), lineNumber_(lineNumber), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_(theMessage) -{ -} - -TestFailure::TestFailure(UtestShell* test, const SimpleString& theMessage) : - testName_(test->getFormattedName()), fileName_(test->getFile()), lineNumber_(test->getLineNumber()), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_(theMessage) -{ -} - -TestFailure::TestFailure(UtestShell* test, const char* fileName, int lineNum) : - testName_(test->getFormattedName()), fileName_(fileName), lineNumber_(lineNum), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_("no message") -{ -} - -TestFailure::TestFailure(const TestFailure& f) : - testName_(f.testName_), fileName_(f.fileName_), lineNumber_(f.lineNumber_), testFileName_(f.testFileName_), testLineNumber_(f.testLineNumber_), message_(f.message_) -{ -} - - -TestFailure::~TestFailure() -{ -} - -SimpleString TestFailure::getFileName() const -{ - return fileName_; -} - -SimpleString TestFailure::getTestFileName() const -{ - return testFileName_; -} - -SimpleString TestFailure::getTestName() const -{ - return testName_; -} - -int TestFailure::getFailureLineNumber() const -{ - return lineNumber_; -} - -int TestFailure::getTestLineNumber() const -{ - return testLineNumber_; -} - -SimpleString TestFailure::getMessage() const -{ - return message_; -} - -bool TestFailure::isOutsideTestFile() const -{ - return testFileName_ != fileName_; -} - -bool TestFailure::isInHelperFunction() const -{ - return lineNumber_ < testLineNumber_; -} - -SimpleString TestFailure::createButWasString(const SimpleString& expected, const SimpleString& actual) -{ - return StringFromFormat("expected <%s>\n\tbut was <%s>", expected.asCharString(), actual.asCharString()); -} - -SimpleString TestFailure::createDifferenceAtPosString(const SimpleString& actual, size_t position) -{ - SimpleString result; - const size_t extraCharactersWindow = 20; - const size_t halfOfExtraCharactersWindow = extraCharactersWindow / 2; - - SimpleString paddingForPreventingOutOfBounds (" ", halfOfExtraCharactersWindow); - SimpleString actualString = paddingForPreventingOutOfBounds + actual + paddingForPreventingOutOfBounds; - SimpleString differentString = StringFromFormat("difference starts at position %lu at: <", (unsigned long) position); - - result += "\n"; - result += StringFromFormat("\t%s%s>\n", differentString.asCharString(), actualString.subString(position, extraCharactersWindow).asCharString()); - - SimpleString markString = actualString.subString(position, halfOfExtraCharactersWindow+1); - markString = removeAllPrintableCharactersFrom(markString); - markString = addMarkerToString(markString, halfOfExtraCharactersWindow); - - result += StringFromFormat("\t%s%s", SimpleString(" ", differentString.size()).asCharString(), markString.asCharString()); - return result; -} - -EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : - TestFailure(test, fileName, lineNumber) -{ - message_ = createButWasString(StringFromOrNull(expected), StringFromOrNull(actual)); -} - -EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) - : TestFailure(test, fileName, lineNumber) -{ - message_ = createButWasString(expected, actual); -} - -static SimpleString StringFromOrNan(double d) -{ - if (PlatformSpecificIsNan(d)) - return "Nan - Not a number"; - return StringFrom(d); -} - -DoublesEqualFailure::DoublesEqualFailure(UtestShell* test, const char* fileName, int lineNumber, double expected, double actual, double threshold) : TestFailure(test, fileName, lineNumber) -{ - message_ = createButWasString(StringFromOrNan(expected), StringFromOrNan(actual)); - message_ += " threshold used was <"; - message_ += StringFromOrNan(threshold); - message_ += ">"; - - if (PlatformSpecificIsNan(expected) || PlatformSpecificIsNan(actual) || PlatformSpecificIsNan(threshold)) - message_ += "\n\tCannot make comparisons with Nan"; -} - -CheckEqualFailure::CheckEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) : TestFailure(test, fileName, lineNumber) -{ - size_t failStart; - for (failStart = 0; actual.asCharString()[failStart] == expected.asCharString()[failStart]; failStart++) - ; - message_ = createButWasString(expected, actual); - message_ += createDifferenceAtPosString(actual, failStart); - -} - -ContainsFailure::ContainsFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) : - TestFailure(test, fileName, lineNumber) -{ - 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) : TestFailure(test, fileName, lineNumber) -{ - message_ = ""; - if (!text.isEmpty()) { - message_ += "Message: "; - message_ += text; - message_ += "\n\t"; - } - message_ += checkString; - message_ += "("; - message_ += conditionString; - message_ += ") failed"; -} - -FailFailure::FailFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& message) : TestFailure(test, fileName, lineNumber) -{ - message_ = message; -} - -LongsEqualFailure::LongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, long expected, long actual) : TestFailure(test, fileName, lineNumber) -{ - 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; - message_ = createButWasString(expectedReported, actualReported); -} - - -StringEqualFailure::StringEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : TestFailure(test, fileName, lineNumber) -{ - size_t failStart; - for (failStart = 0; actual[failStart] == expected[failStart]; failStart++) - ; - message_ = createButWasString(expected, actual); - message_ += createDifferenceAtPosString(actual, failStart); -} - -StringEqualNoCaseFailure::StringEqualNoCaseFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : TestFailure(test, fileName, lineNumber) -{ - size_t failStart; - for (failStart = 0; PlatformSpecificToLower(actual[failStart]) == PlatformSpecificToLower(expected[failStart]); failStart++) - ; - message_ = createButWasString(expected, actual); - message_ += createDifferenceAtPosString(actual, failStart); -} - - +/* + * 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/TestFailure.h" +#include "CppUTest/TestOutput.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; +} + +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) : + testName_(test->getFormattedName()), fileName_(fileName), lineNumber_(lineNumber), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_(theMessage) +{ +} + +TestFailure::TestFailure(UtestShell* test, const SimpleString& theMessage) : + testName_(test->getFormattedName()), fileName_(test->getFile()), lineNumber_(test->getLineNumber()), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_(theMessage) +{ +} + +TestFailure::TestFailure(UtestShell* test, const char* fileName, int lineNum) : + testName_(test->getFormattedName()), fileName_(fileName), lineNumber_(lineNum), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_("no message") +{ +} + +TestFailure::TestFailure(const TestFailure& f) : + testName_(f.testName_), fileName_(f.fileName_), lineNumber_(f.lineNumber_), testFileName_(f.testFileName_), testLineNumber_(f.testLineNumber_), message_(f.message_) +{ +} + + +TestFailure::~TestFailure() +{ +} + +SimpleString TestFailure::getFileName() const +{ + return fileName_; +} + +SimpleString TestFailure::getTestFileName() const +{ + return testFileName_; +} + +SimpleString TestFailure::getTestName() const +{ + return testName_; +} + +int TestFailure::getFailureLineNumber() const +{ + return lineNumber_; +} + +int TestFailure::getTestLineNumber() const +{ + return testLineNumber_; +} + +SimpleString TestFailure::getMessage() const +{ + return message_; +} + +bool TestFailure::isOutsideTestFile() const +{ + return testFileName_ != fileName_; +} + +bool TestFailure::isInHelperFunction() const +{ + return lineNumber_ < testLineNumber_; +} + +SimpleString TestFailure::createButWasString(const SimpleString& expected, const SimpleString& actual) +{ + return StringFromFormat("expected <%s>\n\tbut was <%s>", expected.asCharString(), actual.asCharString()); +} + +SimpleString TestFailure::createDifferenceAtPosString(const SimpleString& actual, size_t position) +{ + SimpleString result; + const size_t extraCharactersWindow = 20; + const size_t halfOfExtraCharactersWindow = extraCharactersWindow / 2; + + SimpleString paddingForPreventingOutOfBounds (" ", halfOfExtraCharactersWindow); + SimpleString actualString = paddingForPreventingOutOfBounds + actual + paddingForPreventingOutOfBounds; + SimpleString differentString = StringFromFormat("difference starts at position %lu at: <", (unsigned long) position); + + result += "\n"; + result += StringFromFormat("\t%s%s>\n", differentString.asCharString(), actualString.subString(position, extraCharactersWindow).asCharString()); + + SimpleString markString = actualString.subString(position, halfOfExtraCharactersWindow+1); + markString = removeAllPrintableCharactersFrom(markString); + markString = addMarkerToString(markString, halfOfExtraCharactersWindow); + + result += StringFromFormat("\t%s%s", SimpleString(" ", differentString.size()).asCharString(), markString.asCharString()); + return result; +} + +EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : + TestFailure(test, fileName, lineNumber) +{ + message_ = createButWasString(StringFromOrNull(expected), StringFromOrNull(actual)); +} + +EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) + : TestFailure(test, fileName, lineNumber) +{ + message_ = createButWasString(expected, actual); +} + +static SimpleString StringFromOrNan(double d) +{ + if (PlatformSpecificIsNan(d)) + return "Nan - Not a number"; + return StringFrom(d); +} + +DoublesEqualFailure::DoublesEqualFailure(UtestShell* test, const char* fileName, int lineNumber, double expected, double actual, double threshold) : TestFailure(test, fileName, lineNumber) +{ + message_ = createButWasString(StringFromOrNan(expected), StringFromOrNan(actual)); + message_ += " threshold used was <"; + message_ += StringFromOrNan(threshold); + message_ += ">"; + + if (PlatformSpecificIsNan(expected) || PlatformSpecificIsNan(actual) || PlatformSpecificIsNan(threshold)) + message_ += "\n\tCannot make comparisons with Nan"; +} + +CheckEqualFailure::CheckEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) : TestFailure(test, fileName, lineNumber) +{ + size_t failStart; + for (failStart = 0; actual.asCharString()[failStart] == expected.asCharString()[failStart]; failStart++) + ; + message_ = createButWasString(expected, actual); + message_ += createDifferenceAtPosString(actual, failStart); + +} + +ContainsFailure::ContainsFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) : + TestFailure(test, fileName, lineNumber) +{ + 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) : TestFailure(test, fileName, lineNumber) +{ + message_ = ""; + if (!text.isEmpty()) { + message_ += "Message: "; + message_ += text; + message_ += "\n\t"; + } + message_ += checkString; + message_ += "("; + message_ += conditionString; + message_ += ") failed"; +} + +FailFailure::FailFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& message) : TestFailure(test, fileName, lineNumber) +{ + message_ = message; +} + +LongsEqualFailure::LongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, long expected, long actual) : TestFailure(test, fileName, lineNumber) +{ + 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; + message_ = createButWasString(expectedReported, actualReported); +} + + +StringEqualFailure::StringEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : TestFailure(test, fileName, lineNumber) +{ + size_t failStart; + for (failStart = 0; actual[failStart] == expected[failStart]; failStart++) + ; + message_ = createButWasString(expected, actual); + message_ += createDifferenceAtPosString(actual, failStart); +} + +StringEqualNoCaseFailure::StringEqualNoCaseFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : TestFailure(test, fileName, lineNumber) +{ + size_t failStart; + for (failStart = 0; PlatformSpecificToLower(actual[failStart]) == PlatformSpecificToLower(expected[failStart]); failStart++) + ; + message_ = createButWasString(expected, actual); + message_ += createDifferenceAtPosString(actual, failStart); +} + + diff --git a/src/CppUTest/TestHarness_c.cpp b/src/CppUTest/TestHarness_c.cpp index 1fbbfffb5..d663c74b1 100644 --- a/src/CppUTest/TestHarness_c.cpp +++ b/src/CppUTest/TestHarness_c.cpp @@ -1,164 +1,164 @@ -/* - * 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 "CppUTest/TestMemoryAllocator.h" -#include "CppUTest/PlatformSpecificFunctions.h" -#include "CppUTest/TestHarness_c.h" - -extern "C" -{ - - -void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, const char* fileName, int lineNumber) -{ - UtestShell::getCurrent()->assertLongsEqual((long)expected, (long)actual, fileName, lineNumber, TestTerminatorWithoutExceptions()); -} - -void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* fileName, int lineNumber) -{ - UtestShell::getCurrent()->assertDoublesEqual(expected, actual, threshold, fileName, lineNumber, TestTerminatorWithoutExceptions()); -} - -void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* fileName, int lineNumber) -{ - UtestShell::getCurrent()->assertEquals(((expected) != (actual)), StringFrom(expected).asCharString(), StringFrom(actual).asCharString(), fileName, lineNumber, TestTerminatorWithoutExceptions()); -} - -void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* fileName, int lineNumber) -{ - UtestShell::getCurrent()->assertCstrEqual(expected, actual, fileName, lineNumber, TestTerminatorWithoutExceptions()); -} - -void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, int lineNumber) -{ - UtestShell::getCurrent()->fail(text, fileName, lineNumber, TestTerminatorWithoutExceptions()); -} - -void FAIL_C_LOCATION(const char* fileName, int lineNumber) -{ - UtestShell::getCurrent()->fail("", fileName, lineNumber, TestTerminatorWithoutExceptions()); -} - -void CHECK_C_LOCATION(int condition, const char* conditionString, const char* fileName, int lineNumber) -{ - UtestShell::getCurrent()->assertTrue(condition != 0, "CHECK_C", conditionString, fileName, lineNumber, TestTerminatorWithoutExceptions()); -} - -enum { NO_COUNTDOWN = -1, OUT_OF_MEMORRY = 0 }; -static int malloc_out_of_memory_counter = NO_COUNTDOWN; -static int malloc_count = 0; - -void cpputest_malloc_count_reset(void) -{ - malloc_count = 0; -} - -int cpputest_malloc_get_count() -{ - return malloc_count; -} - -void cpputest_malloc_set_out_of_memory() -{ - setCurrentMallocAllocator(NullUnknownAllocator::defaultAllocator()); -} - -void cpputest_malloc_set_not_out_of_memory() -{ - malloc_out_of_memory_counter = NO_COUNTDOWN; - setCurrentMallocAllocatorToDefault(); -} - -void cpputest_malloc_set_out_of_memory_countdown(int count) -{ - malloc_out_of_memory_counter = count; - if (malloc_out_of_memory_counter == OUT_OF_MEMORRY) - cpputest_malloc_set_out_of_memory(); -} - -void* cpputest_malloc(size_t size) -{ - return cpputest_malloc_location(size, "", 0); -} - -void* cpputest_calloc(size_t num, size_t size) -{ - return cpputest_calloc_location(num, size, "", 0); -} - -void* cpputest_realloc(void* ptr, size_t size) -{ - return cpputest_realloc_location(ptr, size, "", 0); -} - -void cpputest_free(void* buffer) -{ - cpputest_free_location(buffer, "", 0); -} - -static void countdown() -{ - if (malloc_out_of_memory_counter <= NO_COUNTDOWN) - return; - - if (malloc_out_of_memory_counter == OUT_OF_MEMORRY) - return; - - malloc_out_of_memory_counter--; - - if (malloc_out_of_memory_counter == OUT_OF_MEMORRY) - cpputest_malloc_set_out_of_memory(); -} - -void* cpputest_malloc_location(size_t size, const char* file, int 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) -{ - void* mem = cpputest_malloc_location(num * size, file, line); +/* + * 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 "CppUTest/TestMemoryAllocator.h" +#include "CppUTest/PlatformSpecificFunctions.h" +#include "CppUTest/TestHarness_c.h" + +extern "C" +{ + + +void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, const char* fileName, int lineNumber) +{ + UtestShell::getCurrent()->assertLongsEqual((long)expected, (long)actual, fileName, lineNumber, TestTerminatorWithoutExceptions()); +} + +void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* fileName, int lineNumber) +{ + UtestShell::getCurrent()->assertDoublesEqual(expected, actual, threshold, fileName, lineNumber, TestTerminatorWithoutExceptions()); +} + +void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* fileName, int lineNumber) +{ + UtestShell::getCurrent()->assertEquals(((expected) != (actual)), StringFrom(expected).asCharString(), StringFrom(actual).asCharString(), fileName, lineNumber, TestTerminatorWithoutExceptions()); +} + +void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* fileName, int lineNumber) +{ + UtestShell::getCurrent()->assertCstrEqual(expected, actual, fileName, lineNumber, TestTerminatorWithoutExceptions()); +} + +void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, int lineNumber) +{ + UtestShell::getCurrent()->fail(text, fileName, lineNumber, TestTerminatorWithoutExceptions()); +} + +void FAIL_C_LOCATION(const char* fileName, int lineNumber) +{ + UtestShell::getCurrent()->fail("", fileName, lineNumber, TestTerminatorWithoutExceptions()); +} + +void CHECK_C_LOCATION(int condition, const char* conditionString, const char* fileName, int lineNumber) +{ + UtestShell::getCurrent()->assertTrue(condition != 0, "CHECK_C", conditionString, fileName, lineNumber, TestTerminatorWithoutExceptions()); +} + +enum { NO_COUNTDOWN = -1, OUT_OF_MEMORRY = 0 }; +static int malloc_out_of_memory_counter = NO_COUNTDOWN; +static int malloc_count = 0; + +void cpputest_malloc_count_reset(void) +{ + malloc_count = 0; +} + +int cpputest_malloc_get_count() +{ + return malloc_count; +} + +void cpputest_malloc_set_out_of_memory() +{ + setCurrentMallocAllocator(NullUnknownAllocator::defaultAllocator()); +} + +void cpputest_malloc_set_not_out_of_memory() +{ + malloc_out_of_memory_counter = NO_COUNTDOWN; + setCurrentMallocAllocatorToDefault(); +} + +void cpputest_malloc_set_out_of_memory_countdown(int count) +{ + malloc_out_of_memory_counter = count; + if (malloc_out_of_memory_counter == OUT_OF_MEMORRY) + cpputest_malloc_set_out_of_memory(); +} + +void* cpputest_malloc(size_t size) +{ + return cpputest_malloc_location(size, "", 0); +} + +void* cpputest_calloc(size_t num, size_t size) +{ + return cpputest_calloc_location(num, size, "", 0); +} + +void* cpputest_realloc(void* ptr, size_t size) +{ + return cpputest_realloc_location(ptr, size, "", 0); +} + +void cpputest_free(void* buffer) +{ + cpputest_free_location(buffer, "", 0); +} + +static void countdown() +{ + if (malloc_out_of_memory_counter <= NO_COUNTDOWN) + return; + + if (malloc_out_of_memory_counter == OUT_OF_MEMORRY) + return; + + malloc_out_of_memory_counter--; + + if (malloc_out_of_memory_counter == OUT_OF_MEMORRY) + cpputest_malloc_set_out_of_memory(); +} + +void* cpputest_malloc_location(size_t size, const char* file, int 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) +{ + void* mem = cpputest_malloc_location(num * size, file, line); if (mem) - PlatformSpecificMemset(mem, 0, num*size); - return mem; -} - -void* cpputest_realloc_location(void* memory, size_t size, const char* file, int line) -{ - return cpputest_realloc_location_with_leak_detection(memory, size, file, line); -} - -void cpputest_free_location(void* buffer, const char* file, int line) -{ - cpputest_free_location_with_leak_detection(buffer, file, line); -} - -} + PlatformSpecificMemset(mem, 0, num*size); + return mem; +} + +void* cpputest_realloc_location(void* memory, size_t size, const char* file, int line) +{ + return cpputest_realloc_location_with_leak_detection(memory, size, file, line); +} + +void cpputest_free_location(void* buffer, const char* file, int line) +{ + cpputest_free_location_with_leak_detection(buffer, file, line); +} + +} diff --git a/src/CppUTest/TestMemoryAllocator.cpp b/src/CppUTest/TestMemoryAllocator.cpp index d5c4cf2c0..449591433 100644 --- a/src/CppUTest/TestMemoryAllocator.cpp +++ b/src/CppUTest/TestMemoryAllocator.cpp @@ -1,204 +1,204 @@ -/* - * 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/MemoryLeakDetector.h" - -static char* checkedMalloc(size_t size) -{ - char* mem = (char*) PlatformSpecificMalloc(size); - if (mem == 0) - FAIL("malloc returned null pointer"); - return mem; -} - -static TestMemoryAllocator* currentNewAllocator = 0; -static TestMemoryAllocator* currentNewArrayAllocator = 0; -static TestMemoryAllocator* currentMallocAllocator = 0; - -void setCurrentNewAllocator(TestMemoryAllocator* allocator) -{ - currentNewAllocator = allocator; -} - -TestMemoryAllocator* getCurrentNewAllocator() -{ - if (currentNewAllocator == 0) setCurrentNewAllocatorToDefault(); - return currentNewAllocator; -} - -void setCurrentNewAllocatorToDefault() -{ - currentNewAllocator = defaultNewAllocator(); -} - -TestMemoryAllocator* defaultNewAllocator() -{ - static TestMemoryAllocator allocator("Standard New Allocator", "new", "delete"); - return &allocator; -} - -void setCurrentNewArrayAllocator(TestMemoryAllocator* allocator) -{ - currentNewArrayAllocator = allocator; -} - -TestMemoryAllocator* getCurrentNewArrayAllocator() -{ - if (currentNewArrayAllocator == 0) setCurrentNewArrayAllocatorToDefault(); - return currentNewArrayAllocator; -} - -void setCurrentNewArrayAllocatorToDefault() -{ - currentNewArrayAllocator = defaultNewArrayAllocator(); -} - -TestMemoryAllocator* defaultNewArrayAllocator() -{ - static TestMemoryAllocator allocator("Standard New [] Allocator", "new []", "delete []"); - return &allocator; -} - -void setCurrentMallocAllocator(TestMemoryAllocator* allocator) -{ - currentMallocAllocator = allocator; -} - -TestMemoryAllocator* getCurrentMallocAllocator() -{ - if (currentMallocAllocator == 0) setCurrentMallocAllocatorToDefault(); - return currentMallocAllocator; -} - -void setCurrentMallocAllocatorToDefault() -{ - currentMallocAllocator = defaultMallocAllocator(); -} - -TestMemoryAllocator* defaultMallocAllocator() -{ - static TestMemoryAllocator allocator("Standard Malloc Allocator", "malloc", "free"); - return &allocator; -} - -///////////////////////////////////////////// - -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) -{ -} - -TestMemoryAllocator::~TestMemoryAllocator() -{ - hasBeenDestroyed_ = true; -} - -bool TestMemoryAllocator::hasBeenDestroyed() -{ - return hasBeenDestroyed_; -} - -bool TestMemoryAllocator::isOfEqualType(TestMemoryAllocator* allocator) -{ - return PlatformSpecificStrCmp(this->name(), allocator->name()) == 0; -} - -char* TestMemoryAllocator::allocMemoryLeakNode(size_t size) -{ - return alloc_memory(size, "MemoryLeakNode", 1); -} - -void TestMemoryAllocator::freeMemoryLeakNode(char* memory) -{ - free_memory(memory, "MemoryLeakNode", 1); -} - -char* TestMemoryAllocator::alloc_memory(size_t size, const char*, int) -{ - return checkedMalloc(size); -} - -void TestMemoryAllocator::free_memory(char* memory, const char*, int) -{ - PlatformSpecificFree(memory); -} -const char* TestMemoryAllocator::name() -{ - return name_; -} - -const char* TestMemoryAllocator::alloc_name() -{ - return alloc_name_; -} - -const char* TestMemoryAllocator::free_name() -{ - return free_name_; -} - -CrashOnAllocationAllocator::CrashOnAllocationAllocator() : allocationToCrashOn_(0) -{ -} - -void CrashOnAllocationAllocator::setNumberToCrashOn(unsigned allocationToCrashOn) -{ - allocationToCrashOn_ = allocationToCrashOn; -} - -char* CrashOnAllocationAllocator::alloc_memory(size_t size, const char* file, int line) -{ - if (MemoryLeakWarningPlugin::getGlobalDetector()->getCurrentAllocationNumber() == allocationToCrashOn_) - UT_CRASH(); - - return TestMemoryAllocator::alloc_memory(size, file, line); -} - - -char* NullUnknownAllocator::alloc_memory(size_t /*size*/, const char*, int) -{ - return 0; -} - -void NullUnknownAllocator::free_memory(char* /*memory*/, const char*, int) -{ -} - -NullUnknownAllocator::NullUnknownAllocator() - : TestMemoryAllocator("Null Allocator", "unknown", "unknown") -{ -} - - -TestMemoryAllocator* NullUnknownAllocator::defaultAllocator() -{ - static NullUnknownAllocator allocator; - return &allocator; -} +/* + * 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/MemoryLeakDetector.h" + +static char* checkedMalloc(size_t size) +{ + char* mem = (char*) PlatformSpecificMalloc(size); + if (mem == 0) + FAIL("malloc returned null pointer"); + return mem; +} + +static TestMemoryAllocator* currentNewAllocator = 0; +static TestMemoryAllocator* currentNewArrayAllocator = 0; +static TestMemoryAllocator* currentMallocAllocator = 0; + +void setCurrentNewAllocator(TestMemoryAllocator* allocator) +{ + currentNewAllocator = allocator; +} + +TestMemoryAllocator* getCurrentNewAllocator() +{ + if (currentNewAllocator == 0) setCurrentNewAllocatorToDefault(); + return currentNewAllocator; +} + +void setCurrentNewAllocatorToDefault() +{ + currentNewAllocator = defaultNewAllocator(); +} + +TestMemoryAllocator* defaultNewAllocator() +{ + static TestMemoryAllocator allocator("Standard New Allocator", "new", "delete"); + return &allocator; +} + +void setCurrentNewArrayAllocator(TestMemoryAllocator* allocator) +{ + currentNewArrayAllocator = allocator; +} + +TestMemoryAllocator* getCurrentNewArrayAllocator() +{ + if (currentNewArrayAllocator == 0) setCurrentNewArrayAllocatorToDefault(); + return currentNewArrayAllocator; +} + +void setCurrentNewArrayAllocatorToDefault() +{ + currentNewArrayAllocator = defaultNewArrayAllocator(); +} + +TestMemoryAllocator* defaultNewArrayAllocator() +{ + static TestMemoryAllocator allocator("Standard New [] Allocator", "new []", "delete []"); + return &allocator; +} + +void setCurrentMallocAllocator(TestMemoryAllocator* allocator) +{ + currentMallocAllocator = allocator; +} + +TestMemoryAllocator* getCurrentMallocAllocator() +{ + if (currentMallocAllocator == 0) setCurrentMallocAllocatorToDefault(); + return currentMallocAllocator; +} + +void setCurrentMallocAllocatorToDefault() +{ + currentMallocAllocator = defaultMallocAllocator(); +} + +TestMemoryAllocator* defaultMallocAllocator() +{ + static TestMemoryAllocator allocator("Standard Malloc Allocator", "malloc", "free"); + return &allocator; +} + +///////////////////////////////////////////// + +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) +{ +} + +TestMemoryAllocator::~TestMemoryAllocator() +{ + hasBeenDestroyed_ = true; +} + +bool TestMemoryAllocator::hasBeenDestroyed() +{ + return hasBeenDestroyed_; +} + +bool TestMemoryAllocator::isOfEqualType(TestMemoryAllocator* allocator) +{ + return PlatformSpecificStrCmp(this->name(), allocator->name()) == 0; +} + +char* TestMemoryAllocator::allocMemoryLeakNode(size_t size) +{ + return alloc_memory(size, "MemoryLeakNode", 1); +} + +void TestMemoryAllocator::freeMemoryLeakNode(char* memory) +{ + free_memory(memory, "MemoryLeakNode", 1); +} + +char* TestMemoryAllocator::alloc_memory(size_t size, const char*, int) +{ + return checkedMalloc(size); +} + +void TestMemoryAllocator::free_memory(char* memory, const char*, int) +{ + PlatformSpecificFree(memory); +} +const char* TestMemoryAllocator::name() +{ + return name_; +} + +const char* TestMemoryAllocator::alloc_name() +{ + return alloc_name_; +} + +const char* TestMemoryAllocator::free_name() +{ + return free_name_; +} + +CrashOnAllocationAllocator::CrashOnAllocationAllocator() : allocationToCrashOn_(0) +{ +} + +void CrashOnAllocationAllocator::setNumberToCrashOn(unsigned allocationToCrashOn) +{ + allocationToCrashOn_ = allocationToCrashOn; +} + +char* CrashOnAllocationAllocator::alloc_memory(size_t size, const char* file, int line) +{ + if (MemoryLeakWarningPlugin::getGlobalDetector()->getCurrentAllocationNumber() == allocationToCrashOn_) + UT_CRASH(); + + return TestMemoryAllocator::alloc_memory(size, file, line); +} + + +char* NullUnknownAllocator::alloc_memory(size_t /*size*/, const char*, int) +{ + return 0; +} + +void NullUnknownAllocator::free_memory(char* /*memory*/, const char*, int) +{ +} + +NullUnknownAllocator::NullUnknownAllocator() + : TestMemoryAllocator("Null Allocator", "unknown", "unknown") +{ +} + + +TestMemoryAllocator* NullUnknownAllocator::defaultAllocator() +{ + static NullUnknownAllocator allocator; + return &allocator; +} diff --git a/src/CppUTest/TestOutput.cpp b/src/CppUTest/TestOutput.cpp index 72941bf5a..38c362681 100644 --- a/src/CppUTest/TestOutput.cpp +++ b/src/CppUTest/TestOutput.cpp @@ -1,253 +1,253 @@ -/* - * 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/PlatformSpecificFunctions.h" - -TestOutput::WorkingEnvironment TestOutput::workingEnvironment_ = TestOutput::detectEnvironment; - -void TestOutput::setWorkingEnvironment(TestOutput::WorkingEnvironment workEnvironment) -{ - workingEnvironment_ = workEnvironment; -} - -TestOutput::WorkingEnvironment TestOutput::getWorkingEnvironment() -{ - if (workingEnvironment_ == TestOutput::detectEnvironment) - return PlatformSpecificGetWorkingEnvironment(); - return workingEnvironment_; -} - - -TestOutput::TestOutput() : - dotCount_(0), verbose_(false), progressIndication_(".") -{ -} - -TestOutput::~TestOutput() -{ -} - -void TestOutput::verbose() -{ - verbose_ = true; -} - -void TestOutput::print(const char* str) -{ - printBuffer(str); -} - -void TestOutput::print(long n) -{ - print(StringFrom(n).asCharString()); -} - -void TestOutput::printDouble(double d) -{ - print(StringFrom(d).asCharString()); -} - -void TestOutput::printHex(long n) -{ - print(HexStringFrom(n).asCharString()); -} - -TestOutput& operator<<(TestOutput& p, const char* s) -{ - p.print(s); - return p; -} - -TestOutput& operator<<(TestOutput& p, long int i) -{ - p.print(i); - return p; -} - -void TestOutput::printCurrentTestStarted(const UtestShell& test) -{ - if (verbose_) print(test.getFormattedName().asCharString()); -} - -void TestOutput::printCurrentTestEnded(const TestResult& res) -{ - if (verbose_) { - print(" - "); - print(res.getCurrentTestTotalExecutionTime()); - print(" ms\n"); - } - else { - printProgressIndicator(); - } -} - -void TestOutput::printProgressIndicator() -{ - print(progressIndication_); - if (++dotCount_ % 50 == 0) print("\n"); -} - -void TestOutput::setProgressIndicator(const char* indicator) -{ - progressIndication_ = indicator; -} - -void TestOutput::printTestsStarted() -{ -} - -void TestOutput::printCurrentGroupStarted(const UtestShell& /*test*/) -{ -} - -void TestOutput::printCurrentGroupEnded(const TestResult& /*res*/) -{ -} - -void TestOutput::flush() -{ -} - -void TestOutput::printTestsEnded(const TestResult& result) -{ - if (result.getFailureCount() > 0) { - print("\nErrors ("); - print(result.getFailureCount()); - print(" failures, "); - } - else { - print("\nOK ("); - } - print(result.getTestCount()); - print(" tests, "); - print(result.getRunCount()); - print(" ran, "); - print(result.getCheckCount()); - print(" checks, "); - print(result.getIgnoredCount()); - print(" ignored, "); - print(result.getFilteredOutCount()); - print(" filtered out, "); - print(result.getTotalExecutionTime()); - print(" ms)\n\n"); -} - -void TestOutput::printTestRun(int number, int total) -{ - if (total > 1) { - print("Test run "); - print(number); - print(" of "); - print(total); - print("\n"); - } -} - -void TestOutput::print(const TestFailure& failure) -{ - if (failure.isOutsideTestFile() || failure.isInHelperFunction()) - printFileAndLineForTestAndFailure(failure); - else - printFileAndLineForFailure(failure); - - printFailureMessage(failure.getMessage()); -} - -void TestOutput::printFileAndLineForTestAndFailure(const TestFailure& failure) -{ - printErrorInFileOnLineFormattedForWorkingEnvironment(failure.getTestFileName(), failure.getTestLineNumber()); - printFailureInTest(failure.getTestName()); - printErrorInFileOnLineFormattedForWorkingEnvironment(failure.getFileName(), failure.getFailureLineNumber()); -} - -void TestOutput::printFileAndLineForFailure(const TestFailure& failure) -{ - printErrorInFileOnLineFormattedForWorkingEnvironment(failure.getFileName(), failure.getFailureLineNumber()); - printFailureInTest(failure.getTestName()); -} - -void TestOutput::printFailureInTest(SimpleString testName) -{ - print(" Failure in "); - print(testName.asCharString()); -} - -void TestOutput::printFailureMessage(SimpleString reason) -{ - print("\n"); - print("\t"); - print(reason.asCharString()); - print("\n\n"); -} - -void TestOutput::printErrorInFileOnLineFormattedForWorkingEnvironment(SimpleString file, int lineNumber) -{ - if (TestOutput::getWorkingEnvironment() == TestOutput::vistualStudio) - printVistualStudioErrorInFileOnLine(file, lineNumber); - else - printEclipseErrorInFileOnLine(file, lineNumber); -} - -void TestOutput::printEclipseErrorInFileOnLine(SimpleString file, int lineNumber) -{ - print("\n"); - print(file.asCharString()); - print(":"); - print(lineNumber); - print(":"); - print(" error:"); -} - -void TestOutput::printVistualStudioErrorInFileOnLine(SimpleString file, int lineNumber) -{ - print("\n"); - print(file.asCharString()); - print("("); - print(lineNumber); - print("):"); - print(" error:"); -} - -void ConsoleTestOutput::printBuffer(const char* s) -{ - while (*s) { - PlatformSpecificPutchar(*s); - s++; - } - flush(); -} - -void ConsoleTestOutput::flush() -{ - PlatformSpecificFlush(); -} - -StringBufferTestOutput::~StringBufferTestOutput() -{ -} +/* + * 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/PlatformSpecificFunctions.h" + +TestOutput::WorkingEnvironment TestOutput::workingEnvironment_ = TestOutput::detectEnvironment; + +void TestOutput::setWorkingEnvironment(TestOutput::WorkingEnvironment workEnvironment) +{ + workingEnvironment_ = workEnvironment; +} + +TestOutput::WorkingEnvironment TestOutput::getWorkingEnvironment() +{ + if (workingEnvironment_ == TestOutput::detectEnvironment) + return PlatformSpecificGetWorkingEnvironment(); + return workingEnvironment_; +} + + +TestOutput::TestOutput() : + dotCount_(0), verbose_(false), progressIndication_(".") +{ +} + +TestOutput::~TestOutput() +{ +} + +void TestOutput::verbose() +{ + verbose_ = true; +} + +void TestOutput::print(const char* str) +{ + printBuffer(str); +} + +void TestOutput::print(long n) +{ + print(StringFrom(n).asCharString()); +} + +void TestOutput::printDouble(double d) +{ + print(StringFrom(d).asCharString()); +} + +void TestOutput::printHex(long n) +{ + print(HexStringFrom(n).asCharString()); +} + +TestOutput& operator<<(TestOutput& p, const char* s) +{ + p.print(s); + return p; +} + +TestOutput& operator<<(TestOutput& p, long int i) +{ + p.print(i); + return p; +} + +void TestOutput::printCurrentTestStarted(const UtestShell& test) +{ + if (verbose_) print(test.getFormattedName().asCharString()); +} + +void TestOutput::printCurrentTestEnded(const TestResult& res) +{ + if (verbose_) { + print(" - "); + print(res.getCurrentTestTotalExecutionTime()); + print(" ms\n"); + } + else { + printProgressIndicator(); + } +} + +void TestOutput::printProgressIndicator() +{ + print(progressIndication_); + if (++dotCount_ % 50 == 0) print("\n"); +} + +void TestOutput::setProgressIndicator(const char* indicator) +{ + progressIndication_ = indicator; +} + +void TestOutput::printTestsStarted() +{ +} + +void TestOutput::printCurrentGroupStarted(const UtestShell& /*test*/) +{ +} + +void TestOutput::printCurrentGroupEnded(const TestResult& /*res*/) +{ +} + +void TestOutput::flush() +{ +} + +void TestOutput::printTestsEnded(const TestResult& result) +{ + if (result.getFailureCount() > 0) { + print("\nErrors ("); + print(result.getFailureCount()); + print(" failures, "); + } + else { + print("\nOK ("); + } + print(result.getTestCount()); + print(" tests, "); + print(result.getRunCount()); + print(" ran, "); + print(result.getCheckCount()); + print(" checks, "); + print(result.getIgnoredCount()); + print(" ignored, "); + print(result.getFilteredOutCount()); + print(" filtered out, "); + print(result.getTotalExecutionTime()); + print(" ms)\n\n"); +} + +void TestOutput::printTestRun(int number, int total) +{ + if (total > 1) { + print("Test run "); + print(number); + print(" of "); + print(total); + print("\n"); + } +} + +void TestOutput::print(const TestFailure& failure) +{ + if (failure.isOutsideTestFile() || failure.isInHelperFunction()) + printFileAndLineForTestAndFailure(failure); + else + printFileAndLineForFailure(failure); + + printFailureMessage(failure.getMessage()); +} + +void TestOutput::printFileAndLineForTestAndFailure(const TestFailure& failure) +{ + printErrorInFileOnLineFormattedForWorkingEnvironment(failure.getTestFileName(), failure.getTestLineNumber()); + printFailureInTest(failure.getTestName()); + printErrorInFileOnLineFormattedForWorkingEnvironment(failure.getFileName(), failure.getFailureLineNumber()); +} + +void TestOutput::printFileAndLineForFailure(const TestFailure& failure) +{ + printErrorInFileOnLineFormattedForWorkingEnvironment(failure.getFileName(), failure.getFailureLineNumber()); + printFailureInTest(failure.getTestName()); +} + +void TestOutput::printFailureInTest(SimpleString testName) +{ + print(" Failure in "); + print(testName.asCharString()); +} + +void TestOutput::printFailureMessage(SimpleString reason) +{ + print("\n"); + print("\t"); + print(reason.asCharString()); + print("\n\n"); +} + +void TestOutput::printErrorInFileOnLineFormattedForWorkingEnvironment(SimpleString file, int lineNumber) +{ + if (TestOutput::getWorkingEnvironment() == TestOutput::vistualStudio) + printVistualStudioErrorInFileOnLine(file, lineNumber); + else + printEclipseErrorInFileOnLine(file, lineNumber); +} + +void TestOutput::printEclipseErrorInFileOnLine(SimpleString file, int lineNumber) +{ + print("\n"); + print(file.asCharString()); + print(":"); + print(lineNumber); + print(":"); + print(" error:"); +} + +void TestOutput::printVistualStudioErrorInFileOnLine(SimpleString file, int lineNumber) +{ + print("\n"); + print(file.asCharString()); + print("("); + print(lineNumber); + print("):"); + print(" error:"); +} + +void ConsoleTestOutput::printBuffer(const char* s) +{ + while (*s) { + PlatformSpecificPutchar(*s); + s++; + } + flush(); +} + +void ConsoleTestOutput::flush() +{ + PlatformSpecificFlush(); +} + +StringBufferTestOutput::~StringBufferTestOutput() +{ +} diff --git a/src/CppUTest/TestPlugin.cpp b/src/CppUTest/TestPlugin.cpp index 533993e0a..1a2c6ed51 100644 --- a/src/CppUTest/TestPlugin.cpp +++ b/src/CppUTest/TestPlugin.cpp @@ -1,173 +1,173 @@ -/* - * 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/TestPlugin.h" - -TestPlugin::TestPlugin(const SimpleString& name) : - next_(NullTestPlugin::instance()), name_(name), enabled_(true) -{ -} - -TestPlugin::TestPlugin(TestPlugin* next) : - next_(next), name_("null"), enabled_(true) -{ -} - -TestPlugin::~TestPlugin() -{ -} - -TestPlugin* TestPlugin::addPlugin(TestPlugin* plugin) -{ - next_ = plugin; - return this; -} - -void TestPlugin::runAllPreTestAction(UtestShell& test, TestResult& result) -{ - if (enabled_) preTestAction(test, result); - next_->runAllPreTestAction(test, result); -} - -void TestPlugin::runAllPostTestAction(UtestShell& test, TestResult& result) -{ - next_ ->runAllPostTestAction(test, result); - if (enabled_) postTestAction(test, result); -} - -bool TestPlugin::parseAllArguments(int ac, char** av, int index) -{ - return parseAllArguments(ac, const_cast (av), index); -} - -bool TestPlugin::parseAllArguments(int ac, const char** av, int index) -{ - if (parseArguments(ac, av, index)) return true; - if (next_) return next_->parseAllArguments(ac, av, index); - return false; -} - -const SimpleString& TestPlugin::getName() -{ - return name_; -} - -TestPlugin* TestPlugin::getPluginByName(const SimpleString& name) -{ - if (name == name_) return this; - if (next_) return next_->getPluginByName(name); - return (next_); -} - -TestPlugin* TestPlugin::getNext() -{ - return next_; -} -TestPlugin* TestPlugin::removePluginByName(const SimpleString& name) -{ - TestPlugin* removed = 0; - if (next_ && next_->getName() == name) { - removed = next_; - next_ = next_->next_; - } - return removed; -} - -void TestPlugin::disable() -{ - enabled_ = false; -} - -void TestPlugin::enable() -{ - enabled_ = true; -} - -bool TestPlugin::isEnabled() -{ - return enabled_; -} - -struct cpputest_pair -{ - void **orig; - void *orig_value; -}; - -//////// SetPlugin - -static int pointerTableIndex; -static cpputest_pair setlist[SetPointerPlugin::MAX_SET]; - -SetPointerPlugin::SetPointerPlugin(const SimpleString& name) : - TestPlugin(name) -{ - pointerTableIndex = 0; -} - -SetPointerPlugin::~SetPointerPlugin() -{ -} - -void CppUTestStore(void**function) -{ - if (pointerTableIndex >= SetPointerPlugin::MAX_SET) { - FAIL("Maximum number of function pointers installed!"); - } - setlist[pointerTableIndex].orig_value = *function; - setlist[pointerTableIndex].orig = function; - pointerTableIndex++; -} - -void SetPointerPlugin::postTestAction(UtestShell& /*test*/, TestResult& /*result*/) -{ - for (int i = pointerTableIndex - 1; i >= 0; i--) - *((void**) setlist[i].orig) = setlist[i].orig_value; - pointerTableIndex = 0; -} - -//////// NullPlugin - -NullTestPlugin::NullTestPlugin() : - TestPlugin(0) -{ -} - -NullTestPlugin* NullTestPlugin::instance() -{ - static NullTestPlugin _instance; - return &_instance; -} - -void NullTestPlugin::runAllPreTestAction(UtestShell&, TestResult&) -{ -} - -void NullTestPlugin::runAllPostTestAction(UtestShell&, TestResult&) -{ -} +/* + * 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/TestPlugin.h" + +TestPlugin::TestPlugin(const SimpleString& name) : + next_(NullTestPlugin::instance()), name_(name), enabled_(true) +{ +} + +TestPlugin::TestPlugin(TestPlugin* next) : + next_(next), name_("null"), enabled_(true) +{ +} + +TestPlugin::~TestPlugin() +{ +} + +TestPlugin* TestPlugin::addPlugin(TestPlugin* plugin) +{ + next_ = plugin; + return this; +} + +void TestPlugin::runAllPreTestAction(UtestShell& test, TestResult& result) +{ + if (enabled_) preTestAction(test, result); + next_->runAllPreTestAction(test, result); +} + +void TestPlugin::runAllPostTestAction(UtestShell& test, TestResult& result) +{ + next_ ->runAllPostTestAction(test, result); + if (enabled_) postTestAction(test, result); +} + +bool TestPlugin::parseAllArguments(int ac, char** av, int index) +{ + return parseAllArguments(ac, const_cast (av), index); +} + +bool TestPlugin::parseAllArguments(int ac, const char** av, int index) +{ + if (parseArguments(ac, av, index)) return true; + if (next_) return next_->parseAllArguments(ac, av, index); + return false; +} + +const SimpleString& TestPlugin::getName() +{ + return name_; +} + +TestPlugin* TestPlugin::getPluginByName(const SimpleString& name) +{ + if (name == name_) return this; + if (next_) return next_->getPluginByName(name); + return (next_); +} + +TestPlugin* TestPlugin::getNext() +{ + return next_; +} +TestPlugin* TestPlugin::removePluginByName(const SimpleString& name) +{ + TestPlugin* removed = 0; + if (next_ && next_->getName() == name) { + removed = next_; + next_ = next_->next_; + } + return removed; +} + +void TestPlugin::disable() +{ + enabled_ = false; +} + +void TestPlugin::enable() +{ + enabled_ = true; +} + +bool TestPlugin::isEnabled() +{ + return enabled_; +} + +struct cpputest_pair +{ + void **orig; + void *orig_value; +}; + +//////// SetPlugin + +static int pointerTableIndex; +static cpputest_pair setlist[SetPointerPlugin::MAX_SET]; + +SetPointerPlugin::SetPointerPlugin(const SimpleString& name) : + TestPlugin(name) +{ + pointerTableIndex = 0; +} + +SetPointerPlugin::~SetPointerPlugin() +{ +} + +void CppUTestStore(void**function) +{ + if (pointerTableIndex >= SetPointerPlugin::MAX_SET) { + FAIL("Maximum number of function pointers installed!"); + } + setlist[pointerTableIndex].orig_value = *function; + setlist[pointerTableIndex].orig = function; + pointerTableIndex++; +} + +void SetPointerPlugin::postTestAction(UtestShell& /*test*/, TestResult& /*result*/) +{ + for (int i = pointerTableIndex - 1; i >= 0; i--) + *((void**) setlist[i].orig) = setlist[i].orig_value; + pointerTableIndex = 0; +} + +//////// NullPlugin + +NullTestPlugin::NullTestPlugin() : + TestPlugin(0) +{ +} + +NullTestPlugin* NullTestPlugin::instance() +{ + static NullTestPlugin _instance; + return &_instance; +} + +void NullTestPlugin::runAllPreTestAction(UtestShell&, TestResult&) +{ +} + +void NullTestPlugin::runAllPostTestAction(UtestShell&, TestResult&) +{ +} diff --git a/src/CppUTest/TestRegistry.cpp b/src/CppUTest/TestRegistry.cpp index 28e8cda74..d656456cf 100644 --- a/src/CppUTest/TestRegistry.cpp +++ b/src/CppUTest/TestRegistry.cpp @@ -1,216 +1,216 @@ -/* - * 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/TestRegistry.h" - -TestRegistry::TestRegistry() : - tests_(&NullTestShell::instance()), firstPlugin_(NullTestPlugin::instance()), runInSeperateProcess_(false) -{ -} - -TestRegistry::~TestRegistry() -{ -} - -void TestRegistry::addTest(UtestShell *test) -{ - tests_ = test->addTest(tests_); -} - -void TestRegistry::runAllTests(TestResult& result) -{ - bool groupStart = true; - - result.testsStarted(); - for (UtestShell *test = tests_; !test->isNull(); test = test->getNext()) { - if (runInSeperateProcess_) test->setRunInSeperateProcess(); - - if (groupStart) { - result.currentGroupStarted(test); - groupStart = false; - } - - result.setProgressIndicator(test->getProgressIndicator()); - result.countTest(); - if (testShouldRun(test, result)) { - result.currentTestStarted(test); - test->runOneTest(firstPlugin_, result); - result.currentTestEnded(test); - } - - if (endOfGroup(test)) { - groupStart = true; - result.currentGroupEnded(test); - } - } - result.testsEnded(); -} - -bool TestRegistry::endOfGroup(UtestShell* test) -{ - return (test->isNull() || test->getGroup() != test->getNext()->getGroup()); -} - -int TestRegistry::countTests() -{ - return tests_->countTests(); -} - -TestRegistry* TestRegistry::currentRegistry_ = 0; - -TestRegistry* TestRegistry::getCurrentRegistry() -{ - static TestRegistry registry; - return (currentRegistry_ == 0) ? ®istry : currentRegistry_; -} - -void TestRegistry::setCurrentRegistry(TestRegistry* registry) -{ - currentRegistry_ = registry; -} - -void TestRegistry::unDoLastAddTest() -{ - tests_ = tests_->getNext(); - -} - -void TestRegistry::nameFilter(const TestFilter& f) -{ - nameFilter_ = f; -} - -void TestRegistry::groupFilter(const TestFilter& f) -{ - groupFilter_ = f; -} - -TestFilter TestRegistry::getGroupFilter() -{ - return groupFilter_; -} - -TestFilter TestRegistry::getNameFilter() -{ - return nameFilter_; -} - -void TestRegistry::setRunTestsInSeperateProcess() -{ - runInSeperateProcess_ = true; -} - - -bool TestRegistry::testShouldRun(UtestShell* test, TestResult& result) -{ - if (test->shouldRun(groupFilter_, nameFilter_)) return true; - else { - result.countFilteredOut(); - return false; - } -} - -void TestRegistry::resetPlugins() -{ - firstPlugin_ = NullTestPlugin::instance(); -} - -void TestRegistry::installPlugin(TestPlugin* plugin) -{ - firstPlugin_ = plugin->addPlugin(firstPlugin_); -} - -TestPlugin* TestRegistry::getFirstPlugin() -{ - return firstPlugin_; -} - -TestPlugin* TestRegistry::getPluginByName(const SimpleString& name) -{ - return firstPlugin_->getPluginByName(name); -} - -void TestRegistry::removePluginByName(const SimpleString& name) -{ - if (firstPlugin_->removePluginByName(name) == firstPlugin_) firstPlugin_ = firstPlugin_->getNext(); - if (firstPlugin_->getName() == name) firstPlugin_ = firstPlugin_->getNext(); - firstPlugin_->removePluginByName(name); -} - -int TestRegistry::countPlugins() -{ - int count = 0; - for (TestPlugin* plugin = firstPlugin_; plugin != NullTestPlugin::instance(); plugin = plugin->getNext()) - count++; - return count; -} - - -UtestShell* TestRegistry::getFirstTest() -{ - return tests_; -} - -UtestShell* TestRegistry::getLastTest() -{ - UtestShell* current = tests_; - while (!current->getNext()->isNull()) - current = current->getNext(); - return current; -} - -UtestShell* TestRegistry::getTestWithNext(UtestShell* test) -{ - UtestShell* current = tests_; - while (!current->getNext()->isNull() && current->getNext() != test) - current = current->getNext(); - return current; -} - -UtestShell* TestRegistry::findTestWithName(const SimpleString& name) -{ - UtestShell* current = tests_; - while (!current->isNull()) { - if (current->getName() == name) - return current; - current = current->getNext(); - } - return NULL; -} - -UtestShell* TestRegistry::findTestWithGroup(const SimpleString& group) -{ - UtestShell* current = tests_; - while (!current->isNull()) { - if (current->getGroup() == group) - return current; - current = current->getNext(); - } - return NULL; -} - +/* + * 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/TestRegistry.h" + +TestRegistry::TestRegistry() : + tests_(&NullTestShell::instance()), firstPlugin_(NullTestPlugin::instance()), runInSeperateProcess_(false) +{ +} + +TestRegistry::~TestRegistry() +{ +} + +void TestRegistry::addTest(UtestShell *test) +{ + tests_ = test->addTest(tests_); +} + +void TestRegistry::runAllTests(TestResult& result) +{ + bool groupStart = true; + + result.testsStarted(); + for (UtestShell *test = tests_; !test->isNull(); test = test->getNext()) { + if (runInSeperateProcess_) test->setRunInSeperateProcess(); + + if (groupStart) { + result.currentGroupStarted(test); + groupStart = false; + } + + result.setProgressIndicator(test->getProgressIndicator()); + result.countTest(); + if (testShouldRun(test, result)) { + result.currentTestStarted(test); + test->runOneTest(firstPlugin_, result); + result.currentTestEnded(test); + } + + if (endOfGroup(test)) { + groupStart = true; + result.currentGroupEnded(test); + } + } + result.testsEnded(); +} + +bool TestRegistry::endOfGroup(UtestShell* test) +{ + return (test->isNull() || test->getGroup() != test->getNext()->getGroup()); +} + +int TestRegistry::countTests() +{ + return tests_->countTests(); +} + +TestRegistry* TestRegistry::currentRegistry_ = 0; + +TestRegistry* TestRegistry::getCurrentRegistry() +{ + static TestRegistry registry; + return (currentRegistry_ == 0) ? ®istry : currentRegistry_; +} + +void TestRegistry::setCurrentRegistry(TestRegistry* registry) +{ + currentRegistry_ = registry; +} + +void TestRegistry::unDoLastAddTest() +{ + tests_ = tests_->getNext(); + +} + +void TestRegistry::nameFilter(const TestFilter& f) +{ + nameFilter_ = f; +} + +void TestRegistry::groupFilter(const TestFilter& f) +{ + groupFilter_ = f; +} + +TestFilter TestRegistry::getGroupFilter() +{ + return groupFilter_; +} + +TestFilter TestRegistry::getNameFilter() +{ + return nameFilter_; +} + +void TestRegistry::setRunTestsInSeperateProcess() +{ + runInSeperateProcess_ = true; +} + + +bool TestRegistry::testShouldRun(UtestShell* test, TestResult& result) +{ + if (test->shouldRun(groupFilter_, nameFilter_)) return true; + else { + result.countFilteredOut(); + return false; + } +} + +void TestRegistry::resetPlugins() +{ + firstPlugin_ = NullTestPlugin::instance(); +} + +void TestRegistry::installPlugin(TestPlugin* plugin) +{ + firstPlugin_ = plugin->addPlugin(firstPlugin_); +} + +TestPlugin* TestRegistry::getFirstPlugin() +{ + return firstPlugin_; +} + +TestPlugin* TestRegistry::getPluginByName(const SimpleString& name) +{ + return firstPlugin_->getPluginByName(name); +} + +void TestRegistry::removePluginByName(const SimpleString& name) +{ + if (firstPlugin_->removePluginByName(name) == firstPlugin_) firstPlugin_ = firstPlugin_->getNext(); + if (firstPlugin_->getName() == name) firstPlugin_ = firstPlugin_->getNext(); + firstPlugin_->removePluginByName(name); +} + +int TestRegistry::countPlugins() +{ + int count = 0; + for (TestPlugin* plugin = firstPlugin_; plugin != NullTestPlugin::instance(); plugin = plugin->getNext()) + count++; + return count; +} + + +UtestShell* TestRegistry::getFirstTest() +{ + return tests_; +} + +UtestShell* TestRegistry::getLastTest() +{ + UtestShell* current = tests_; + while (!current->getNext()->isNull()) + current = current->getNext(); + return current; +} + +UtestShell* TestRegistry::getTestWithNext(UtestShell* test) +{ + UtestShell* current = tests_; + while (!current->getNext()->isNull() && current->getNext() != test) + current = current->getNext(); + return current; +} + +UtestShell* TestRegistry::findTestWithName(const SimpleString& name) +{ + UtestShell* current = tests_; + while (!current->isNull()) { + if (current->getName() == name) + return current; + current = current->getNext(); + } + return NULL; +} + +UtestShell* TestRegistry::findTestWithGroup(const SimpleString& group) +{ + UtestShell* current = tests_; + while (!current->isNull()) { + if (current->getGroup() == group) + return current; + current = current->getNext(); + } + return NULL; +} + diff --git a/src/CppUTest/TestResult.cpp b/src/CppUTest/TestResult.cpp index a98e683c2..5a14a8c30 100644 --- a/src/CppUTest/TestResult.cpp +++ b/src/CppUTest/TestResult.cpp @@ -1,142 +1,142 @@ -/* - * 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/TestResult.h" -#include "CppUTest/TestFailure.h" -#include "CppUTest/TestOutput.h" -#include "CppUTest/PlatformSpecificFunctions.h" - -TestResult::TestResult(TestOutput& p) : - output_(p), testCount_(0), runCount_(0), checkCount_(0), failureCount_(0), filteredOutCount_(0), ignoredCount_(0), totalExecutionTime_(0), timeStarted_(0), currentTestTimeStarted_(0), - currentTestTotalExecutionTime_(0), currentGroupTimeStarted_(0), currentGroupTotalExecutionTime_(0) -{ -} - -void TestResult::setProgressIndicator(const char* indicator) -{ - output_.setProgressIndicator(indicator); -} - -TestResult::~TestResult() -{ -} - -void TestResult::currentGroupStarted(UtestShell* test) -{ - output_.printCurrentGroupStarted(*test); - currentGroupTimeStarted_ = GetPlatformSpecificTimeInMillis(); -} - -void TestResult::currentGroupEnded(UtestShell* /*test*/) -{ - currentGroupTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentGroupTimeStarted_; - output_.printCurrentGroupEnded(*this); -} - -void TestResult::currentTestStarted(UtestShell* test) -{ - output_.printCurrentTestStarted(*test); - currentTestTimeStarted_ = GetPlatformSpecificTimeInMillis(); -} - -void TestResult::print(const char* text) -{ - output_.print(text); -} - -void TestResult::currentTestEnded(UtestShell* /*test*/) -{ - currentTestTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentTestTimeStarted_; - output_.printCurrentTestEnded(*this); - -} - -void TestResult::addFailure(const TestFailure& failure) -{ - output_.print(failure); - failureCount_++; -} - -void TestResult::countTest() -{ - testCount_++; -} - -void TestResult::countRun() -{ - runCount_++; -} - -void TestResult::countCheck() -{ - checkCount_++; -} - -void TestResult::countFilteredOut() -{ - filteredOutCount_++; -} - -void TestResult::countIgnored() -{ - ignoredCount_++; -} - -void TestResult::testsStarted() -{ - timeStarted_ = GetPlatformSpecificTimeInMillis(); - output_.printTestsStarted(); -} - -void TestResult::testsEnded() -{ - long timeEnded = GetPlatformSpecificTimeInMillis(); - totalExecutionTime_ = timeEnded - timeStarted_; - output_.printTestsEnded(*this); -} - -long TestResult::getTotalExecutionTime() const -{ - return totalExecutionTime_; -} - -void TestResult::setTotalExecutionTime(long exTime) -{ - totalExecutionTime_ = exTime; -} - -long TestResult::getCurrentTestTotalExecutionTime() const -{ - return currentTestTotalExecutionTime_; -} - -long TestResult::getCurrentGroupTotalExecutionTime() const -{ - return currentGroupTotalExecutionTime_; -} - +/* + * 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/TestResult.h" +#include "CppUTest/TestFailure.h" +#include "CppUTest/TestOutput.h" +#include "CppUTest/PlatformSpecificFunctions.h" + +TestResult::TestResult(TestOutput& p) : + output_(p), testCount_(0), runCount_(0), checkCount_(0), failureCount_(0), filteredOutCount_(0), ignoredCount_(0), totalExecutionTime_(0), timeStarted_(0), currentTestTimeStarted_(0), + currentTestTotalExecutionTime_(0), currentGroupTimeStarted_(0), currentGroupTotalExecutionTime_(0) +{ +} + +void TestResult::setProgressIndicator(const char* indicator) +{ + output_.setProgressIndicator(indicator); +} + +TestResult::~TestResult() +{ +} + +void TestResult::currentGroupStarted(UtestShell* test) +{ + output_.printCurrentGroupStarted(*test); + currentGroupTimeStarted_ = GetPlatformSpecificTimeInMillis(); +} + +void TestResult::currentGroupEnded(UtestShell* /*test*/) +{ + currentGroupTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentGroupTimeStarted_; + output_.printCurrentGroupEnded(*this); +} + +void TestResult::currentTestStarted(UtestShell* test) +{ + output_.printCurrentTestStarted(*test); + currentTestTimeStarted_ = GetPlatformSpecificTimeInMillis(); +} + +void TestResult::print(const char* text) +{ + output_.print(text); +} + +void TestResult::currentTestEnded(UtestShell* /*test*/) +{ + currentTestTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentTestTimeStarted_; + output_.printCurrentTestEnded(*this); + +} + +void TestResult::addFailure(const TestFailure& failure) +{ + output_.print(failure); + failureCount_++; +} + +void TestResult::countTest() +{ + testCount_++; +} + +void TestResult::countRun() +{ + runCount_++; +} + +void TestResult::countCheck() +{ + checkCount_++; +} + +void TestResult::countFilteredOut() +{ + filteredOutCount_++; +} + +void TestResult::countIgnored() +{ + ignoredCount_++; +} + +void TestResult::testsStarted() +{ + timeStarted_ = GetPlatformSpecificTimeInMillis(); + output_.printTestsStarted(); +} + +void TestResult::testsEnded() +{ + long timeEnded = GetPlatformSpecificTimeInMillis(); + totalExecutionTime_ = timeEnded - timeStarted_; + output_.printTestsEnded(*this); +} + +long TestResult::getTotalExecutionTime() const +{ + return totalExecutionTime_; +} + +void TestResult::setTotalExecutionTime(long exTime) +{ + totalExecutionTime_ = exTime; +} + +long TestResult::getCurrentTestTotalExecutionTime() const +{ + return currentTestTotalExecutionTime_; +} + +long TestResult::getCurrentGroupTotalExecutionTime() const +{ + return currentGroupTotalExecutionTime_; +} + diff --git a/src/CppUTestExt/OrderedTest.cpp b/src/CppUTestExt/OrderedTest.cpp index 729639412..08ce41f2a 100644 --- a/src/CppUTestExt/OrderedTest.cpp +++ b/src/CppUTestExt/OrderedTest.cpp @@ -1,132 +1,132 @@ -/* - * 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/TestRegistry.h" -#include "CppUTestExt/OrderedTest.h" - -OrderedTestShell* OrderedTestShell::_orderedTestsHead = 0; - -OrderedTestShell::OrderedTestShell() : - _nextOrderedTest(0), _level(0) -{ -} - -OrderedTestShell::~OrderedTestShell() -{ -} - -int OrderedTestShell::getLevel() -{ - return _level; -} - -void OrderedTestShell::setLevel(int level) -{ - _level = level; -} - -void OrderedTestShell::setOrderedTestHead(OrderedTestShell* test) -{ - _orderedTestsHead = test; -} - -OrderedTestShell* OrderedTestShell::getOrderedTestHead() -{ - return _orderedTestsHead; -} - -bool OrderedTestShell::firstOrderedTest() -{ - return (getOrderedTestHead() == 0); -} - -OrderedTestShell* OrderedTestShell::addOrderedTest(OrderedTestShell* test) -{ - UtestShell::addTest(test); - _nextOrderedTest = test; - return this; -} - -void OrderedTestShell::addOrderedTestToHead(OrderedTestShell* test) -{ - TestRegistry *reg = TestRegistry::getCurrentRegistry(); - - if (reg->getFirstTest()->isNull() || getOrderedTestHead() - == reg->getFirstTest()) reg->addTest(test); - else reg->getTestWithNext(getOrderedTestHead())->addTest(test); - - test->_nextOrderedTest = getOrderedTestHead(); - setOrderedTestHead(test); -} - -OrderedTestShell* OrderedTestShell::getNextOrderedTest() -{ - return _nextOrderedTest; -} - -OrderedTestInstaller::OrderedTestInstaller(OrderedTestShell& test, - const char* groupName, const char* testName, const char* fileName, - int lineNumber, int level) -{ - test.setTestName(testName); - test.setGroupName(groupName); - test.setFileName(fileName); - test.setLineNumber(lineNumber); - test.setLevel(level); - - if (OrderedTestShell::firstOrderedTest()) OrderedTestShell::addOrderedTestToHead(&test); - else addOrderedTestInOrder(&test); -} - -void OrderedTestInstaller::addOrderedTestInOrder(OrderedTestShell* test) -{ - if (test->getLevel() < OrderedTestShell::getOrderedTestHead()->getLevel()) OrderedTestShell::addOrderedTestToHead( - test); - else addOrderedTestInOrderNotAtHeadPosition(test); -} - -void OrderedTestInstaller::addOrderedTestInOrderNotAtHeadPosition( - OrderedTestShell* test) -{ - OrderedTestShell* current = OrderedTestShell::getOrderedTestHead(); - while (current->getNextOrderedTest()) { - - if (current->getNextOrderedTest()->getLevel() > test->getLevel()) { - test->addOrderedTest(current->getNextOrderedTest()); - current->addOrderedTest(test); - return; - } - current = current->getNextOrderedTest(); - } - test->addOrderedTest(current->getNextOrderedTest()); - current->addOrderedTest(test); -} - -OrderedTestInstaller::~OrderedTestInstaller() -{ -} +/* + * 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/TestRegistry.h" +#include "CppUTestExt/OrderedTest.h" + +OrderedTestShell* OrderedTestShell::_orderedTestsHead = 0; + +OrderedTestShell::OrderedTestShell() : + _nextOrderedTest(0), _level(0) +{ +} + +OrderedTestShell::~OrderedTestShell() +{ +} + +int OrderedTestShell::getLevel() +{ + return _level; +} + +void OrderedTestShell::setLevel(int level) +{ + _level = level; +} + +void OrderedTestShell::setOrderedTestHead(OrderedTestShell* test) +{ + _orderedTestsHead = test; +} + +OrderedTestShell* OrderedTestShell::getOrderedTestHead() +{ + return _orderedTestsHead; +} + +bool OrderedTestShell::firstOrderedTest() +{ + return (getOrderedTestHead() == 0); +} + +OrderedTestShell* OrderedTestShell::addOrderedTest(OrderedTestShell* test) +{ + UtestShell::addTest(test); + _nextOrderedTest = test; + return this; +} + +void OrderedTestShell::addOrderedTestToHead(OrderedTestShell* test) +{ + TestRegistry *reg = TestRegistry::getCurrentRegistry(); + + if (reg->getFirstTest()->isNull() || getOrderedTestHead() + == reg->getFirstTest()) reg->addTest(test); + else reg->getTestWithNext(getOrderedTestHead())->addTest(test); + + test->_nextOrderedTest = getOrderedTestHead(); + setOrderedTestHead(test); +} + +OrderedTestShell* OrderedTestShell::getNextOrderedTest() +{ + return _nextOrderedTest; +} + +OrderedTestInstaller::OrderedTestInstaller(OrderedTestShell& test, + const char* groupName, const char* testName, const char* fileName, + int lineNumber, int level) +{ + test.setTestName(testName); + test.setGroupName(groupName); + test.setFileName(fileName); + test.setLineNumber(lineNumber); + test.setLevel(level); + + if (OrderedTestShell::firstOrderedTest()) OrderedTestShell::addOrderedTestToHead(&test); + else addOrderedTestInOrder(&test); +} + +void OrderedTestInstaller::addOrderedTestInOrder(OrderedTestShell* test) +{ + if (test->getLevel() < OrderedTestShell::getOrderedTestHead()->getLevel()) OrderedTestShell::addOrderedTestToHead( + test); + else addOrderedTestInOrderNotAtHeadPosition(test); +} + +void OrderedTestInstaller::addOrderedTestInOrderNotAtHeadPosition( + OrderedTestShell* test) +{ + OrderedTestShell* current = OrderedTestShell::getOrderedTestHead(); + while (current->getNextOrderedTest()) { + + if (current->getNextOrderedTest()->getLevel() > test->getLevel()) { + test->addOrderedTest(current->getNextOrderedTest()); + current->addOrderedTest(test); + return; + } + current = current->getNextOrderedTest(); + } + test->addOrderedTest(current->getNextOrderedTest()); + current->addOrderedTest(test); +} + +OrderedTestInstaller::~OrderedTestInstaller() +{ +} diff --git a/src/Platforms/Gcc/UtestPlatform.cpp b/src/Platforms/Gcc/UtestPlatform.cpp index 7d825a526..c5ed75af3 100644 --- a/src/Platforms/Gcc/UtestPlatform.cpp +++ b/src/Platforms/Gcc/UtestPlatform.cpp @@ -1,276 +1,276 @@ -/* - * 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 - -#include "CppUTest/TestRegistry.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifndef __MINGW32__ -#include -#endif - -#include "CppUTest/PlatformSpecificFunctions.h" - -static jmp_buf test_exit_jmp_buf[10]; -static int jmp_buf_index = 0; - -void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) -{ -#ifdef __MINGW32__ - printf("-p doesn't work on MinGW as it is lacking fork. Running inside the process\b"); - shell->runOneTest(plugin, *result); -#else - - int info; - pid_t pid = fork(); - - if (pid) { - wait(&info); - if (WIFEXITED(info) && WEXITSTATUS(info) > result->getFailureCount()) - result->addFailure(TestFailure(shell, "failed in seperate process")); - else if (!WIFEXITED(info)) - result->addFailure(TestFailure(shell, "failed in seperate process")); - } - else { - shell->runOneTest(plugin, *result); - exit(result->getFailureCount() ); - } -#endif -} - -TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() -{ - return TestOutput::eclipse; -} - - -extern "C" { - -int PlatformSpecificSetJmp(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; -} - -/* - * MacOSX clang 3.0 doesn't seem to recognize longjmp and thus complains about __no_return_. - * 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__ -#endif -void PlatformSpecificLongJmp() -{ - jmp_buf_index--; - longjmp(test_exit_jmp_buf[jmp_buf_index], 1); -} - -void PlatformSpecificRestoreJumpBuffer() -{ - jmp_buf_index--; -} - -///////////// Time in millis - -static long TimeInMillisImplementation() -{ - struct timeval tv; - struct timezone tz; - gettimeofday(&tv, &tz); - return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001); -} - -static long (*timeInMillisFp) () = TimeInMillisImplementation; - -long GetPlatformSpecificTimeInMillis() -{ - return timeInMillisFp(); -} - -void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) -{ - timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; -} - -///////////// Time in String - -static const char* TimeStringImplementation() -{ - time_t tm = time(NULL); - static char dateTime[80]; - struct tm *tmp = localtime(&tm); - strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp); - return dateTime; -} - -static const char* (*timeStringFp) () = TimeStringImplementation; - -const char* GetPlatformSpecificTimeString() -{ - return timeStringFp(); -} - -void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) -{ - timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; -} - -int PlatformSpecificAtoI(const char*str) -{ - return atoi(str); -} - -size_t PlatformSpecificStrLen(const char* str) -{ - return strlen(str); -} - -char* PlatformSpecificStrCat(char* s1, const char* s2) -{ - return strcat(s1, s2); -} - -char* PlatformSpecificStrCpy(char* s1, const char* s2) -{ - return strcpy(s1, s2); -} - -char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) -{ - return strncpy(s1, s2, size); -} - -int PlatformSpecificStrCmp(const char* s1, const char* s2) -{ - return strcmp(s1, s2); -} - -int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) -{ - return strncmp(s1, s2, size); -} -char* PlatformSpecificStrStr(const char* s1, const char* s2) -{ - return (char*) strstr(s1, s2); -} - -/* Wish we could add an attribute to the format for discovering mis-use... but the __attribute__(format) seems to not work on va_list */ -#ifdef __clang__ -#pragma clang diagnostic ignored "-Wformat-nonliteral" -#endif - -int PlatformSpecificVSNprintf(char *str, size_t size, const char* format, va_list args) -{ - return vsnprintf( str, size, format, args); -} - -char PlatformSpecificToLower(char c) -{ - return (char) tolower((char) c); -} - -PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) -{ - return fopen(filename, flag); -} - - -void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) -{ - fputs(str, (FILE*)file); -} - -void PlatformSpecificFClose(PlatformSpecificFile file) -{ - fclose((FILE*)file); -} - -void PlatformSpecificFlush() -{ - fflush(stdout); -} - -int PlatformSpecificPutchar(int c) -{ - return putchar(c); -} - -void* PlatformSpecificMalloc(size_t size) -{ - return malloc(size); -} - -void* PlatformSpecificRealloc (void* memory, size_t size) -{ - return realloc(memory, size); -} - -void PlatformSpecificFree(void* memory) -{ - free(memory); -} - -void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) -{ - return memcpy(s1, s2, size); -} - -void* PlatformSpecificMemset(void* mem, int c, size_t size) -{ - return memset(mem, c, size); -} - - -double PlatformSpecificFabs(double d) -{ - return fabs(d); -} - -int PlatformSpecificIsNan(double d) -{ - return isnan((float)d); -} - -} +/* + * 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 + +#include "CppUTest/TestRegistry.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef __MINGW32__ +#include +#endif + +#include "CppUTest/PlatformSpecificFunctions.h" + +static jmp_buf test_exit_jmp_buf[10]; +static int jmp_buf_index = 0; + +void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) +{ +#ifdef __MINGW32__ + printf("-p doesn't work on MinGW as it is lacking fork. Running inside the process\b"); + shell->runOneTest(plugin, *result); +#else + + int info; + pid_t pid = fork(); + + if (pid) { + wait(&info); + if (WIFEXITED(info) && WEXITSTATUS(info) > result->getFailureCount()) + result->addFailure(TestFailure(shell, "failed in seperate process")); + else if (!WIFEXITED(info)) + result->addFailure(TestFailure(shell, "failed in seperate process")); + } + else { + shell->runOneTest(plugin, *result); + exit(result->getFailureCount() ); + } +#endif +} + +TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() +{ + return TestOutput::eclipse; +} + + +extern "C" { + +int PlatformSpecificSetJmp(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; +} + +/* + * MacOSX clang 3.0 doesn't seem to recognize longjmp and thus complains about __no_return_. + * 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__ +#endif +void PlatformSpecificLongJmp() +{ + jmp_buf_index--; + longjmp(test_exit_jmp_buf[jmp_buf_index], 1); +} + +void PlatformSpecificRestoreJumpBuffer() +{ + jmp_buf_index--; +} + +///////////// Time in millis + +static long TimeInMillisImplementation() +{ + struct timeval tv; + struct timezone tz; + gettimeofday(&tv, &tz); + return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001); +} + +static long (*timeInMillisFp) () = TimeInMillisImplementation; + +long GetPlatformSpecificTimeInMillis() +{ + return timeInMillisFp(); +} + +void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) +{ + timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; +} + +///////////// Time in String + +static const char* TimeStringImplementation() +{ + time_t tm = time(NULL); + static char dateTime[80]; + struct tm *tmp = localtime(&tm); + strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp); + return dateTime; +} + +static const char* (*timeStringFp) () = TimeStringImplementation; + +const char* GetPlatformSpecificTimeString() +{ + return timeStringFp(); +} + +void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) +{ + timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; +} + +int PlatformSpecificAtoI(const char*str) +{ + return atoi(str); +} + +size_t PlatformSpecificStrLen(const char* str) +{ + return strlen(str); +} + +char* PlatformSpecificStrCat(char* s1, const char* s2) +{ + return strcat(s1, s2); +} + +char* PlatformSpecificStrCpy(char* s1, const char* s2) +{ + return strcpy(s1, s2); +} + +char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) +{ + return strncpy(s1, s2, size); +} + +int PlatformSpecificStrCmp(const char* s1, const char* s2) +{ + return strcmp(s1, s2); +} + +int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) +{ + return strncmp(s1, s2, size); +} +char* PlatformSpecificStrStr(const char* s1, const char* s2) +{ + return (char*) strstr(s1, s2); +} + +/* Wish we could add an attribute to the format for discovering mis-use... but the __attribute__(format) seems to not work on va_list */ +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wformat-nonliteral" +#endif + +int PlatformSpecificVSNprintf(char *str, size_t size, const char* format, va_list args) +{ + return vsnprintf( str, size, format, args); +} + +char PlatformSpecificToLower(char c) +{ + return (char) tolower((char) c); +} + +PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) +{ + return fopen(filename, flag); +} + + +void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) +{ + fputs(str, (FILE*)file); +} + +void PlatformSpecificFClose(PlatformSpecificFile file) +{ + fclose((FILE*)file); +} + +void PlatformSpecificFlush() +{ + fflush(stdout); +} + +int PlatformSpecificPutchar(int c) +{ + return putchar(c); +} + +void* PlatformSpecificMalloc(size_t size) +{ + return malloc(size); +} + +void* PlatformSpecificRealloc (void* memory, size_t size) +{ + return realloc(memory, size); +} + +void PlatformSpecificFree(void* memory) +{ + free(memory); +} + +void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) +{ + return memcpy(s1, s2, size); +} + +void* PlatformSpecificMemset(void* mem, int c, size_t size) +{ + return memset(mem, c, size); +} + + +double PlatformSpecificFabs(double d) +{ + return fabs(d); +} + +int PlatformSpecificIsNan(double d) +{ + return isnan((float)d); +} + +} diff --git a/src/Platforms/GccNoStdC/UtestPlatform.cpp b/src/Platforms/GccNoStdC/UtestPlatform.cpp index d95fc4959..c040a48f6 100644 --- a/src/Platforms/GccNoStdC/UtestPlatform.cpp +++ b/src/Platforms/GccNoStdC/UtestPlatform.cpp @@ -1,271 +1,271 @@ -/* - * 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" -#undef malloc -#undef free -#undef calloc -#undef realloc - -#include "CppUTest/TestRegistry.h" -#include "CppUTest/PlatformSpecificFunctions.h" - -int PlatformSpecificSetJmp(void (*function) (void* data), void* data) -{ - (void) data; - (void) function; - /* To be implemented */ - return 0; -} - -void PlatformSpecificLongJmp() -{ - /* To be implemented */ -} - -void PlatformSpecificRestoreJumpBuffer() -{ - /* To be implemented */ -} - - -void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) -{ - (void) shell; - (void) plugin; - (void) result; - /* To be implemented */ -} - -long GetPlatformSpecificTimeInMillis() -{ - /* To be implemented */ - return 0; -} - -void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) -{ - (void) platformSpecific; -} - -TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() -{ - return TestOutput::eclipse; -} - -///////////// Time in String - -const char* GetPlatformSpecificTimeString() -{ - /* To be implemented */ - return NULL; -} - -void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) -{ - /* To be implemented */ - (void) platformMethod; -} - -int PlatformSpecificAtoI(const char*str) -{ - /* To be implemented */ - (void) str; - return 0; -} - -size_t PlatformSpecificStrLen(const char* str) -{ - /* To be implemented */ - (void) str; - return 0; -} - -char* PlatformSpecificStrCat(char* s1, const char* s2) -{ - /* To be implemented */ - (void) s1; - (void) s2; - return NULL; -} - -char* PlatformSpecificStrCpy(char* s1, const char* s2) -{ - /* To be implemented */ - (void) s1; - (void) s2; - return NULL; -} - -char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) -{ - /* To be implemented */ - (void) s1; - (void) s2; - (void) size; - return NULL; -} - -int PlatformSpecificStrCmp(const char* s1, const char* s2) -{ - /* To be implemented */ - (void) s1; - (void) s2; - return 0; -} - -int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) -{ - /* To be implemented */ - (void) s1; - (void) s2; - (void) size; - return 0; -} - -char* PlatformSpecificStrStr(const char* s1, const char* s2) -{ - /* To be implemented */ - (void) s1; - (void) s2; - return NULL; -} - -int PlatformSpecificVSNprintf(char *str, size_t size, const char* format, va_list args) -{ - /* To be implemented */ - (void) size; - (void) args; - (void) format; - (void) args; - (void) str; - return 0; -} - -char PlatformSpecificToLower(char c) -{ - /* To be implemented */ - (void) c; - return 0; -} - -PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) -{ - /* To be implemented */ - (void) filename; - (void) flag; - return NULL; -} - - -void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) -{ - /* To be implemented */ - (void) str; - (void) file; -} - -void PlatformSpecificFClose(PlatformSpecificFile file) -{ - /* To be implemented */ - (void) file; -} - -void PlatformSpecificFlush() -{ - /* To be implemented */ -} - -int PlatformSpecificPutchar(int c) -{ - /* To be implemented */ - (void) c; - return 0; -} - -void* PlatformSpecificMalloc(size_t size) -{ - /* To be implemented */ - (void) size; - return NULL; -} - -void* PlatformSpecificRealloc (void* memory, size_t size) -{ - /* To be implemented */ - (void) memory; - (void) size; - return NULL; -} - -void PlatformSpecificFree(void* memory) -{ - /* To be implemented */ - (void) memory; -} - -void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) -{ - /* To be implemented */ - (void) size; - (void) s1; - (void) s2; - return NULL; -} - -void* PlatformSpecificMemset(void* mem, int c, size_t size) -{ - /* To be implemented */ - (void) mem; - (void) c; - (void) size; - return NULL; -} - -double PlatformSpecificFabs(double d) -{ - /* To be implemented */ - (void) d; - return 0.0; -} - -int PlatformSpecificIsNan(double d) -{ - /* To be implemented */ - (void) d; - return 0; -} - -void* malloc(size_t) -{ - return NULL; -} - -void free(void *) -{ -} - +/* + * 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" +#undef malloc +#undef free +#undef calloc +#undef realloc + +#include "CppUTest/TestRegistry.h" +#include "CppUTest/PlatformSpecificFunctions.h" + +int PlatformSpecificSetJmp(void (*function) (void* data), void* data) +{ + (void) data; + (void) function; + /* To be implemented */ + return 0; +} + +void PlatformSpecificLongJmp() +{ + /* To be implemented */ +} + +void PlatformSpecificRestoreJumpBuffer() +{ + /* To be implemented */ +} + + +void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) +{ + (void) shell; + (void) plugin; + (void) result; + /* To be implemented */ +} + +long GetPlatformSpecificTimeInMillis() +{ + /* To be implemented */ + return 0; +} + +void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) +{ + (void) platformSpecific; +} + +TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() +{ + return TestOutput::eclipse; +} + +///////////// Time in String + +const char* GetPlatformSpecificTimeString() +{ + /* To be implemented */ + return NULL; +} + +void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) +{ + /* To be implemented */ + (void) platformMethod; +} + +int PlatformSpecificAtoI(const char*str) +{ + /* To be implemented */ + (void) str; + return 0; +} + +size_t PlatformSpecificStrLen(const char* str) +{ + /* To be implemented */ + (void) str; + return 0; +} + +char* PlatformSpecificStrCat(char* s1, const char* s2) +{ + /* To be implemented */ + (void) s1; + (void) s2; + return NULL; +} + +char* PlatformSpecificStrCpy(char* s1, const char* s2) +{ + /* To be implemented */ + (void) s1; + (void) s2; + return NULL; +} + +char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) +{ + /* To be implemented */ + (void) s1; + (void) s2; + (void) size; + return NULL; +} + +int PlatformSpecificStrCmp(const char* s1, const char* s2) +{ + /* To be implemented */ + (void) s1; + (void) s2; + return 0; +} + +int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) +{ + /* To be implemented */ + (void) s1; + (void) s2; + (void) size; + return 0; +} + +char* PlatformSpecificStrStr(const char* s1, const char* s2) +{ + /* To be implemented */ + (void) s1; + (void) s2; + return NULL; +} + +int PlatformSpecificVSNprintf(char *str, size_t size, const char* format, va_list args) +{ + /* To be implemented */ + (void) size; + (void) args; + (void) format; + (void) args; + (void) str; + return 0; +} + +char PlatformSpecificToLower(char c) +{ + /* To be implemented */ + (void) c; + return 0; +} + +PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) +{ + /* To be implemented */ + (void) filename; + (void) flag; + return NULL; +} + + +void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) +{ + /* To be implemented */ + (void) str; + (void) file; +} + +void PlatformSpecificFClose(PlatformSpecificFile file) +{ + /* To be implemented */ + (void) file; +} + +void PlatformSpecificFlush() +{ + /* To be implemented */ +} + +int PlatformSpecificPutchar(int c) +{ + /* To be implemented */ + (void) c; + return 0; +} + +void* PlatformSpecificMalloc(size_t size) +{ + /* To be implemented */ + (void) size; + return NULL; +} + +void* PlatformSpecificRealloc (void* memory, size_t size) +{ + /* To be implemented */ + (void) memory; + (void) size; + return NULL; +} + +void PlatformSpecificFree(void* memory) +{ + /* To be implemented */ + (void) memory; +} + +void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) +{ + /* To be implemented */ + (void) size; + (void) s1; + (void) s2; + return NULL; +} + +void* PlatformSpecificMemset(void* mem, int c, size_t size) +{ + /* To be implemented */ + (void) mem; + (void) c; + (void) size; + return NULL; +} + +double PlatformSpecificFabs(double d) +{ + /* To be implemented */ + (void) d; + return 0.0; +} + +int PlatformSpecificIsNan(double d) +{ + /* To be implemented */ + (void) d; + return 0; +} + +void* malloc(size_t) +{ + return NULL; +} + +void free(void *) +{ +} + diff --git a/src/Platforms/Iar/UtestPlatform.cpp b/src/Platforms/Iar/UtestPlatform.cpp index 80e4ddc5a..c7c1df004 100644 --- a/src/Platforms/Iar/UtestPlatform.cpp +++ b/src/Platforms/Iar/UtestPlatform.cpp @@ -1,229 +1,229 @@ -/* - * 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 -#include -#include -#include -#include -#include -#include -#include "CppUTest/TestHarness.h" -#undef malloc -#undef calloc -#undef realloc -#undef free -#include "CppUTest/TestRegistry.h" -#include "CppUTest/PlatformSpecificFunctions.h" - -static jmp_buf test_exit_jmp_buf[10]; -static int jmp_buf_index = 0; - -int PlatformSpecificSetJmp(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; -} - -void PlatformSpecificLongJmp() -{ - jmp_buf_index--; - longjmp(test_exit_jmp_buf[jmp_buf_index], 1); -} - -void PlatformSpecificRestoreJumpBuffer() -{ - jmp_buf_index--; -} - -void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) -{ - printf("-p doesn't work on this platform as it is not implemented. Running inside the process\b"); - shell->runOneTest(plugin, *result); -} - -TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() -{ - return TestOutput::eclipse; -} - -///////////// Time in millis - -static long TimeInMillisImplementation() -{ - clock_t t = clock(); - - t = t * 10; - - return t; -} - -static long (*timeInMillisFp) () = TimeInMillisImplementation; - -long GetPlatformSpecificTimeInMillis() -{ - return timeInMillisFp(); -} - -void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) -{ - timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; -} - -///////////// Time in String - -static const char* TimeStringImplementation() -{ - time_t tm = time(NULL); - return ctime(&tm); -} - -static const char* (*timeStringFp) () = TimeStringImplementation; - -const char* GetPlatformSpecificTimeString() -{ - return timeStringFp(); -} - -void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) -{ - timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; -} - -int PlatformSpecificAtoI(const char*str) -{ - return atoi(str); -} - -size_t PlatformSpecificStrLen(const char* str) -{ - return strlen(str); -} - -char* PlatformSpecificStrCat(char* s1, const char* s2) -{ - return strcat(s1, s2); -} - -char* PlatformSpecificStrCpy(char* s1, const char* s2) -{ - return strcpy(s1, s2); -} - -char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) -{ - return strncpy(s1, s2, size); -} - -int PlatformSpecificStrCmp(const char* s1, const char* s2) -{ - return strcmp(s1, s2); -} - -int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) -{ - return strncmp(s1, s2, size); -} - -char* PlatformSpecificStrStr(const char* s1, const char* s2) -{ - return strstr((char*)s1, (char*)s2); -} - -int PlatformSpecificVSNprintf(char *str, size_t size, const char* format, va_list args) -{ - return vsnprintf( str, size, format, args); -} - -char PlatformSpecificToLower(char c) -{ - return tolower(c); -} - -PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) -{ - return 0; -} - -void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) -{ -} - -void PlatformSpecificFClose(PlatformSpecificFile file) -{ -} - -void PlatformSpecificFlush() -{ -} - -int PlatformSpecificPutchar(int c) -{ - return putchar(c); -} - -void* PlatformSpecificMalloc(size_t size) -{ - return malloc(size); -} - -void* PlatformSpecificRealloc (void* memory, size_t size) -{ - return realloc(memory, size); -} - -void PlatformSpecificFree(void* memory) -{ - free(memory); -} - -void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) -{ - return memcpy(s1, s2, size); -} - -void* PlatformSpecificMemset(void* mem, int c, size_t size) -{ - return memset(mem, c, size); -} - -double PlatformSpecificFabs(double d) -{ - return fabs(d); -} - -int PlatformSpecificIsNan(double d) -{ - return isnan(d); -} +/* + * 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 +#include +#include +#include +#include +#include +#include +#include "CppUTest/TestHarness.h" +#undef malloc +#undef calloc +#undef realloc +#undef free +#include "CppUTest/TestRegistry.h" +#include "CppUTest/PlatformSpecificFunctions.h" + +static jmp_buf test_exit_jmp_buf[10]; +static int jmp_buf_index = 0; + +int PlatformSpecificSetJmp(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; +} + +void PlatformSpecificLongJmp() +{ + jmp_buf_index--; + longjmp(test_exit_jmp_buf[jmp_buf_index], 1); +} + +void PlatformSpecificRestoreJumpBuffer() +{ + jmp_buf_index--; +} + +void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) +{ + printf("-p doesn't work on this platform as it is not implemented. Running inside the process\b"); + shell->runOneTest(plugin, *result); +} + +TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() +{ + return TestOutput::eclipse; +} + +///////////// Time in millis + +static long TimeInMillisImplementation() +{ + clock_t t = clock(); + + t = t * 10; + + return t; +} + +static long (*timeInMillisFp) () = TimeInMillisImplementation; + +long GetPlatformSpecificTimeInMillis() +{ + return timeInMillisFp(); +} + +void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) +{ + timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; +} + +///////////// Time in String + +static const char* TimeStringImplementation() +{ + time_t tm = time(NULL); + return ctime(&tm); +} + +static const char* (*timeStringFp) () = TimeStringImplementation; + +const char* GetPlatformSpecificTimeString() +{ + return timeStringFp(); +} + +void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) +{ + timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; +} + +int PlatformSpecificAtoI(const char*str) +{ + return atoi(str); +} + +size_t PlatformSpecificStrLen(const char* str) +{ + return strlen(str); +} + +char* PlatformSpecificStrCat(char* s1, const char* s2) +{ + return strcat(s1, s2); +} + +char* PlatformSpecificStrCpy(char* s1, const char* s2) +{ + return strcpy(s1, s2); +} + +char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) +{ + return strncpy(s1, s2, size); +} + +int PlatformSpecificStrCmp(const char* s1, const char* s2) +{ + return strcmp(s1, s2); +} + +int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) +{ + return strncmp(s1, s2, size); +} + +char* PlatformSpecificStrStr(const char* s1, const char* s2) +{ + return strstr((char*)s1, (char*)s2); +} + +int PlatformSpecificVSNprintf(char *str, size_t size, const char* format, va_list args) +{ + return vsnprintf( str, size, format, args); +} + +char PlatformSpecificToLower(char c) +{ + return tolower(c); +} + +PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) +{ + return 0; +} + +void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) +{ +} + +void PlatformSpecificFClose(PlatformSpecificFile file) +{ +} + +void PlatformSpecificFlush() +{ +} + +int PlatformSpecificPutchar(int c) +{ + return putchar(c); +} + +void* PlatformSpecificMalloc(size_t size) +{ + return malloc(size); +} + +void* PlatformSpecificRealloc (void* memory, size_t size) +{ + return realloc(memory, size); +} + +void PlatformSpecificFree(void* memory) +{ + free(memory); +} + +void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) +{ + return memcpy(s1, s2, size); +} + +void* PlatformSpecificMemset(void* mem, int c, size_t size) +{ + return memset(mem, c, size); +} + +double PlatformSpecificFabs(double d) +{ + return fabs(d); +} + +int PlatformSpecificIsNan(double d) +{ + return isnan(d); +} diff --git a/src/Platforms/StarterKit/StarterMemoryLeakWarning.cpp b/src/Platforms/StarterKit/StarterMemoryLeakWarning.cpp index e97cb1bc3..f0e6f1de4 100644 --- a/src/Platforms/StarterKit/StarterMemoryLeakWarning.cpp +++ b/src/Platforms/StarterKit/StarterMemoryLeakWarning.cpp @@ -1,225 +1,225 @@ -/* - * 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/MemoryLeakWarning.h" - -#include -#include - -/* Static since we REALLY can have only one of these! */ -static int allocatedBlocks = 0; -static int allocatedArrays = 0; -static int firstInitialBlocks = 0; -static int firstInitialArrays = 0; -static bool reporterRegistered = false; - -class MemoryLeakWarningData -{ - public: - MemoryLeakWarningData(); - - int initialBlocksUsed; - int initialArraysUsed; - - int blockUsageCheckPoint; - int arrayUsageCheckPoint; - int expectCount; - char message[100]; -}; - -void MemoryLeakWarning::CreateData() -{ - _impl = (MemoryLeakWarningData*) malloc(sizeof(MemoryLeakWarningData)); - _impl->initialBlocksUsed = 0; - _impl->initialArraysUsed = 0; - - _impl->blockUsageCheckPoint = 0; - _impl->arrayUsageCheckPoint = 0; - _impl->expectCount = 0; - _impl->message_[0] = '\0'; -} - -void MemoryLeakWarning::DestroyData() -{ - free(_impl); -} - -extern "C" { -void reportMemoryBallance(); -} - -void reportMemoryBallance() -{ - int blockBalance = allocatedBlocks - firstInitialBlocks; - int arrayBalance = allocatedArrays - firstInitialArrays; - if (blockBalance == 0 && arrayBalance == 0) - ; - else if (blockBalance + arrayBalance == 0) - printf("No leaks but some arrays were deleted without []\n"); - else - { - if (blockBalance > 0) - printf("Memory leak! %d blocks not deleted\n", blockBalance); - if (arrayBalance > 0) - printf("Memory leak! %d arrays not deleted\n", arrayBalance); - if (blockBalance < 0) - printf("More blocks deleted than newed! %d extra deletes\n", blockBalance); - if (arrayBalance < 0) - printf("More arrays deleted than newed! %d extra deletes\n", arrayBalance); - - printf("NOTE - some memory leaks appear to be allocated statics that are not released\n" - " - by the standard library\n" - " - Use the -r switch on your unit tests to repeat the test sequence\n" - " - If no leaks are reported on the second pass, it is likely a static\n" - " - that is not released\n"); - } -} - - -MemoryLeakWarning* MemoryLeakWarning::_latest = NULL; - -MemoryLeakWarning::MemoryLeakWarning() -{ - _latest = this; - CreateData(); -} - -MemoryLeakWarning::~MemoryLeakWarning() -{ - DestroyData(); -} - -MemoryLeakWarning* MemoryLeakWarning::GetLatest() -{ - return _latest; -} - -void MemoryLeakWarning::SetLatest(MemoryLeakWarning* latest) -{ - _latest = latest; -} - -void MemoryLeakWarning::Enable() -{ - _impl->initialBlocksUsed = allocatedBlocks; - _impl->initialArraysUsed = allocatedArrays; - - if (!reporterRegistered) { - firstInitialBlocks = allocatedBlocks; - firstInitialArrays = allocatedArrays; - reporterRegistered = true; - } - -} - -const char* MemoryLeakWarning::FinalReport(int toBeDeletedLeaks) -{ - if (_impl->initialBlocksUsed != (allocatedBlocks-toBeDeletedLeaks) - || _impl->initialArraysUsed != allocatedArrays ) - { - printf("initial blocks=%d, allocated blocks=%d\ninitial arrays=%d, allocated arrays=%d\n", - _impl->initialBlocksUsed, allocatedBlocks, _impl->initialArraysUsed, allocatedArrays); - - return "Memory new/delete imbalance after running tests\n"; - } - else - return ""; -} - -void MemoryLeakWarning::CheckPointUsage() -{ - _impl->blockUsageCheckPoint = allocatedBlocks; - _impl->arrayUsageCheckPoint = allocatedArrays; -} - -bool MemoryLeakWarning::UsageIsNotBalanced() -{ - int arrayBalance = allocatedArrays - _impl->arrayUsageCheckPoint; - int blockBalance = allocatedBlocks - _impl->blockUsageCheckPoint; - - if (_impl->expectCount != 0 && blockBalance + arrayBalance == _impl->expectCount) - return false; - if (blockBalance == 0 && arrayBalance == 0) - return false; - else if (blockBalance + arrayBalance == 0) - sprintf(_impl->message_, "No leaks but some arrays were deleted without []\n"); - else - { - int nchars = 0; - if (_impl->blockUsageCheckPoint != allocatedBlocks) - nchars = sprintf(_impl->message_, "this test leaks %d blocks", - allocatedBlocks - _impl->blockUsageCheckPoint); - - if (_impl->arrayUsageCheckPoint != allocatedArrays) - sprintf(_impl->message_ + nchars, "this test leaks %d arrays", - allocatedArrays - _impl->arrayUsageCheckPoint); - } - return true; -} - -const char* MemoryLeakWarning::Message() -{ - return _impl->message_; -} - -void MemoryLeakWarning::ExpectLeaks(int n) -{ - _impl->expectCount = n; -} - -/* Global overloaded operators */ - -void* operator new(size_t size) -{ - allocatedBlocks++; - return malloc(size); -} - -void operator delete(void* mem) -{ - allocatedBlocks--; - free(mem); -} - -void* operator new[](size_t size) -{ - allocatedArrays++; - return malloc(size); -} - -void operator delete[](void* mem) -{ - allocatedArrays--; - free(mem); -} - -void* operator new(size_t size, const char* file, int line) -{ - allocatedBlocks++; - return malloc(size); - -} +/* + * 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/MemoryLeakWarning.h" + +#include +#include + +/* Static since we REALLY can have only one of these! */ +static int allocatedBlocks = 0; +static int allocatedArrays = 0; +static int firstInitialBlocks = 0; +static int firstInitialArrays = 0; +static bool reporterRegistered = false; + +class MemoryLeakWarningData +{ + public: + MemoryLeakWarningData(); + + int initialBlocksUsed; + int initialArraysUsed; + + int blockUsageCheckPoint; + int arrayUsageCheckPoint; + int expectCount; + char message[100]; +}; + +void MemoryLeakWarning::CreateData() +{ + _impl = (MemoryLeakWarningData*) malloc(sizeof(MemoryLeakWarningData)); + _impl->initialBlocksUsed = 0; + _impl->initialArraysUsed = 0; + + _impl->blockUsageCheckPoint = 0; + _impl->arrayUsageCheckPoint = 0; + _impl->expectCount = 0; + _impl->message_[0] = '\0'; +} + +void MemoryLeakWarning::DestroyData() +{ + free(_impl); +} + +extern "C" { +void reportMemoryBallance(); +} + +void reportMemoryBallance() +{ + int blockBalance = allocatedBlocks - firstInitialBlocks; + int arrayBalance = allocatedArrays - firstInitialArrays; + if (blockBalance == 0 && arrayBalance == 0) + ; + else if (blockBalance + arrayBalance == 0) + printf("No leaks but some arrays were deleted without []\n"); + else + { + if (blockBalance > 0) + printf("Memory leak! %d blocks not deleted\n", blockBalance); + if (arrayBalance > 0) + printf("Memory leak! %d arrays not deleted\n", arrayBalance); + if (blockBalance < 0) + printf("More blocks deleted than newed! %d extra deletes\n", blockBalance); + if (arrayBalance < 0) + printf("More arrays deleted than newed! %d extra deletes\n", arrayBalance); + + printf("NOTE - some memory leaks appear to be allocated statics that are not released\n" + " - by the standard library\n" + " - Use the -r switch on your unit tests to repeat the test sequence\n" + " - If no leaks are reported on the second pass, it is likely a static\n" + " - that is not released\n"); + } +} + + +MemoryLeakWarning* MemoryLeakWarning::_latest = NULL; + +MemoryLeakWarning::MemoryLeakWarning() +{ + _latest = this; + CreateData(); +} + +MemoryLeakWarning::~MemoryLeakWarning() +{ + DestroyData(); +} + +MemoryLeakWarning* MemoryLeakWarning::GetLatest() +{ + return _latest; +} + +void MemoryLeakWarning::SetLatest(MemoryLeakWarning* latest) +{ + _latest = latest; +} + +void MemoryLeakWarning::Enable() +{ + _impl->initialBlocksUsed = allocatedBlocks; + _impl->initialArraysUsed = allocatedArrays; + + if (!reporterRegistered) { + firstInitialBlocks = allocatedBlocks; + firstInitialArrays = allocatedArrays; + reporterRegistered = true; + } + +} + +const char* MemoryLeakWarning::FinalReport(int toBeDeletedLeaks) +{ + if (_impl->initialBlocksUsed != (allocatedBlocks-toBeDeletedLeaks) + || _impl->initialArraysUsed != allocatedArrays ) + { + printf("initial blocks=%d, allocated blocks=%d\ninitial arrays=%d, allocated arrays=%d\n", + _impl->initialBlocksUsed, allocatedBlocks, _impl->initialArraysUsed, allocatedArrays); + + return "Memory new/delete imbalance after running tests\n"; + } + else + return ""; +} + +void MemoryLeakWarning::CheckPointUsage() +{ + _impl->blockUsageCheckPoint = allocatedBlocks; + _impl->arrayUsageCheckPoint = allocatedArrays; +} + +bool MemoryLeakWarning::UsageIsNotBalanced() +{ + int arrayBalance = allocatedArrays - _impl->arrayUsageCheckPoint; + int blockBalance = allocatedBlocks - _impl->blockUsageCheckPoint; + + if (_impl->expectCount != 0 && blockBalance + arrayBalance == _impl->expectCount) + return false; + if (blockBalance == 0 && arrayBalance == 0) + return false; + else if (blockBalance + arrayBalance == 0) + sprintf(_impl->message_, "No leaks but some arrays were deleted without []\n"); + else + { + int nchars = 0; + if (_impl->blockUsageCheckPoint != allocatedBlocks) + nchars = sprintf(_impl->message_, "this test leaks %d blocks", + allocatedBlocks - _impl->blockUsageCheckPoint); + + if (_impl->arrayUsageCheckPoint != allocatedArrays) + sprintf(_impl->message_ + nchars, "this test leaks %d arrays", + allocatedArrays - _impl->arrayUsageCheckPoint); + } + return true; +} + +const char* MemoryLeakWarning::Message() +{ + return _impl->message_; +} + +void MemoryLeakWarning::ExpectLeaks(int n) +{ + _impl->expectCount = n; +} + +/* Global overloaded operators */ + +void* operator new(size_t size) +{ + allocatedBlocks++; + return malloc(size); +} + +void operator delete(void* mem) +{ + allocatedBlocks--; + free(mem); +} + +void* operator new[](size_t size) +{ + allocatedArrays++; + return malloc(size); +} + +void operator delete[](void* mem) +{ + allocatedArrays--; + free(mem); +} + +void* operator new(size_t size, const char* file, int line) +{ + allocatedBlocks++; + return malloc(size); + +} diff --git a/src/Platforms/StarterKit/UtestPlatform.cpp b/src/Platforms/StarterKit/UtestPlatform.cpp index 57ea7ddd3..003f5d2bc 100644 --- a/src/Platforms/StarterKit/UtestPlatform.cpp +++ b/src/Platforms/StarterKit/UtestPlatform.cpp @@ -1,77 +1,77 @@ - -#include "CppUTest/TestHarness.h" -#include "CppUTest/TestResult.h" -#include -#include - -void executePlatformSpecificTestBody(Utest* test) -{ - test->testBody(); -} - - -///////////// Time in millis - -static long TimeInMillisImplementation() -{ - struct timeval tv; - struct timezone tz; - ::gettimeofday(&tv, &tz); - return (tv.tv_sec * 1000) + (long)(tv.tv_usec * 0.001); -} - -static long (*timeInMillisFp) () = TimeInMillisImplementation; - -long GetPlatformSpecificTimeInMillis() -{ - return timeInMillisFp(); -} - -void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) -{ - timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; -} - -///////////// Time in String - -static SimpleString TimeStringImplementation() -{ - time_t tm = time(NULL); - return ctime(&tm); -} - -static SimpleString (*timeStringFp) () = TimeStringImplementation; - -SimpleString GetPlatformSpecificTimeString() -{ - return timeStringFp(); -} - -void SetPlatformSpecificTimeStringMethod(SimpleString (*platformMethod) ()) -{ - timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; -} - -///////////// Run one test with exit on first error, using setjmp/longjmp -#include - -static jmp_buf test_exit_jmp_buf; - -void TestRegistry::platformSpecificRunOneTest(Utest* test, TestResult& result) -{ - if (0 == setjmp(test_exit_jmp_buf)) - runOneTest(test, result) ; -} - -void PlatformSpecificExitCurrentTestImpl() -{ - longjmp(test_exit_jmp_buf, 1); -} - -void FakePlatformSpecificExitCurrentTest() -{ -} - -void (*PlatformSpecificExitCurrentTest)() = PlatformSpecificExitCurrentTestImpl; - - + +#include "CppUTest/TestHarness.h" +#include "CppUTest/TestResult.h" +#include +#include + +void executePlatformSpecificTestBody(Utest* test) +{ + test->testBody(); +} + + +///////////// Time in millis + +static long TimeInMillisImplementation() +{ + struct timeval tv; + struct timezone tz; + ::gettimeofday(&tv, &tz); + return (tv.tv_sec * 1000) + (long)(tv.tv_usec * 0.001); +} + +static long (*timeInMillisFp) () = TimeInMillisImplementation; + +long GetPlatformSpecificTimeInMillis() +{ + return timeInMillisFp(); +} + +void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) +{ + timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; +} + +///////////// Time in String + +static SimpleString TimeStringImplementation() +{ + time_t tm = time(NULL); + return ctime(&tm); +} + +static SimpleString (*timeStringFp) () = TimeStringImplementation; + +SimpleString GetPlatformSpecificTimeString() +{ + return timeStringFp(); +} + +void SetPlatformSpecificTimeStringMethod(SimpleString (*platformMethod) ()) +{ + timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; +} + +///////////// Run one test with exit on first error, using setjmp/longjmp +#include + +static jmp_buf test_exit_jmp_buf; + +void TestRegistry::platformSpecificRunOneTest(Utest* test, TestResult& result) +{ + if (0 == setjmp(test_exit_jmp_buf)) + runOneTest(test, result) ; +} + +void PlatformSpecificExitCurrentTestImpl() +{ + longjmp(test_exit_jmp_buf, 1); +} + +void FakePlatformSpecificExitCurrentTest() +{ +} + +void (*PlatformSpecificExitCurrentTest)() = PlatformSpecificExitCurrentTestImpl; + + diff --git a/src/Platforms/Symbian/UtestPlatform.cpp b/src/Platforms/Symbian/UtestPlatform.cpp index 7823c1621..5db545b2f 100644 --- a/src/Platforms/Symbian/UtestPlatform.cpp +++ b/src/Platforms/Symbian/UtestPlatform.cpp @@ -1,193 +1,193 @@ -/* - * Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde and Timo Puronen - * 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 -#include -#include -#include -#include -#include -#include -#include -#include "CppUTest/PlatformSpecificFunctions.h" - -static jmp_buf test_exit_jmp_buf[10]; -static int jmp_buf_index = 0; - -int PlatformSpecificSetJmp(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; -} - -void PlatformSpecificLongJmp() -{ - jmp_buf_index--; - longjmp(test_exit_jmp_buf[jmp_buf_index], 1); -} - -void PlatformSpecificRestoreJumpBuffer() -{ - jmp_buf_index--; -} - -void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) -{ - printf("-p doesn't work on this platform as it is not implemented. Running inside the process\b"); - shell->runOneTest(plugin, *result); -} - -static long TimeInMillisImplementation() { - struct timeval tv; - struct timezone tz; - ::gettimeofday(&tv, &tz); - return (tv.tv_sec * 1000) + (long)(tv.tv_usec * 0.001); -} - -static long (*timeInMillisFp) () = TimeInMillisImplementation; - -long GetPlatformSpecificTimeInMillis() { - return timeInMillisFp(); -} - -void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { - timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; -} - -TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() -{ - return TestOutput::eclipse; -} - -///////////// Time in String - -static SimpleString TimeStringImplementation() { - time_t tm = time(NULL); - return ctime(&tm); -} - -static SimpleString (*timeStringFp) () = TimeStringImplementation; - -SimpleString GetPlatformSpecificTimeString() { - return timeStringFp(); -} - -void SetPlatformSpecificTimeStringMethod(SimpleString (*platformMethod) ()) { - timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; -} - -int PlatformSpecificVSNprintf(char* str, size_t size, const char* format, va_list args) { - return vsnprintf(str, size, format, args); -} - -char PlatformSpecificToLower(char c) -{ - return tolower(c); -} - -void PlatformSpecificFlush() { - fflush(stdout); -} - -int PlatformSpecificPutchar(int c) { - return putchar(c); -} - -char* PlatformSpecificStrCpy(char* s1, const char* s2) { - return strcpy(s1, s2); -} - -size_t PlatformSpecificStrLen(const char* s) { - return strlen(s); -} - -char* PlatformSpecificStrStr(const char* s1, const char* s2) { - return strstr(s1, s2); -} - -int PlatformSpecificStrCmp(const char* s1, const char* s2) { - return strcmp(s1, s2); -} - -char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { - return strncpy(s1, s2, size); -} - -int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { - return strncmp(s1, s2, size); -} - -char* PlatformSpecificStrCat(char* s1, const char* s2) { - return strcat(s1, s2); -} - -double PlatformSpecificFabs(double d) { - return fabs(d); -} - -void* PlatformSpecificMalloc(size_t size) { - return malloc(size); -} - -void* PlatformSpecificRealloc (void* memory, size_t size) { - return realloc(memory, size); -} - -void PlatformSpecificFree(void* memory) { - free(memory); -} - -void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { - return memcpy(s1, s2, size); -} - -void* PlatformSpecificMemset(void* mem, int c, size_t size) -{ - return memset(mem, c, size); -} - -PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { - return fopen(filename, flag); -} - -void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { - fputs(str, (FILE*)file); -} - -void PlatformSpecificFClose(PlatformSpecificFile file) { - fclose((FILE*)file); -} - -int PlatformSpecificAtoI(const char*str) { - return atoi(str); -} +/* + * Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde and Timo Puronen + * 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 +#include +#include +#include +#include +#include +#include +#include +#include "CppUTest/PlatformSpecificFunctions.h" + +static jmp_buf test_exit_jmp_buf[10]; +static int jmp_buf_index = 0; + +int PlatformSpecificSetJmp(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; +} + +void PlatformSpecificLongJmp() +{ + jmp_buf_index--; + longjmp(test_exit_jmp_buf[jmp_buf_index], 1); +} + +void PlatformSpecificRestoreJumpBuffer() +{ + jmp_buf_index--; +} + +void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) +{ + printf("-p doesn't work on this platform as it is not implemented. Running inside the process\b"); + shell->runOneTest(plugin, *result); +} + +static long TimeInMillisImplementation() { + struct timeval tv; + struct timezone tz; + ::gettimeofday(&tv, &tz); + return (tv.tv_sec * 1000) + (long)(tv.tv_usec * 0.001); +} + +static long (*timeInMillisFp) () = TimeInMillisImplementation; + +long GetPlatformSpecificTimeInMillis() { + return timeInMillisFp(); +} + +void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { + timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; +} + +TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() +{ + return TestOutput::eclipse; +} + +///////////// Time in String + +static SimpleString TimeStringImplementation() { + time_t tm = time(NULL); + return ctime(&tm); +} + +static SimpleString (*timeStringFp) () = TimeStringImplementation; + +SimpleString GetPlatformSpecificTimeString() { + return timeStringFp(); +} + +void SetPlatformSpecificTimeStringMethod(SimpleString (*platformMethod) ()) { + timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; +} + +int PlatformSpecificVSNprintf(char* str, size_t size, const char* format, va_list args) { + return vsnprintf(str, size, format, args); +} + +char PlatformSpecificToLower(char c) +{ + return tolower(c); +} + +void PlatformSpecificFlush() { + fflush(stdout); +} + +int PlatformSpecificPutchar(int c) { + return putchar(c); +} + +char* PlatformSpecificStrCpy(char* s1, const char* s2) { + return strcpy(s1, s2); +} + +size_t PlatformSpecificStrLen(const char* s) { + return strlen(s); +} + +char* PlatformSpecificStrStr(const char* s1, const char* s2) { + return strstr(s1, s2); +} + +int PlatformSpecificStrCmp(const char* s1, const char* s2) { + return strcmp(s1, s2); +} + +char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { + return strncpy(s1, s2, size); +} + +int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { + return strncmp(s1, s2, size); +} + +char* PlatformSpecificStrCat(char* s1, const char* s2) { + return strcat(s1, s2); +} + +double PlatformSpecificFabs(double d) { + return fabs(d); +} + +void* PlatformSpecificMalloc(size_t size) { + return malloc(size); +} + +void* PlatformSpecificRealloc (void* memory, size_t size) { + return realloc(memory, size); +} + +void PlatformSpecificFree(void* memory) { + free(memory); +} + +void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { + return memcpy(s1, s2, size); +} + +void* PlatformSpecificMemset(void* mem, int c, size_t size) +{ + return memset(mem, c, size); +} + +PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { + return fopen(filename, flag); +} + +void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { + fputs(str, (FILE*)file); +} + +void PlatformSpecificFClose(PlatformSpecificFile file) { + fclose((FILE*)file); +} + +int PlatformSpecificAtoI(const char*str) { + return atoi(str); +} diff --git a/src/Platforms/VisualCpp/UtestPlatform.cpp b/src/Platforms/VisualCpp/UtestPlatform.cpp index 2e7a44bf3..3e8c89ff7 100644 --- a/src/Platforms/VisualCpp/UtestPlatform.cpp +++ b/src/Platforms/VisualCpp/UtestPlatform.cpp @@ -1,237 +1,237 @@ -#include "Platform.h" -#include -#include "CppUTest/TestHarness.h" -#undef malloc -#undef free -#undef calloc -#undef realloc - -#include "CppUTest/TestRegistry.h" -#include -#include -#include -#include -#include -#include -#include -#include "CppUTest/PlatformSpecificFunctions.h" - -#include -#include - - -#include - -static jmp_buf test_exit_jmp_buf[10]; -static int jmp_buf_index = 0; - -int PlatformSpecificSetJmp(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; -} - -void PlatformSpecificLongJmp() -{ - jmp_buf_index--; - longjmp(test_exit_jmp_buf[jmp_buf_index], 1); -} - -void PlatformSpecificRestoreJumpBuffer() -{ - jmp_buf_index--; -} - -void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) -{ - printf("-p doesn't work on this platform as it is not implemented. Running inside the process\b"); - shell->runOneTest(plugin, *result); -} - -TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() -{ - return TestOutput::vistualStudio; -} - -///////////// Time in millis - -static long TimeInMillisImplementation() -{ - return timeGetTime(); -} - -static long (*timeInMillisFp) () = TimeInMillisImplementation; - -long GetPlatformSpecificTimeInMillis() -{ - return timeInMillisFp(); -} - -void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) -{ - timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; -} - -///////////// Time in String - -static const char* TimeStringImplementation() -{ - time_t tm = time(NULL); - static char dateTime[80]; - struct tm *tmp = localtime(&tm); - strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp); - return dateTime; -} - -static const char* (*timeStringFp) () = TimeStringImplementation; - -const char* GetPlatformSpecificTimeString() -{ - return timeStringFp(); -} - -void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) -{ - timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; -} - - -////// taken from gcc - -int PlatformSpecificAtoI(const char*str) -{ - return atoi(str); -} - -size_t PlatformSpecificStrLen(const char* str) -{ - return strlen(str); -} - -char* PlatformSpecificStrCat(char* s1, const char* s2) -{ - return strcat(s1, s2); -} - -char* PlatformSpecificStrCpy(char* s1, const char* s2) -{ - return strcpy(s1, s2); -} - -char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) -{ - return strncpy(s1, s2, size); -} - -int PlatformSpecificStrCmp(const char* s1, const char* s2) -{ - return strcmp(s1, s2); -} - -int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) -{ - return strncmp(s1, s2, size); -} -char* PlatformSpecificStrStr(const char* s1, const char* s2) -{ - return (char*) strstr(s1, s2); -} - -int PlatformSpecificVSNprintf(char *str, size_t size, const char* format, va_list args) -{ - char* buf = 0; - size_t sizeGuess = size; - - int result = _vsnprintf( str, size, format, args); - str[size-1] = 0; - while (result == -1) - { - if (buf != 0) - free(buf); - sizeGuess += 10; - buf = (char*)malloc(sizeGuess); - result = _vsnprintf( buf, sizeGuess, format, args); - } - - if (buf != 0) - free(buf); - return result; - -} - -PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) -{ - return fopen(filename, flag); -} - -void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) -{ - fputs(str, (FILE*)file); -} - -void PlatformSpecificFClose(PlatformSpecificFile file) -{ - fclose((FILE*)file); -} - -void PlatformSpecificFlush() -{ - fflush(stdout); -} - -int PlatformSpecificPutchar(int c) -{ - return putchar(c); -} - -void* PlatformSpecificMalloc(size_t size) -{ - return malloc(size); -} - -void* PlatformSpecificRealloc (void* memory, size_t size) -{ - return realloc(memory, size); -} - -void PlatformSpecificFree(void* memory) -{ - free(memory); -} - -void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) -{ - return memcpy(s1, s2, size); -} - -void* PlatformSpecificMemset(void* mem, int c, size_t size) -{ - return memset(mem, c, size); -} - -double PlatformSpecificFabs(double d) -{ - return fabs(d); -} - -int PlatformSpecificIsNan(double d) -{ - return _isnan(d); -} - -int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, void* args) -{ - return _vsnprintf( str, size, format, (va_list) args); -} - -char PlatformSpecificToLower(char c) -{ - return tolower(c); -} - - +#include "Platform.h" +#include +#include "CppUTest/TestHarness.h" +#undef malloc +#undef free +#undef calloc +#undef realloc + +#include "CppUTest/TestRegistry.h" +#include +#include +#include +#include +#include +#include +#include +#include "CppUTest/PlatformSpecificFunctions.h" + +#include +#include + + +#include + +static jmp_buf test_exit_jmp_buf[10]; +static int jmp_buf_index = 0; + +int PlatformSpecificSetJmp(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; +} + +void PlatformSpecificLongJmp() +{ + jmp_buf_index--; + longjmp(test_exit_jmp_buf[jmp_buf_index], 1); +} + +void PlatformSpecificRestoreJumpBuffer() +{ + jmp_buf_index--; +} + +void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) +{ + printf("-p doesn't work on this platform as it is not implemented. Running inside the process\b"); + shell->runOneTest(plugin, *result); +} + +TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() +{ + return TestOutput::vistualStudio; +} + +///////////// Time in millis + +static long TimeInMillisImplementation() +{ + return timeGetTime(); +} + +static long (*timeInMillisFp) () = TimeInMillisImplementation; + +long GetPlatformSpecificTimeInMillis() +{ + return timeInMillisFp(); +} + +void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) +{ + timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; +} + +///////////// Time in String + +static const char* TimeStringImplementation() +{ + time_t tm = time(NULL); + static char dateTime[80]; + struct tm *tmp = localtime(&tm); + strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp); + return dateTime; +} + +static const char* (*timeStringFp) () = TimeStringImplementation; + +const char* GetPlatformSpecificTimeString() +{ + return timeStringFp(); +} + +void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) +{ + timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; +} + + +////// taken from gcc + +int PlatformSpecificAtoI(const char*str) +{ + return atoi(str); +} + +size_t PlatformSpecificStrLen(const char* str) +{ + return strlen(str); +} + +char* PlatformSpecificStrCat(char* s1, const char* s2) +{ + return strcat(s1, s2); +} + +char* PlatformSpecificStrCpy(char* s1, const char* s2) +{ + return strcpy(s1, s2); +} + +char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) +{ + return strncpy(s1, s2, size); +} + +int PlatformSpecificStrCmp(const char* s1, const char* s2) +{ + return strcmp(s1, s2); +} + +int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) +{ + return strncmp(s1, s2, size); +} +char* PlatformSpecificStrStr(const char* s1, const char* s2) +{ + return (char*) strstr(s1, s2); +} + +int PlatformSpecificVSNprintf(char *str, size_t size, const char* format, va_list args) +{ + char* buf = 0; + size_t sizeGuess = size; + + int result = _vsnprintf( str, size, format, args); + str[size-1] = 0; + while (result == -1) + { + if (buf != 0) + free(buf); + sizeGuess += 10; + buf = (char*)malloc(sizeGuess); + result = _vsnprintf( buf, sizeGuess, format, args); + } + + if (buf != 0) + free(buf); + return result; + +} + +PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) +{ + return fopen(filename, flag); +} + +void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) +{ + fputs(str, (FILE*)file); +} + +void PlatformSpecificFClose(PlatformSpecificFile file) +{ + fclose((FILE*)file); +} + +void PlatformSpecificFlush() +{ + fflush(stdout); +} + +int PlatformSpecificPutchar(int c) +{ + return putchar(c); +} + +void* PlatformSpecificMalloc(size_t size) +{ + return malloc(size); +} + +void* PlatformSpecificRealloc (void* memory, size_t size) +{ + return realloc(memory, size); +} + +void PlatformSpecificFree(void* memory) +{ + free(memory); +} + +void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) +{ + return memcpy(s1, s2, size); +} + +void* PlatformSpecificMemset(void* mem, int c, size_t size) +{ + return memset(mem, c, size); +} + +double PlatformSpecificFabs(double d) +{ + return fabs(d); +} + +int PlatformSpecificIsNan(double d) +{ + return _isnan(d); +} + +int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, void* args) +{ + return _vsnprintf( str, size, format, (va_list) args); +} + +char PlatformSpecificToLower(char c) +{ + return tolower(c); +} + + diff --git a/tests/AllTests.cpp b/tests/AllTests.cpp index 5a992ac3d..c642140c5 100644 --- a/tests/AllTests.cpp +++ b/tests/AllTests.cpp @@ -1,38 +1,38 @@ -/* - * 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" - -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); - - return CommandLineTestRunner::RunAllTests(ac, av); -} - +/* + * 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" + +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); + + return CommandLineTestRunner::RunAllTests(ac, av); +} + diff --git a/tests/AllTests.h b/tests/AllTests.h index c7e60eaac..9e2fb1649 100644 --- a/tests/AllTests.h +++ b/tests/AllTests.h @@ -1,43 +1,43 @@ -/* - * 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 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); - -/* In allTest.cpp */ -IMPORT_TEST_GROUP(CheatSheet); - +/* + * 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 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); + +/* In allTest.cpp */ +IMPORT_TEST_GROUP(CheatSheet); + diff --git a/tests/AllTests.vcproj b/tests/AllTests.vcproj index 768ec5e8f..67221b998 100644 --- a/tests/AllTests.vcproj +++ b/tests/AllTests.vcproj @@ -1,411 +1,411 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/AllTests.vcxproj b/tests/AllTests.vcxproj index 6fcdfcada..5fcb75732 100644 --- a/tests/AllTests.vcxproj +++ b/tests/AllTests.vcxproj @@ -1,197 +1,197 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {913088F6-37C0-4195-80E9-548C7C5303CB} - - - - Application - false - MultiByte - - - Application - false - MultiByte - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.30319.1 - .\Release\ - .\Release\ - false - .\Debug\ - .\Debug\ - true - - - - .\Release/AllTests.tlb - - - - - MaxSpeed - OnlyExplicitInline - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - MultiThreaded - true - .\Release/AllTests.pch - .\Release/ - .\Release/ - .\Release/ - Level3 - true - ..\include;..\include\CppUTestExt\CppUTestGTest;..\include\CppUTestExt\CppUTestGMock;..\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - - - $(OutDir)AllTests.exe - true - .\Release/AllTests.pdb - Console - false - - - MachineX86 - - - true - .\Release/AllTests.bsc - - - "$(TargetPath)" - - - - - .\Debug/AllTests.tlb - - - - - Disabled - ..\include;..\include\CppUTestExt\CppUTestGTest;..\include\CppUTestExt\CppUTestGMock;..\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) - _CONSOLE;WIN32;_DEBUG;%(PreprocessorDefinitions) - EnableFastChecks - MultiThreadedDebugDLL - .\Debug/AllTests.pch - .\Debug/ - .\Debug/ - .\Debug/ - true - Level3 - true - EditAndContinue - ..\include\Platforms\VisualCpp\Platform.h;..\include\CppUTest\MemoryLeakDetectorMallocMacros.h;%(ForcedIncludeFiles) - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - - - - - $(OutDir)AllTests.exe - true - true - .\Debug/AllTests.pdb - Console - false - - - MachineX86 - - - true - .\Debug/AllTests.bsc - - - "$(TargetPath)" - - - - - {f468f539-27bd-468e-be64-dde641400b51} - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + + {913088F6-37C0-4195-80E9-548C7C5303CB} + + + + Application + false + MultiByte + + + Application + false + MultiByte + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + .\Release\ + .\Release\ + false + .\Debug\ + .\Debug\ + true + + + + .\Release/AllTests.tlb + + + + + MaxSpeed + OnlyExplicitInline + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + MultiThreaded + true + .\Release/AllTests.pch + .\Release/ + .\Release/ + .\Release/ + Level3 + true + ..\include;..\include\CppUTestExt\CppUTestGTest;..\include\CppUTestExt\CppUTestGMock;..\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)AllTests.exe + true + .\Release/AllTests.pdb + Console + false + + + MachineX86 + + + true + .\Release/AllTests.bsc + + + "$(TargetPath)" + + + + + .\Debug/AllTests.tlb + + + + + Disabled + ..\include;..\include\CppUTestExt\CppUTestGTest;..\include\CppUTestExt\CppUTestGMock;..\include\Platforms\VisualCpp;%(AdditionalIncludeDirectories) + _CONSOLE;WIN32;_DEBUG;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + .\Debug/AllTests.pch + .\Debug/ + .\Debug/ + .\Debug/ + true + Level3 + true + EditAndContinue + ..\include\Platforms\VisualCpp\Platform.h;..\include\CppUTest\MemoryLeakDetectorMallocMacros.h;%(ForcedIncludeFiles) + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + + + $(OutDir)AllTests.exe + true + true + .\Debug/AllTests.pdb + Console + false + + + MachineX86 + + + true + .\Debug/AllTests.bsc + + + "$(TargetPath)" + + + + + {f468f539-27bd-468e-be64-dde641400b51} + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/CommandLineTestRunnerTest.cpp b/tests/CommandLineTestRunnerTest.cpp index d437d2d2e..941129995 100644 --- a/tests/CommandLineTestRunnerTest.cpp +++ b/tests/CommandLineTestRunnerTest.cpp @@ -1,96 +1,96 @@ -/* - * 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/CommandLineTestRunner.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTest/TestTestingFixture.h" -#include "CppUTest/TestPlugin.h" - -class DummyPluginWhichCountsThePlugins : public TestPlugin -{ -public: - - bool returnValue; - int amountOfPlugins; - - DummyPluginWhichCountsThePlugins(const SimpleString& name, TestRegistry* registry) : - TestPlugin(name), returnValue(true), amountOfPlugins(0), registry_(registry) - { - } - - virtual bool parseArguments(int, const char**, int) - { - /* Remove ourselves from the count */ - amountOfPlugins = registry_->countPlugins() - 1; - return returnValue; - } -private: - TestRegistry* registry_; - -}; - - -TEST_GROUP(CommandLineTestRunner) -{ - TestRegistry registry; - StringBufferTestOutput output; - DummyPluginWhichCountsThePlugins* pluginCountingPlugin; - - void setup() - { - pluginCountingPlugin = new DummyPluginWhichCountsThePlugins("PluginCountingPlugin", ®istry); - } - void teardown() - { - delete pluginCountingPlugin; - } -}; - -TEST(CommandLineTestRunner, OnePluginGetsInstalledDuringTheRunningTheTests) -{ - const char* argv[] = { "tests.exe", "-psomething"}; - - registry.installPlugin(pluginCountingPlugin); - - CommandLineTestRunner commandLineTestRunner(2, argv, &output, ®istry); - commandLineTestRunner.runAllTestsMain(); - registry.removePluginByName("PluginCountingPlugin"); - - LONGS_EQUAL(0, registry.countPlugins()); - LONGS_EQUAL(1, pluginCountingPlugin->amountOfPlugins); -} - -TEST(CommandLineTestRunner, NoPluginsAreInstalledAtTheEndOfARunWhenTheArgumentsAreInvalid) -{ - const char* argv[] = { "tests.exe", "-fdskjnfkds"}; - - CommandLineTestRunner commandLineTestRunner(2, argv, &output, ®istry); - commandLineTestRunner.runAllTestsMain(); - - LONGS_EQUAL(0, registry.countPlugins()); -} +/* + * 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/CommandLineTestRunner.h" +#include "CppUTest/TestRegistry.h" +#include "CppUTest/TestTestingFixture.h" +#include "CppUTest/TestPlugin.h" + +class DummyPluginWhichCountsThePlugins : public TestPlugin +{ +public: + + bool returnValue; + int amountOfPlugins; + + DummyPluginWhichCountsThePlugins(const SimpleString& name, TestRegistry* registry) : + TestPlugin(name), returnValue(true), amountOfPlugins(0), registry_(registry) + { + } + + virtual bool parseArguments(int, const char**, int) + { + /* Remove ourselves from the count */ + amountOfPlugins = registry_->countPlugins() - 1; + return returnValue; + } +private: + TestRegistry* registry_; + +}; + + +TEST_GROUP(CommandLineTestRunner) +{ + TestRegistry registry; + StringBufferTestOutput output; + DummyPluginWhichCountsThePlugins* pluginCountingPlugin; + + void setup() + { + pluginCountingPlugin = new DummyPluginWhichCountsThePlugins("PluginCountingPlugin", ®istry); + } + void teardown() + { + delete pluginCountingPlugin; + } +}; + +TEST(CommandLineTestRunner, OnePluginGetsInstalledDuringTheRunningTheTests) +{ + const char* argv[] = { "tests.exe", "-psomething"}; + + registry.installPlugin(pluginCountingPlugin); + + CommandLineTestRunner commandLineTestRunner(2, argv, &output, ®istry); + commandLineTestRunner.runAllTestsMain(); + registry.removePluginByName("PluginCountingPlugin"); + + LONGS_EQUAL(0, registry.countPlugins()); + LONGS_EQUAL(1, pluginCountingPlugin->amountOfPlugins); +} + +TEST(CommandLineTestRunner, NoPluginsAreInstalledAtTheEndOfARunWhenTheArgumentsAreInvalid) +{ + const char* argv[] = { "tests.exe", "-fdskjnfkds"}; + + CommandLineTestRunner commandLineTestRunner(2, argv, &output, ®istry); + commandLineTestRunner.runAllTestsMain(); + + LONGS_EQUAL(0, registry.countPlugins()); +} diff --git a/tests/CppUTestExt/AllTests.cpp b/tests/CppUTestExt/AllTests.cpp index 69394c378..24d3700cd 100644 --- a/tests/CppUTestExt/AllTests.cpp +++ b/tests/CppUTestExt/AllTests.cpp @@ -1,61 +1,61 @@ -/* - * 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/TestRegistry.h" -#include "CppUTestExt/MemoryReporterPlugin.h" -#include "CppUTestExt/MockSupportPlugin.h" - -#ifdef INCLUDE_GTEST_TESTS -#include "CppUTestExt/GTestConvertor.h" -#endif - -int main(int ac, const char** av) -{ -#ifdef INCLUDE_GTEST_TESTS - GTestConvertor convertor; - convertor.addAllGTestToTestRegistry(); -#endif - - MemoryReporterPlugin plugin; - MockSupportPlugin mockPlugin; - TestRegistry::getCurrentRegistry()->installPlugin(&plugin); - TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin); - -#ifndef GMOCK_RENAME_MAIN - return CommandLineTestRunner::RunAllTests(ac, av); -#else - /* Don't have any memory leak detector when running the Google Test tests */ - - testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity; - - ConsoleTestOutput output; - CommandLineTestRunner runner(ac, av, &output, TestRegistry::getCurrentRegistry()); - return runner.runAllTestsMain(); -#endif -} - +/* + * 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/TestRegistry.h" +#include "CppUTestExt/MemoryReporterPlugin.h" +#include "CppUTestExt/MockSupportPlugin.h" + +#ifdef INCLUDE_GTEST_TESTS +#include "CppUTestExt/GTestConvertor.h" +#endif + +int main(int ac, const char** av) +{ +#ifdef INCLUDE_GTEST_TESTS + GTestConvertor convertor; + convertor.addAllGTestToTestRegistry(); +#endif + + MemoryReporterPlugin plugin; + MockSupportPlugin mockPlugin; + TestRegistry::getCurrentRegistry()->installPlugin(&plugin); + TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin); + +#ifndef GMOCK_RENAME_MAIN + return CommandLineTestRunner::RunAllTests(ac, av); +#else + /* Don't have any memory leak detector when running the Google Test tests */ + + testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity; + + ConsoleTestOutput output; + CommandLineTestRunner runner(ac, av, &output, TestRegistry::getCurrentRegistry()); + return runner.runAllTestsMain(); +#endif +} + diff --git a/tests/CppUTestExt/OrderedTestTest.cpp b/tests/CppUTestExt/OrderedTestTest.cpp index 2d1534966..f76279340 100644 --- a/tests/CppUTestExt/OrderedTestTest.cpp +++ b/tests/CppUTestExt/OrderedTestTest.cpp @@ -1,183 +1,183 @@ -/* - * 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/TestRegistry.h" -#include "CppUTest/TestTestingFixture.h" -#include "CppUTestExt/OrderedTest.h" - -TEST_GROUP(TestOrderedTest) -{ - TestTestingFixture* fixture; - - OrderedTestShell orderedTest; - OrderedTestShell orderedTest2; - OrderedTestShell orderedTest3; - ExecFunctionTestShell normalTest; - ExecFunctionTestShell normalTest2; - ExecFunctionTestShell normalTest3; - - OrderedTestShell* orderedTestCache; - void setup() - { - orderedTestCache = OrderedTestShell::getOrderedTestHead(); - OrderedTestShell::setOrderedTestHead(0); - - fixture = new TestTestingFixture(); - fixture->registry_->unDoLastAddTest(); - } - - void teardown() - { - delete fixture; - OrderedTestShell::setOrderedTestHead(orderedTestCache); - } - - void InstallOrderedTest(OrderedTestShell& test, int level) - { - OrderedTestInstaller(test, "testgroup", "testname", __FILE__, __LINE__, level); - } - - void InstallNormalTest(UtestShell& test) - { - TestInstaller(test, "testgroup", "testname", __FILE__, __LINE__); - } - - UtestShell* firstTest() - { - return fixture->registry_->getFirstTest(); - } - - UtestShell* secondTest() - { - return fixture->registry_->getFirstTest()->getNext(); - } -}; - -TEST(TestOrderedTest, TestInstallerSetsFields) -{ - OrderedTestInstaller(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()); - LONGS_EQUAL(10, orderedTest.getLineNumber()); - LONGS_EQUAL(5, orderedTest.getLevel()); -} - -TEST(TestOrderedTest, InstallOneText) -{ - InstallOrderedTest(orderedTest, 5); - CHECK(firstTest() == &orderedTest); -} - -TEST(TestOrderedTest, OrderedTestsAreLast) -{ - InstallNormalTest(normalTest); - InstallOrderedTest(orderedTest, 5); - CHECK(firstTest() == &normalTest); - CHECK(secondTest() == &orderedTest); -} - -TEST(TestOrderedTest, TwoTestsAddedInReverseOrder) -{ - InstallOrderedTest(orderedTest, 5); - InstallOrderedTest(orderedTest2, 3); - CHECK(firstTest() == &orderedTest2); - CHECK(secondTest() == &orderedTest); -} - -TEST(TestOrderedTest, TwoTestsAddedInOrder) -{ - InstallOrderedTest(orderedTest2, 3); - InstallOrderedTest(orderedTest, 5); - CHECK(firstTest() == &orderedTest2); - CHECK(secondTest() == &orderedTest); -} - -TEST(TestOrderedTest, MultipleOrderedTests) -{ - InstallNormalTest(normalTest); - InstallOrderedTest(orderedTest2, 3); - InstallNormalTest(normalTest2); - InstallOrderedTest(orderedTest, 5); - InstallNormalTest(normalTest3); - InstallOrderedTest(orderedTest3, 7); - - UtestShell * firstOrderedTest = firstTest()->getNext()->getNext()->getNext(); - CHECK(firstOrderedTest == &orderedTest2); - CHECK(firstOrderedTest->getNext() == &orderedTest); - CHECK(firstOrderedTest->getNext()->getNext() == &orderedTest3); -} - -TEST(TestOrderedTest, MultipleOrderedTests2) -{ - InstallOrderedTest(orderedTest, 3); - InstallOrderedTest(orderedTest2, 1); - InstallOrderedTest(orderedTest3, 2); - - CHECK(firstTest() == &orderedTest2); - CHECK(secondTest() == &orderedTest3); - CHECK(secondTest()->getNext() == &orderedTest); - -} - -TEST_GROUP(TestOrderedTestMacros) -{ -}; - -static int testNumber = 0; - -TEST(TestOrderedTestMacros, NormalTest) -{ - CHECK(testNumber == 0); - testNumber++; -} - -TEST_ORDERED(TestOrderedTestMacros, Test2, 2) -{ - CHECK(testNumber == 2); - testNumber++; -} - -TEST_ORDERED(TestOrderedTestMacros, Test1, 1) -{ - CHECK(testNumber == 1); - testNumber++; -} - -TEST_ORDERED(TestOrderedTestMacros, Test4, 4) -{ - CHECK(testNumber == 4); - testNumber++; -} - -TEST_ORDERED(TestOrderedTestMacros, Test3, 3) -{ - CHECK(testNumber == 3); - testNumber++; -} +/* + * 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/TestRegistry.h" +#include "CppUTest/TestTestingFixture.h" +#include "CppUTestExt/OrderedTest.h" + +TEST_GROUP(TestOrderedTest) +{ + TestTestingFixture* fixture; + + OrderedTestShell orderedTest; + OrderedTestShell orderedTest2; + OrderedTestShell orderedTest3; + ExecFunctionTestShell normalTest; + ExecFunctionTestShell normalTest2; + ExecFunctionTestShell normalTest3; + + OrderedTestShell* orderedTestCache; + void setup() + { + orderedTestCache = OrderedTestShell::getOrderedTestHead(); + OrderedTestShell::setOrderedTestHead(0); + + fixture = new TestTestingFixture(); + fixture->registry_->unDoLastAddTest(); + } + + void teardown() + { + delete fixture; + OrderedTestShell::setOrderedTestHead(orderedTestCache); + } + + void InstallOrderedTest(OrderedTestShell& test, int level) + { + OrderedTestInstaller(test, "testgroup", "testname", __FILE__, __LINE__, level); + } + + void InstallNormalTest(UtestShell& test) + { + TestInstaller(test, "testgroup", "testname", __FILE__, __LINE__); + } + + UtestShell* firstTest() + { + return fixture->registry_->getFirstTest(); + } + + UtestShell* secondTest() + { + return fixture->registry_->getFirstTest()->getNext(); + } +}; + +TEST(TestOrderedTest, TestInstallerSetsFields) +{ + OrderedTestInstaller(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()); + LONGS_EQUAL(10, orderedTest.getLineNumber()); + LONGS_EQUAL(5, orderedTest.getLevel()); +} + +TEST(TestOrderedTest, InstallOneText) +{ + InstallOrderedTest(orderedTest, 5); + CHECK(firstTest() == &orderedTest); +} + +TEST(TestOrderedTest, OrderedTestsAreLast) +{ + InstallNormalTest(normalTest); + InstallOrderedTest(orderedTest, 5); + CHECK(firstTest() == &normalTest); + CHECK(secondTest() == &orderedTest); +} + +TEST(TestOrderedTest, TwoTestsAddedInReverseOrder) +{ + InstallOrderedTest(orderedTest, 5); + InstallOrderedTest(orderedTest2, 3); + CHECK(firstTest() == &orderedTest2); + CHECK(secondTest() == &orderedTest); +} + +TEST(TestOrderedTest, TwoTestsAddedInOrder) +{ + InstallOrderedTest(orderedTest2, 3); + InstallOrderedTest(orderedTest, 5); + CHECK(firstTest() == &orderedTest2); + CHECK(secondTest() == &orderedTest); +} + +TEST(TestOrderedTest, MultipleOrderedTests) +{ + InstallNormalTest(normalTest); + InstallOrderedTest(orderedTest2, 3); + InstallNormalTest(normalTest2); + InstallOrderedTest(orderedTest, 5); + InstallNormalTest(normalTest3); + InstallOrderedTest(orderedTest3, 7); + + UtestShell * firstOrderedTest = firstTest()->getNext()->getNext()->getNext(); + CHECK(firstOrderedTest == &orderedTest2); + CHECK(firstOrderedTest->getNext() == &orderedTest); + CHECK(firstOrderedTest->getNext()->getNext() == &orderedTest3); +} + +TEST(TestOrderedTest, MultipleOrderedTests2) +{ + InstallOrderedTest(orderedTest, 3); + InstallOrderedTest(orderedTest2, 1); + InstallOrderedTest(orderedTest3, 2); + + CHECK(firstTest() == &orderedTest2); + CHECK(secondTest() == &orderedTest3); + CHECK(secondTest()->getNext() == &orderedTest); + +} + +TEST_GROUP(TestOrderedTestMacros) +{ +}; + +static int testNumber = 0; + +TEST(TestOrderedTestMacros, NormalTest) +{ + CHECK(testNumber == 0); + testNumber++; +} + +TEST_ORDERED(TestOrderedTestMacros, Test2, 2) +{ + CHECK(testNumber == 2); + testNumber++; +} + +TEST_ORDERED(TestOrderedTestMacros, Test1, 1) +{ + CHECK(testNumber == 1); + testNumber++; +} + +TEST_ORDERED(TestOrderedTestMacros, Test4, 4) +{ + CHECK(testNumber == 4); + testNumber++; +} + +TEST_ORDERED(TestOrderedTestMacros, Test3, 3) +{ + CHECK(testNumber == 3); + testNumber++; +} diff --git a/tests/JUnitOutputTest.cpp b/tests/JUnitOutputTest.cpp index 983e5d102..e2ace6ea6 100644 --- a/tests/JUnitOutputTest.cpp +++ b/tests/JUnitOutputTest.cpp @@ -1,591 +1,591 @@ -/* - * 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/JUnitTestOutput.h" -#include "CppUTest/TestResult.h" -#include "CppUTest/PlatformSpecificFunctions.h" -#include "CppUTest/SimpleString.h" - -class FileForJUnitOutputTests -{ - SimpleString name_; - bool isOpen_; - SimpleString buffer_; - FileForJUnitOutputTests* next_; - - SimpleStringCollection linesOfFile_; - -public: - - FileForJUnitOutputTests(SimpleString filename, FileForJUnitOutputTests* next) : - name_(filename), isOpen_(true), next_(next) {} - - FileForJUnitOutputTests* nextFile() - { - return next_; - } - - SimpleString name() - { - return name_; - } - - void write(const SimpleString& buffer) - { - buffer_ += buffer; - } - - void close() - { - isOpen_ = false; - } - - const char* line(size_t lineNumber) - { - buffer_.split("\n", linesOfFile_); - return linesOfFile_[lineNumber-1].asCharString(); - - } - const char* lineFromTheBack(size_t lineNumberFromTheBack) - { - return line(amountOfLines() - (lineNumberFromTheBack - 1)); - } - - size_t amountOfLines() - { - buffer_.split("\n", linesOfFile_); - return linesOfFile_.size(); - } - - SimpleString content() - { - return buffer_; - } -}; - -class FileSystemForJUnitTestOutputTests -{ - FileForJUnitOutputTests* firstFile_; - -public: - FileSystemForJUnitTestOutputTests() : firstFile_(0) {} - ~FileSystemForJUnitTestOutputTests() - { - while (firstFile_) { - FileForJUnitOutputTests* fileToBeDeleted = firstFile_; - firstFile_ = firstFile_->nextFile(); - delete fileToBeDeleted; - } - } - - FileForJUnitOutputTests* openFile(const SimpleString& filename) - { - firstFile_ = new FileForJUnitOutputTests(filename, firstFile_); - return firstFile_; - } - - int amountOfFiles() { - int totalAmountOfFiles = 0; - for (FileForJUnitOutputTests* current = firstFile_; current != NULL; current = current->nextFile()) - totalAmountOfFiles++; - return totalAmountOfFiles; - } - - bool fileExists(const char* filename) - { - FileForJUnitOutputTests *searchedFile = file(filename); - return (searchedFile != NULL); - } - - FileForJUnitOutputTests* file(const char* filename) - { - for (FileForJUnitOutputTests* current = firstFile_; current != NULL; current = current->nextFile()) - if (current->name() == filename) - return current; - return NULL; - } -}; - -class JUnitTestOutputToBuffer : public JUnitTestOutput -{ -public: - - FileSystemForJUnitTestOutputTests& fileSystem_; - FileForJUnitOutputTests* currentOpenFile_; - - JUnitTestOutputToBuffer(FileSystemForJUnitTestOutputTests& fileSystem) - : fileSystem_(fileSystem), currentOpenFile_(0) {} - - void writeToFile(const SimpleString& buffer) - { - currentOpenFile_->write(buffer); - } - - void openFileForWrite(const SimpleString& filename) - { - currentOpenFile_ = fileSystem_.openFile(filename); - } - - void closeFile() - { - currentOpenFile_->close(); - currentOpenFile_ = 0; - } -}; - -extern "C" { - static long millisTime = 0; - static const char* theTime = ""; - - static long MockGetPlatformSpecificTimeInMillis() - { - return millisTime; - } - - static const char* MockGetPlatformSpecificTimeString() - { - return theTime; - } -} - -class JUnitTestOutputTestRunner -{ - TestResult result_; - - const char* currentGroupName_; - UtestShell* currentTest_; - bool firstTestInGroup_; - int timeTheTestTakes_; - TestFailure* testFailure_; - - -public: - - JUnitTestOutputTestRunner(TestResult result) : - result_(result), currentGroupName_(0), currentTest_(0), firstTestInGroup_(true), timeTheTestTakes_(0), testFailure_(0) - { - millisTime = 0; - theTime = "1978-10-03T00:00:00"; - - SetPlatformSpecificTimeInMillisMethod(MockGetPlatformSpecificTimeInMillis); - SetPlatformSpecificTimeStringMethod(MockGetPlatformSpecificTimeString); - } - - ~JUnitTestOutputTestRunner() - { - SetPlatformSpecificTimeInMillisMethod(0); - SetPlatformSpecificTimeStringMethod(0); - } - - JUnitTestOutputTestRunner& start() - { - result_.testsStarted(); - return *this; - } - - JUnitTestOutputTestRunner& end() - { - endOfPreviousTestGroup(); - delete currentTest_; - result_.testsEnded(); - return *this; - } - - void endOfPreviousTestGroup() - { - runPreviousTest(); - if (currentTest_) { - result_.currentGroupEnded(currentTest_); - firstTestInGroup_ = true; - } - - currentGroupName_ = 0; - } - - JUnitTestOutputTestRunner& withGroup(const char* groupName) - { - runPreviousTest(); - endOfPreviousTestGroup(); - - currentGroupName_ = groupName; - return *this; - } - - JUnitTestOutputTestRunner& withTest(const char* testName) - { - runPreviousTest(); - delete currentTest_; - - currentTest_ = new UtestShell(currentGroupName_, testName, "file", 1); - return *this; - } - - void runPreviousTest() - { - if (currentTest_ == 0) return; - - if (firstTestInGroup_) { - result_.currentGroupStarted(currentTest_); - firstTestInGroup_ = false; - } - result_.currentTestStarted(currentTest_); - - millisTime += timeTheTestTakes_; - - if (testFailure_) { - result_.addFailure(*testFailure_); - delete testFailure_; - testFailure_ = 0; - } - - - result_.currentTestEnded(currentTest_); - } - - - JUnitTestOutputTestRunner& thatTakes(int timeElapsed) - { - timeTheTestTakes_ = timeElapsed; - return *this; - } - - JUnitTestOutputTestRunner& seconds() - { - return *this; - } - - JUnitTestOutputTestRunner& thatFails(const char* message, const char* file, int line) - { - testFailure_ = new TestFailure( currentTest_, file, line, message); - return *this; - } - - JUnitTestOutputTestRunner& atTime(const char* newTime) - { - theTime = newTime; - return *this; - } -}; - -TEST_GROUP(JUnitOutputTest) -{ - FileSystemForJUnitTestOutputTests fileSystem; - - JUnitTestOutputToBuffer *junitOutput; - TestResult *result; - JUnitTestOutputTestRunner *testCaseRunner; - FileForJUnitOutputTests* outputFile; - - void setup() - { - junitOutput = new JUnitTestOutputToBuffer (fileSystem); - result = new TestResult(*junitOutput); - testCaseRunner = new JUnitTestOutputTestRunner(*result); - } - - void teardown() - { - delete testCaseRunner; - delete result; - delete junitOutput; - } -}; - -TEST(JUnitOutputTest, withOneTestGroupAndOneTestOnlyWriteToOneFile) -{ - testCaseRunner->start() - .withGroup("groupname").withTest("testname") - .end(); - - LONGS_EQUAL(1, fileSystem.amountOfFiles()); - CHECK(fileSystem.fileExists("cpputest_groupname.xml")); -} - -TEST(JUnitOutputTest, withOneTestGroupAndOneTestOutputsValidXMLFiles) -{ - testCaseRunner->start() - .withGroup("groupname").withTest("testname") - .end(); - - outputFile = fileSystem.file("cpputest_groupname.xml"); - STRCMP_EQUAL("\n", outputFile->line(1)); -} - -TEST(JUnitOutputTest, withOneTestGroupAndOneTestoutputsTestSuiteStartAndEndBlocks) -{ - testCaseRunner->start() - .withGroup("groupname").withTest("testname") - .end(); - - outputFile = fileSystem.file("cpputest_groupname.xml"); - STRCMP_EQUAL("\n", outputFile->line(2)); - STRCMP_EQUAL("", outputFile->lineFromTheBack(1)); -} - -TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainAnEmptyPropertiesBlock) -{ - testCaseRunner->start() - .withGroup("groupname").withTest("testname") - .end(); - - outputFile = fileSystem.file("cpputest_groupname.xml"); - STRCMP_EQUAL("\n", outputFile->line(3)); - STRCMP_EQUAL("\n", outputFile->line(4)); -} - -TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainAnEmptyStdoutBlock) -{ - testCaseRunner->start() - .withGroup("groupname").withTest("testname") - .end(); - - outputFile = fileSystem.file("cpputest_groupname.xml"); - STRCMP_EQUAL("\n", outputFile->lineFromTheBack(3)); -} - -TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainAnEmptyStderrBlock) -{ - testCaseRunner->start() - .withGroup("groupname").withTest("testname") - .end(); - - outputFile = fileSystem.file("cpputest_groupname.xml"); - STRCMP_EQUAL("\n", outputFile->lineFromTheBack(2)); -} - -TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainsATestCaseBlock) -{ - testCaseRunner->start() - .withGroup("groupname").withTest("testname") - .end(); - - outputFile = fileSystem.file("cpputest_groupname.xml"); - - STRCMP_EQUAL("\n", outputFile->line(5)); - STRCMP_EQUAL("\n", outputFile->line(6)); -} - -TEST(JUnitOutputTest, withOneTestGroupAndTwoTestCasesCreateCorrectTestgroupBlockAndCorrectTestCaseBlock) -{ - testCaseRunner->start() - .withGroup("twoTestsGroup").withTest("firstTestName").withTest("secondTestName") - .end(); - - outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); - - STRCMP_EQUAL("\n", outputFile->line(2)); - STRCMP_EQUAL("\n", outputFile->line(5)); - STRCMP_EQUAL("\n", outputFile->line(6)); - STRCMP_EQUAL("\n", outputFile->line(7)); - STRCMP_EQUAL("\n", outputFile->line(8)); -} - -TEST(JUnitOutputTest, withOneTestGroupAndTimeHasElapsedAndTimestampChanged) -{ - testCaseRunner->start().atTime("2013-07-04T22:28:00") - .withGroup("timeGroup").withTest("Dummy").thatTakes(10).seconds() - .end(); - - outputFile = fileSystem.file("cpputest_timeGroup.xml"); - - STRCMP_EQUAL("\n", outputFile->line(2)); -} - -TEST(JUnitOutputTest, withOneTestGroupAndMultipleTestCasesWithElapsedTime) -{ - testCaseRunner->start() - .withGroup("twoTestsGroup") - .withTest("firstTestName").thatTakes(10).seconds() - .withTest("secondTestName").thatTakes(50).seconds() - .end(); - - outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); - STRCMP_EQUAL("\n", outputFile->line(2)); - STRCMP_EQUAL("\n", outputFile->line(5)); - STRCMP_EQUAL("\n", outputFile->line(6)); - STRCMP_EQUAL("\n", outputFile->line(7)); - STRCMP_EQUAL("\n", outputFile->line(8)); -} - -TEST(JUnitOutputTest, withOneTestGroupAndOneFailingTest) -{ - testCaseRunner->start() - .withGroup("testGroupWithFailingTest") - .withTest("FailingTestName").thatFails("Test failed", "thisfile", 10) - .end(); - - outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); - STRCMP_EQUAL("\n", outputFile->line(2)); - STRCMP_EQUAL("\n", outputFile->line(5)); - STRCMP_EQUAL("\n", outputFile->line(6)); - STRCMP_EQUAL("\n", outputFile->line(7)); - STRCMP_EQUAL("\n", outputFile->line(8)); -} - -TEST(JUnitOutputTest, withTwoTestGroupAndOneFailingTest) -{ - testCaseRunner->start() - .withGroup("testGroupWithFailingTest") - .withTest("FirstTest") - .withTest("FailingTestName").thatFails("Test failed", "thisfile", 10) - .end(); - - outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); - - STRCMP_EQUAL("\n", outputFile->line(2)); - STRCMP_EQUAL("\n", outputFile->line(7)); - STRCMP_EQUAL("\n", outputFile->line(8)); -} - -TEST(JUnitOutputTest, testFailureWithLessThanAndGreaterThanInsideIt) -{ - testCaseRunner->start() - .withGroup("testGroupWithFailingTest") - .withTest("FailingTestName").thatFails("Test ", "thisfile", 10) - .end(); - - outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); - - STRCMP_EQUAL("\n", outputFile->line(6)); -} - -TEST(JUnitOutputTest, testFailureWithQuotesInIt) -{ - testCaseRunner->start() - .withGroup("testGroupWithFailingTest") - .withTest("FailingTestName").thatFails("Test \"failed\"", "thisfile", 10) - .end(); - - outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); - - STRCMP_EQUAL("\n", outputFile->line(6)); -} - -TEST(JUnitOutputTest, testFailureWithNewlineInIt) -{ - testCaseRunner->start() - .withGroup("testGroupWithFailingTest") - .withTest("FailingTestName").thatFails("Test \nfailed", "thisfile", 10) - .end(); - - outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); - - STRCMP_EQUAL("\n", outputFile->line(6)); -} - -TEST(JUnitOutputTest, testFailureWithDifferentFileAndLine) -{ - testCaseRunner->start() - .withGroup("testGroupWithFailingTest") - .withTest("FailingTestName").thatFails("Test failed", "importantFile", 999) - .end(); - - outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); - - STRCMP_EQUAL("\n", outputFile->line(6)); -} - -TEST(JUnitOutputTest, testFailureWithAmpersands) -{ - 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, aCoupleOfTestFailures) -{ - testCaseRunner->start() - .withGroup("testGroup") - .withTest("passingOne") - .withTest("FailingTest").thatFails("Failure", "file", 99) - .withTest("passingTwo") - .withTest("passingThree") - .withTest("AnotherFailingTest").thatFails("otherFailure", "anotherFile", 10) - .end(); - - outputFile = fileSystem.file("cpputest_testGroup.xml"); - - STRCMP_EQUAL("\n", outputFile->line(8)); - STRCMP_EQUAL("\n", outputFile->line(16)); -} - -TEST(JUnitOutputTest, testFailuresInSeparateGroups) -{ - testCaseRunner->start() - .withGroup("testGroup") - .withTest("passingOne") - .withTest("FailingTest").thatFails("Failure", "file", 99) - .withGroup("AnotherGroup") - .withTest("AnotherFailingTest").thatFails("otherFailure", "anotherFile", 10) - .end(); - - outputFile = fileSystem.file("cpputest_testGroup.xml"); - - STRCMP_EQUAL("\n", outputFile->line(8)); - - outputFile = fileSystem.file("cpputest_AnotherGroup.xml"); - STRCMP_EQUAL("\n", outputFile->line(8)); -} - -TEST(JUnitOutputTest, twoTestGroupsWriteToTwoDifferentFiles) -{ - testCaseRunner->start() - .withGroup("firstTestGroup") - .withTest("testName") - .withGroup("secondTestGroup") - .withTest("testName") - .end(); - - CHECK(fileSystem.file("cpputest_firstTestGroup.xml")); - CHECK(fileSystem.file("cpputest_secondTestGroup.xml")); - -} - -TEST(JUnitOutputTest, testGroupWithWeirdName) -{ - STRCMP_EQUAL("cpputest_group_weird_name.xml", junitOutput->createFileName("group/weird/name").asCharString()); -} - -TEST(JUnitOutputTest, TestCaseBlockWithAPackageName) -{ - junitOutput->setPackageName("packagename"); - testCaseRunner->start() - .withGroup("groupname").withTest("testname") - .end(); - - outputFile = fileSystem.file("cpputest_groupname.xml"); - - STRCMP_EQUAL("\n", outputFile->line(5)); - STRCMP_EQUAL("\n", outputFile->line(6)); -} - +/* + * 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/JUnitTestOutput.h" +#include "CppUTest/TestResult.h" +#include "CppUTest/PlatformSpecificFunctions.h" +#include "CppUTest/SimpleString.h" + +class FileForJUnitOutputTests +{ + SimpleString name_; + bool isOpen_; + SimpleString buffer_; + FileForJUnitOutputTests* next_; + + SimpleStringCollection linesOfFile_; + +public: + + FileForJUnitOutputTests(SimpleString filename, FileForJUnitOutputTests* next) : + name_(filename), isOpen_(true), next_(next) {} + + FileForJUnitOutputTests* nextFile() + { + return next_; + } + + SimpleString name() + { + return name_; + } + + void write(const SimpleString& buffer) + { + buffer_ += buffer; + } + + void close() + { + isOpen_ = false; + } + + const char* line(size_t lineNumber) + { + buffer_.split("\n", linesOfFile_); + return linesOfFile_[lineNumber-1].asCharString(); + + } + const char* lineFromTheBack(size_t lineNumberFromTheBack) + { + return line(amountOfLines() - (lineNumberFromTheBack - 1)); + } + + size_t amountOfLines() + { + buffer_.split("\n", linesOfFile_); + return linesOfFile_.size(); + } + + SimpleString content() + { + return buffer_; + } +}; + +class FileSystemForJUnitTestOutputTests +{ + FileForJUnitOutputTests* firstFile_; + +public: + FileSystemForJUnitTestOutputTests() : firstFile_(0) {} + ~FileSystemForJUnitTestOutputTests() + { + while (firstFile_) { + FileForJUnitOutputTests* fileToBeDeleted = firstFile_; + firstFile_ = firstFile_->nextFile(); + delete fileToBeDeleted; + } + } + + FileForJUnitOutputTests* openFile(const SimpleString& filename) + { + firstFile_ = new FileForJUnitOutputTests(filename, firstFile_); + return firstFile_; + } + + int amountOfFiles() { + int totalAmountOfFiles = 0; + for (FileForJUnitOutputTests* current = firstFile_; current != NULL; current = current->nextFile()) + totalAmountOfFiles++; + return totalAmountOfFiles; + } + + bool fileExists(const char* filename) + { + FileForJUnitOutputTests *searchedFile = file(filename); + return (searchedFile != NULL); + } + + FileForJUnitOutputTests* file(const char* filename) + { + for (FileForJUnitOutputTests* current = firstFile_; current != NULL; current = current->nextFile()) + if (current->name() == filename) + return current; + return NULL; + } +}; + +class JUnitTestOutputToBuffer : public JUnitTestOutput +{ +public: + + FileSystemForJUnitTestOutputTests& fileSystem_; + FileForJUnitOutputTests* currentOpenFile_; + + JUnitTestOutputToBuffer(FileSystemForJUnitTestOutputTests& fileSystem) + : fileSystem_(fileSystem), currentOpenFile_(0) {} + + void writeToFile(const SimpleString& buffer) + { + currentOpenFile_->write(buffer); + } + + void openFileForWrite(const SimpleString& filename) + { + currentOpenFile_ = fileSystem_.openFile(filename); + } + + void closeFile() + { + currentOpenFile_->close(); + currentOpenFile_ = 0; + } +}; + +extern "C" { + static long millisTime = 0; + static const char* theTime = ""; + + static long MockGetPlatformSpecificTimeInMillis() + { + return millisTime; + } + + static const char* MockGetPlatformSpecificTimeString() + { + return theTime; + } +} + +class JUnitTestOutputTestRunner +{ + TestResult result_; + + const char* currentGroupName_; + UtestShell* currentTest_; + bool firstTestInGroup_; + int timeTheTestTakes_; + TestFailure* testFailure_; + + +public: + + JUnitTestOutputTestRunner(TestResult result) : + result_(result), currentGroupName_(0), currentTest_(0), firstTestInGroup_(true), timeTheTestTakes_(0), testFailure_(0) + { + millisTime = 0; + theTime = "1978-10-03T00:00:00"; + + SetPlatformSpecificTimeInMillisMethod(MockGetPlatformSpecificTimeInMillis); + SetPlatformSpecificTimeStringMethod(MockGetPlatformSpecificTimeString); + } + + ~JUnitTestOutputTestRunner() + { + SetPlatformSpecificTimeInMillisMethod(0); + SetPlatformSpecificTimeStringMethod(0); + } + + JUnitTestOutputTestRunner& start() + { + result_.testsStarted(); + return *this; + } + + JUnitTestOutputTestRunner& end() + { + endOfPreviousTestGroup(); + delete currentTest_; + result_.testsEnded(); + return *this; + } + + void endOfPreviousTestGroup() + { + runPreviousTest(); + if (currentTest_) { + result_.currentGroupEnded(currentTest_); + firstTestInGroup_ = true; + } + + currentGroupName_ = 0; + } + + JUnitTestOutputTestRunner& withGroup(const char* groupName) + { + runPreviousTest(); + endOfPreviousTestGroup(); + + currentGroupName_ = groupName; + return *this; + } + + JUnitTestOutputTestRunner& withTest(const char* testName) + { + runPreviousTest(); + delete currentTest_; + + currentTest_ = new UtestShell(currentGroupName_, testName, "file", 1); + return *this; + } + + void runPreviousTest() + { + if (currentTest_ == 0) return; + + if (firstTestInGroup_) { + result_.currentGroupStarted(currentTest_); + firstTestInGroup_ = false; + } + result_.currentTestStarted(currentTest_); + + millisTime += timeTheTestTakes_; + + if (testFailure_) { + result_.addFailure(*testFailure_); + delete testFailure_; + testFailure_ = 0; + } + + + result_.currentTestEnded(currentTest_); + } + + + JUnitTestOutputTestRunner& thatTakes(int timeElapsed) + { + timeTheTestTakes_ = timeElapsed; + return *this; + } + + JUnitTestOutputTestRunner& seconds() + { + return *this; + } + + JUnitTestOutputTestRunner& thatFails(const char* message, const char* file, int line) + { + testFailure_ = new TestFailure( currentTest_, file, line, message); + return *this; + } + + JUnitTestOutputTestRunner& atTime(const char* newTime) + { + theTime = newTime; + return *this; + } +}; + +TEST_GROUP(JUnitOutputTest) +{ + FileSystemForJUnitTestOutputTests fileSystem; + + JUnitTestOutputToBuffer *junitOutput; + TestResult *result; + JUnitTestOutputTestRunner *testCaseRunner; + FileForJUnitOutputTests* outputFile; + + void setup() + { + junitOutput = new JUnitTestOutputToBuffer (fileSystem); + result = new TestResult(*junitOutput); + testCaseRunner = new JUnitTestOutputTestRunner(*result); + } + + void teardown() + { + delete testCaseRunner; + delete result; + delete junitOutput; + } +}; + +TEST(JUnitOutputTest, withOneTestGroupAndOneTestOnlyWriteToOneFile) +{ + testCaseRunner->start() + .withGroup("groupname").withTest("testname") + .end(); + + LONGS_EQUAL(1, fileSystem.amountOfFiles()); + CHECK(fileSystem.fileExists("cpputest_groupname.xml")); +} + +TEST(JUnitOutputTest, withOneTestGroupAndOneTestOutputsValidXMLFiles) +{ + testCaseRunner->start() + .withGroup("groupname").withTest("testname") + .end(); + + outputFile = fileSystem.file("cpputest_groupname.xml"); + STRCMP_EQUAL("\n", outputFile->line(1)); +} + +TEST(JUnitOutputTest, withOneTestGroupAndOneTestoutputsTestSuiteStartAndEndBlocks) +{ + testCaseRunner->start() + .withGroup("groupname").withTest("testname") + .end(); + + outputFile = fileSystem.file("cpputest_groupname.xml"); + STRCMP_EQUAL("\n", outputFile->line(2)); + STRCMP_EQUAL("", outputFile->lineFromTheBack(1)); +} + +TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainAnEmptyPropertiesBlock) +{ + testCaseRunner->start() + .withGroup("groupname").withTest("testname") + .end(); + + outputFile = fileSystem.file("cpputest_groupname.xml"); + STRCMP_EQUAL("\n", outputFile->line(3)); + STRCMP_EQUAL("\n", outputFile->line(4)); +} + +TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainAnEmptyStdoutBlock) +{ + testCaseRunner->start() + .withGroup("groupname").withTest("testname") + .end(); + + outputFile = fileSystem.file("cpputest_groupname.xml"); + STRCMP_EQUAL("\n", outputFile->lineFromTheBack(3)); +} + +TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainAnEmptyStderrBlock) +{ + testCaseRunner->start() + .withGroup("groupname").withTest("testname") + .end(); + + outputFile = fileSystem.file("cpputest_groupname.xml"); + STRCMP_EQUAL("\n", outputFile->lineFromTheBack(2)); +} + +TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainsATestCaseBlock) +{ + testCaseRunner->start() + .withGroup("groupname").withTest("testname") + .end(); + + outputFile = fileSystem.file("cpputest_groupname.xml"); + + STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(6)); +} + +TEST(JUnitOutputTest, withOneTestGroupAndTwoTestCasesCreateCorrectTestgroupBlockAndCorrectTestCaseBlock) +{ + testCaseRunner->start() + .withGroup("twoTestsGroup").withTest("firstTestName").withTest("secondTestName") + .end(); + + outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); + + STRCMP_EQUAL("\n", outputFile->line(2)); + STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(6)); + STRCMP_EQUAL("\n", outputFile->line(7)); + STRCMP_EQUAL("\n", outputFile->line(8)); +} + +TEST(JUnitOutputTest, withOneTestGroupAndTimeHasElapsedAndTimestampChanged) +{ + testCaseRunner->start().atTime("2013-07-04T22:28:00") + .withGroup("timeGroup").withTest("Dummy").thatTakes(10).seconds() + .end(); + + outputFile = fileSystem.file("cpputest_timeGroup.xml"); + + STRCMP_EQUAL("\n", outputFile->line(2)); +} + +TEST(JUnitOutputTest, withOneTestGroupAndMultipleTestCasesWithElapsedTime) +{ + testCaseRunner->start() + .withGroup("twoTestsGroup") + .withTest("firstTestName").thatTakes(10).seconds() + .withTest("secondTestName").thatTakes(50).seconds() + .end(); + + outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); + STRCMP_EQUAL("\n", outputFile->line(2)); + STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(6)); + STRCMP_EQUAL("\n", outputFile->line(7)); + STRCMP_EQUAL("\n", outputFile->line(8)); +} + +TEST(JUnitOutputTest, withOneTestGroupAndOneFailingTest) +{ + testCaseRunner->start() + .withGroup("testGroupWithFailingTest") + .withTest("FailingTestName").thatFails("Test failed", "thisfile", 10) + .end(); + + outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); + STRCMP_EQUAL("\n", outputFile->line(2)); + STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(6)); + STRCMP_EQUAL("\n", outputFile->line(7)); + STRCMP_EQUAL("\n", outputFile->line(8)); +} + +TEST(JUnitOutputTest, withTwoTestGroupAndOneFailingTest) +{ + testCaseRunner->start() + .withGroup("testGroupWithFailingTest") + .withTest("FirstTest") + .withTest("FailingTestName").thatFails("Test failed", "thisfile", 10) + .end(); + + outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); + + STRCMP_EQUAL("\n", outputFile->line(2)); + STRCMP_EQUAL("\n", outputFile->line(7)); + STRCMP_EQUAL("\n", outputFile->line(8)); +} + +TEST(JUnitOutputTest, testFailureWithLessThanAndGreaterThanInsideIt) +{ + testCaseRunner->start() + .withGroup("testGroupWithFailingTest") + .withTest("FailingTestName").thatFails("Test ", "thisfile", 10) + .end(); + + outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); + + STRCMP_EQUAL("\n", outputFile->line(6)); +} + +TEST(JUnitOutputTest, testFailureWithQuotesInIt) +{ + testCaseRunner->start() + .withGroup("testGroupWithFailingTest") + .withTest("FailingTestName").thatFails("Test \"failed\"", "thisfile", 10) + .end(); + + outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); + + STRCMP_EQUAL("\n", outputFile->line(6)); +} + +TEST(JUnitOutputTest, testFailureWithNewlineInIt) +{ + testCaseRunner->start() + .withGroup("testGroupWithFailingTest") + .withTest("FailingTestName").thatFails("Test \nfailed", "thisfile", 10) + .end(); + + outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); + + STRCMP_EQUAL("\n", outputFile->line(6)); +} + +TEST(JUnitOutputTest, testFailureWithDifferentFileAndLine) +{ + testCaseRunner->start() + .withGroup("testGroupWithFailingTest") + .withTest("FailingTestName").thatFails("Test failed", "importantFile", 999) + .end(); + + outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); + + STRCMP_EQUAL("\n", outputFile->line(6)); +} + +TEST(JUnitOutputTest, testFailureWithAmpersands) +{ + 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, aCoupleOfTestFailures) +{ + testCaseRunner->start() + .withGroup("testGroup") + .withTest("passingOne") + .withTest("FailingTest").thatFails("Failure", "file", 99) + .withTest("passingTwo") + .withTest("passingThree") + .withTest("AnotherFailingTest").thatFails("otherFailure", "anotherFile", 10) + .end(); + + outputFile = fileSystem.file("cpputest_testGroup.xml"); + + STRCMP_EQUAL("\n", outputFile->line(8)); + STRCMP_EQUAL("\n", outputFile->line(16)); +} + +TEST(JUnitOutputTest, testFailuresInSeparateGroups) +{ + testCaseRunner->start() + .withGroup("testGroup") + .withTest("passingOne") + .withTest("FailingTest").thatFails("Failure", "file", 99) + .withGroup("AnotherGroup") + .withTest("AnotherFailingTest").thatFails("otherFailure", "anotherFile", 10) + .end(); + + outputFile = fileSystem.file("cpputest_testGroup.xml"); + + STRCMP_EQUAL("\n", outputFile->line(8)); + + outputFile = fileSystem.file("cpputest_AnotherGroup.xml"); + STRCMP_EQUAL("\n", outputFile->line(8)); +} + +TEST(JUnitOutputTest, twoTestGroupsWriteToTwoDifferentFiles) +{ + testCaseRunner->start() + .withGroup("firstTestGroup") + .withTest("testName") + .withGroup("secondTestGroup") + .withTest("testName") + .end(); + + CHECK(fileSystem.file("cpputest_firstTestGroup.xml")); + CHECK(fileSystem.file("cpputest_secondTestGroup.xml")); + +} + +TEST(JUnitOutputTest, testGroupWithWeirdName) +{ + STRCMP_EQUAL("cpputest_group_weird_name.xml", junitOutput->createFileName("group/weird/name").asCharString()); +} + +TEST(JUnitOutputTest, TestCaseBlockWithAPackageName) +{ + junitOutput->setPackageName("packagename"); + testCaseRunner->start() + .withGroup("groupname").withTest("testname") + .end(); + + outputFile = fileSystem.file("cpputest_groupname.xml"); + + STRCMP_EQUAL("\n", outputFile->line(5)); + STRCMP_EQUAL("\n", outputFile->line(6)); +} + diff --git a/tests/MemoryLeakDetectorTest.cpp b/tests/MemoryLeakDetectorTest.cpp index 3cc1a0e86..f302875a9 100644 --- a/tests/MemoryLeakDetectorTest.cpp +++ b/tests/MemoryLeakDetectorTest.cpp @@ -1,552 +1,552 @@ -/* - * 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 "CppUTest/TestMemoryAllocator.h" -#include "CppUTest/PlatformSpecificFunctions.h" - -class MemoryLeakFailureForTest: public MemoryLeakFailure -{ -public: - virtual ~MemoryLeakFailureForTest() - { - } - - virtual void fail(char* fail_string) - { - *message = fail_string; - } - - SimpleString *message; -}; - -class NewAllocatorForMemoryLeakDetectionTest: public TestMemoryAllocator -{ -public: - NewAllocatorForMemoryLeakDetectionTest() : - TestMemoryAllocator("Standard New Allocator", "new", "delete"), - alloc_called(0), free_called(0) - { - } - - int alloc_called; - int free_called; - char* alloc_memory(size_t size, const char*, int) - { - alloc_called++; - return TestMemoryAllocator::alloc_memory(size, "file", 1); - } - void free_memory(char* memory, const char* file, int line) - { - free_called++; - TestMemoryAllocator::free_memory(memory, file, line); - } -}; - -class AllocatorForMemoryLeakDetectionTest: public TestMemoryAllocator -{ -public: - AllocatorForMemoryLeakDetectionTest() : - alloc_called(0), free_called(0), allocMemoryLeakNodeCalled(0), freeMemoryLeakNodeCalled(0) - { - } - - int alloc_called; - int free_called; - int allocMemoryLeakNodeCalled; - int freeMemoryLeakNodeCalled; - - char* alloc_memory(size_t size, const char* file, int line) - { - alloc_called++; - return TestMemoryAllocator::alloc_memory(size, file, line); - } - void free_memory(char* memory, const char* file, int line) - { - free_called++; - TestMemoryAllocator::free_memory(memory, file, line); - } - - char* allocMemoryLeakNode(size_t size) - { - allocMemoryLeakNodeCalled++; - return TestMemoryAllocator::alloc_memory(size, __FILE__, __LINE__); - } - - void freeMemoryLeakNode(char* memory) - { - freeMemoryLeakNodeCalled++; - TestMemoryAllocator::free_memory(memory, __FILE__, __LINE__); - } -}; - -TEST_GROUP(MemoryLeakDetectorTest) -{ - MemoryLeakDetector* detector; - MemoryLeakFailureForTest *reporter; - AllocatorForMemoryLeakDetectionTest* testAllocator; - - void setup() - { - reporter = new MemoryLeakFailureForTest; - detector = new MemoryLeakDetector(reporter); - testAllocator = new AllocatorForMemoryLeakDetectionTest; - detector->enable(); - detector->startChecking(); - reporter->message = new SimpleString(); - } - void teardown() - { - delete reporter->message; - delete detector; - delete reporter; - delete testAllocator; - } -}; - -TEST(MemoryLeakDetectorTest, OneLeak) -{ - char* mem = detector->allocMemory(testAllocator, 3); - detector->stopChecking(); - SimpleString output = detector->report(mem_leak_period_checking); - STRCMP_CONTAINS("Memory leak(s) found", output.asCharString()); - STRCMP_CONTAINS("size: 3", output.asCharString()); - STRCMP_CONTAINS("alloc", output.asCharString()); - STRCMP_CONTAINS(StringFromFormat("%p", mem).asCharString(), output.asCharString()); - STRCMP_CONTAINS("Total number of leaks", output.asCharString()); - PlatformSpecificFree(mem); - LONGS_EQUAL(1, testAllocator->alloc_called); - LONGS_EQUAL(0, testAllocator->free_called); -} - -TEST(MemoryLeakDetectorTest, sequenceNumbersOfMemoryLeaks) -{ - char* mem = detector->allocMemory(defaultNewAllocator(), 1); - char* mem2 = detector->allocMemory(defaultNewAllocator(), 2); - char* mem3 = detector->allocMemory(defaultNewAllocator(), 3); - SimpleString output = detector->report(mem_leak_period_checking); - - STRCMP_CONTAINS("Alloc num (1)", output.asCharString()); - STRCMP_CONTAINS("Alloc num (2)", output.asCharString()); - STRCMP_CONTAINS("Alloc num (3)", output.asCharString()); - - PlatformSpecificFree(mem); - PlatformSpecificFree(mem2); - PlatformSpecificFree(mem3); -} - - -TEST(MemoryLeakDetectorTest, OneHundredLeaks) -{ - const int amount_alloc = 100; - char *mem[amount_alloc]; - for (int i = 0; i < amount_alloc; i++) - mem[i] = detector->allocMemory(defaultMallocAllocator(), 3); - detector->stopChecking(); - - SimpleString output = detector->report(mem_leak_period_checking); - - STRCMP_CONTAINS("Memory leak(s) found", output.asCharString()); - STRCMP_CONTAINS("Total number of leaks", output.asCharString()); - STRCMP_CONTAINS("Memory leak reports about malloc and free", output.asCharString()); - - //don't reuse i for vc6 compatibility - for (int j = 0; j < amount_alloc; j++) - PlatformSpecificFree(mem[j]); -} - -TEST(MemoryLeakDetectorTest, OneLeakOutsideCheckingPeriod) -{ - detector->stopChecking(); - char* mem = detector->allocMemory(defaultNewAllocator(), 4); - SimpleString output = detector->report(mem_leak_period_all); - CHECK(output.contains("Memory leak(s) found")); - CHECK(output.contains("size: 4")); - CHECK(output.contains("new")); - CHECK(output.contains("Total number of leaks")); - PlatformSpecificFree(mem); -} - -TEST(MemoryLeakDetectorTest, NoLeaksWhatsoever) -{ - detector->stopChecking(); - STRCMP_CONTAINS("No memory leaks", detector->report(mem_leak_period_checking)); - STRCMP_CONTAINS("No memory leaks", detector->report(mem_leak_period_all)); -} - -TEST(MemoryLeakDetectorTest, TwoLeaksUsingOperatorNew) -{ - char* mem = detector->allocMemory(defaultNewAllocator(), 4); - char* mem2 = detector->allocMemory(defaultNewAllocator(), 8); - detector->stopChecking(); - SimpleString output = detector->report(mem_leak_period_checking); - LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); - CHECK(output.contains("size: 8")); - CHECK(output.contains("size: 4")); - PlatformSpecificFree(mem); - PlatformSpecificFree(mem2); -} - -TEST(MemoryLeakDetectorTest, OneAllocButNoLeak) -{ - char* mem = detector->allocMemory(testAllocator, 4); - detector->deallocMemory(testAllocator, mem); - detector->stopChecking(); - STRCMP_CONTAINS("No memory leaks", detector->report(mem_leak_period_checking)); - LONGS_EQUAL(1, testAllocator->alloc_called); - LONGS_EQUAL(1, testAllocator->free_called); -} - -TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeak) -{ - char* mem = detector->allocMemory(testAllocator, 4); - char* mem2 = detector->allocMemory(testAllocator, 12); - detector->deallocMemory(testAllocator, mem); - detector->stopChecking(); - SimpleString output = detector->report(mem_leak_period_checking); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); - CHECK(output.contains("size: 12")); - CHECK(!output.contains("size: 4")); - PlatformSpecificFree(mem2); - LONGS_EQUAL(2, testAllocator->alloc_called); - LONGS_EQUAL(1, testAllocator->free_called); -} - -TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeakReverseOrder) -{ - char* mem = detector->allocMemory(defaultNewAllocator(), 4); - char* mem2 = detector->allocMemory(defaultNewAllocator(), 12); - detector->deallocMemory(defaultNewAllocator(), mem2); - detector->stopChecking(); - SimpleString output = detector->report(mem_leak_period_checking); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); - CHECK(!output.contains("size: 12")); - CHECK(output.contains("size: 4")); - PlatformSpecificFree(mem); -} - -TEST(MemoryLeakDetectorTest, DeleteNonAlocatedMemory) -{ - char a; - char* pa = &a; - detector->deallocMemory(defaultMallocAllocator(), pa, "FREE.c", 100); - detector->stopChecking(); - CHECK(reporter->message->contains("Deallocating non-allocated memory")); - CHECK(reporter->message->contains(" allocated at file: line: 0 size: 0 type: unknown")); - CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free")); -} - -TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriod) -{ - detector->stopChecking(); - char* mem = detector->allocMemory(defaultNewAllocator(), 4); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); - detector->deallocMemory(defaultNewAllocator(), mem); -} - -TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriodComplicatedCase) -{ - char* mem = detector->allocMemory(defaultNewAllocator(), 4); - detector->stopChecking(); - - char* mem2 = detector->allocMemory(defaultNewAllocator(), 8); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); - detector->clearAllAccounting(mem_leak_period_checking); - PlatformSpecificFree(mem); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); - - detector->startChecking(); - char* mem3 = detector->allocMemory(defaultNewAllocator(), 4); - detector->stopChecking(); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); - LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); - - detector->clearAllAccounting(mem_leak_period_checking); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); - - detector->clearAllAccounting(mem_leak_period_all); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); - PlatformSpecificFree(mem2); - PlatformSpecificFree(mem3); -} - -TEST(MemoryLeakDetectorTest, OneLeakUsingOperatorNewWithFileLine) -{ - char* mem = detector->allocMemory(defaultNewAllocator(), 4, "file.cpp", 1234); - detector->stopChecking(); - SimpleString output = detector->report(mem_leak_period_checking); - CHECK(output.contains("file.cpp")); - CHECK(output.contains("1234")); - PlatformSpecificFree(mem); -} - -TEST(MemoryLeakDetectorTest, OneAllocAndFreeUsingArrayNew) -{ - char* mem = detector->allocMemory(defaultNewArrayAllocator(), 10, "file.cpp", 1234); - char* mem2 = detector->allocMemory(defaultNewArrayAllocator(), 12); - LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); - SimpleString output = detector->report(mem_leak_period_checking); - CHECK(output.contains("new []")); - detector->deallocMemory(defaultNewArrayAllocator(), mem); - detector->deallocMemory(defaultNewArrayAllocator(), mem2); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); - detector->stopChecking(); -} - -TEST(MemoryLeakDetectorTest, OneAllocAndFree) -{ - char* mem = detector->allocMemory(defaultMallocAllocator(), 10, "file.cpp", 1234); - char* mem2 = detector->allocMemory(defaultMallocAllocator(), 12); - LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); - SimpleString output = detector->report(mem_leak_period_checking); - CHECK(output.contains("malloc")); - detector->deallocMemory(defaultMallocAllocator(), mem); - detector->deallocMemory(defaultMallocAllocator(), mem2, "file.c", 5678); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); - detector->stopChecking(); -} - -TEST(MemoryLeakDetectorTest, OneRealloc) -{ - char* mem1 = detector->allocMemory(testAllocator, 10, "file.cpp", 1234, true); - - char* mem2 = detector->reallocMemory(testAllocator, mem1, 1000, "other.cpp", 5678, true); - - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); - SimpleString output = detector->report(mem_leak_period_checking); - CHECK(output.contains("other.cpp")); - - detector->deallocMemory(testAllocator, mem2, true); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); - detector->stopChecking(); - LONGS_EQUAL(1, testAllocator->alloc_called); - LONGS_EQUAL(1, testAllocator->free_called); - LONGS_EQUAL(2, testAllocator->allocMemoryLeakNodeCalled); - LONGS_EQUAL(2, testAllocator->freeMemoryLeakNodeCalled); -} - -TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherType) -{ - char* mem = detector->allocMemory(defaultNewArrayAllocator(), 100, "ALLOC.c", 10); - detector->deallocMemory(defaultMallocAllocator(), mem, "FREE.c", 100); - detector->stopChecking(); - CHECK(reporter->message->contains("Allocation/deallocation type mismatch")); - CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 100 type: new []")); - CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free")); -} - -TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherTypeWithCheckingDisabled) -{ - detector->disableAllocationTypeChecking(); - char* mem = detector->allocMemory(defaultNewArrayAllocator(), 100, "ALLOC.c", 10); - detector->deallocMemory(defaultNewAllocator(), mem, "FREE.c", 100); - detector->stopChecking(); - STRCMP_EQUAL("", reporter->message->asCharString()); - detector->enableAllocationTypeChecking(); -} - -TEST(MemoryLeakDetectorTest, mallocLeakGivesAdditionalWarning) -{ - char* mem = detector->allocMemory(defaultMallocAllocator(), 100, "ALLOC.c", 10); - detector->stopChecking(); - SimpleString output = detector->report(mem_leak_period_checking); - STRCMP_CONTAINS("Memory leak reports about malloc and free can be caused by allocating using the cpputest version of malloc", output.asCharString()); - PlatformSpecificFree(mem); -} - -TEST(MemoryLeakDetectorTest, newLeakDoesNotGiveAdditionalWarning) -{ - char* mem = detector->allocMemory(defaultNewAllocator(), 100, "ALLOC.c", 10); - detector->stopChecking(); - SimpleString output = detector->report(mem_leak_period_checking); - CHECK(! output.contains("Memory leak reports about malloc and free")); - PlatformSpecificFree(mem); -} - -TEST(MemoryLeakDetectorTest, MarkCheckingPeriodLeaksAsNonCheckingPeriod) -{ - char* mem = detector->allocMemory(defaultNewArrayAllocator(), 100); - char* mem2 = detector->allocMemory(defaultNewArrayAllocator(), 100); - detector->stopChecking(); - LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); - LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); - detector->markCheckingPeriodLeaksAsNonCheckingPeriod(); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); - LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); - PlatformSpecificFree(mem); - PlatformSpecificFree(mem2); -} - -TEST(MemoryLeakDetectorTest, memoryCorruption) -{ - char* mem = detector->allocMemory(defaultMallocAllocator(), 10, "ALLOC.c", 10); - mem[10] = 'O'; - mem[11] = 'H'; - detector->deallocMemory(defaultMallocAllocator(), mem, "FREE.c", 100); - detector->stopChecking(); - CHECK(reporter->message->contains("Memory corruption")); - CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 10 type: malloc")); - CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free")); -} - -TEST(MemoryLeakDetectorTest, safelyDeleteNULL) -{ - detector->deallocMemory(defaultNewAllocator(), 0); - STRCMP_EQUAL("", reporter->message->asCharString()); -} - -TEST(MemoryLeakDetectorTest, periodDisabled) -{ - detector->disable(); - char* mem = detector->allocMemory(defaultMallocAllocator(), 2); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_disabled)); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_enabled)); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); - detector->deallocMemory(defaultMallocAllocator(), mem); -} - -TEST(MemoryLeakDetectorTest, periodEnabled) -{ - detector->enable(); - char* mem = detector->allocMemory(defaultMallocAllocator(), 2); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled)); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled)); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); - detector->deallocMemory(defaultMallocAllocator(), mem); -} - -TEST(MemoryLeakDetectorTest, periodChecking) -{ - char* mem = detector->allocMemory(defaultMallocAllocator(), 2); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); - LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled)); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled)); - LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); - detector->deallocMemory(defaultMallocAllocator(), mem); -} - -TEST(MemoryLeakDetectorTest, allocateWithANullAllocatorCausesNoProblems) -{ - char* mem = detector->allocMemory(NullUnknownAllocator::defaultAllocator(), 2); - detector->deallocMemory(NullUnknownAllocator::defaultAllocator(), mem); -} - -TEST(MemoryLeakDetectorTest, invalidateMemory) -{ - unsigned char* mem = (unsigned char*)detector->allocMemory(defaultMallocAllocator(), 2); - - detector->invalidateMemory((char*)mem); - CHECK(mem[0] == 0xCD); - CHECK(mem[1] == 0xCD); - detector->deallocMemory(defaultMallocAllocator(), mem); -} - -TEST(MemoryLeakDetectorTest, invalidateMemoryNULLShouldWork) -{ - detector->invalidateMemory(NULL); -} - -TEST_GROUP(SimpleStringBuffer) -{ -}; - -TEST(SimpleStringBuffer, simpleTest) -{ - SimpleStringBuffer buffer; - buffer.add("Hello"); - buffer.add(" World"); - STRCMP_EQUAL("Hello World", buffer.toString()); -} - -TEST(SimpleStringBuffer, writePastLimit) -{ - SimpleStringBuffer buffer; - for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN * 2; i++) - buffer.add("h"); - SimpleString str("h", SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN-1); - STRCMP_EQUAL(str.asCharString(), buffer.toString()); -} - -TEST(SimpleStringBuffer, setWriteLimit) -{ - SimpleStringBuffer buffer; - buffer.setWriteLimit(10); - for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN ; i++) - buffer.add("h"); - SimpleString str("h", 10); - STRCMP_EQUAL(str.asCharString(), buffer.toString()); -} - -TEST(SimpleStringBuffer, setWriteLimitTooHighIsIgnored) -{ - SimpleStringBuffer buffer; - buffer.setWriteLimit(SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN+10); - for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN+10; i++) - buffer.add("h"); - SimpleString str("h", SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN-1); - STRCMP_EQUAL(str.asCharString(), buffer.toString()); -} - -TEST(SimpleStringBuffer, resetWriteLimit) -{ - SimpleStringBuffer buffer; - buffer.setWriteLimit(10); - for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN ; i++) - buffer.add("h"); - buffer.resetWriteLimit(); - buffer.add("%s", SimpleString("h", 10).asCharString()); - - SimpleString str("h", 20); - STRCMP_EQUAL(str.asCharString(), buffer.toString()); -} - -TEST_GROUP(ReallocBugReported) -{ - MemoryLeakFailureForTest reporter; -}; - -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); -} - -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); -} +/* + * 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 "CppUTest/TestMemoryAllocator.h" +#include "CppUTest/PlatformSpecificFunctions.h" + +class MemoryLeakFailureForTest: public MemoryLeakFailure +{ +public: + virtual ~MemoryLeakFailureForTest() + { + } + + virtual void fail(char* fail_string) + { + *message = fail_string; + } + + SimpleString *message; +}; + +class NewAllocatorForMemoryLeakDetectionTest: public TestMemoryAllocator +{ +public: + NewAllocatorForMemoryLeakDetectionTest() : + TestMemoryAllocator("Standard New Allocator", "new", "delete"), + alloc_called(0), free_called(0) + { + } + + int alloc_called; + int free_called; + char* alloc_memory(size_t size, const char*, int) + { + alloc_called++; + return TestMemoryAllocator::alloc_memory(size, "file", 1); + } + void free_memory(char* memory, const char* file, int line) + { + free_called++; + TestMemoryAllocator::free_memory(memory, file, line); + } +}; + +class AllocatorForMemoryLeakDetectionTest: public TestMemoryAllocator +{ +public: + AllocatorForMemoryLeakDetectionTest() : + alloc_called(0), free_called(0), allocMemoryLeakNodeCalled(0), freeMemoryLeakNodeCalled(0) + { + } + + int alloc_called; + int free_called; + int allocMemoryLeakNodeCalled; + int freeMemoryLeakNodeCalled; + + char* alloc_memory(size_t size, const char* file, int line) + { + alloc_called++; + return TestMemoryAllocator::alloc_memory(size, file, line); + } + void free_memory(char* memory, const char* file, int line) + { + free_called++; + TestMemoryAllocator::free_memory(memory, file, line); + } + + char* allocMemoryLeakNode(size_t size) + { + allocMemoryLeakNodeCalled++; + return TestMemoryAllocator::alloc_memory(size, __FILE__, __LINE__); + } + + void freeMemoryLeakNode(char* memory) + { + freeMemoryLeakNodeCalled++; + TestMemoryAllocator::free_memory(memory, __FILE__, __LINE__); + } +}; + +TEST_GROUP(MemoryLeakDetectorTest) +{ + MemoryLeakDetector* detector; + MemoryLeakFailureForTest *reporter; + AllocatorForMemoryLeakDetectionTest* testAllocator; + + void setup() + { + reporter = new MemoryLeakFailureForTest; + detector = new MemoryLeakDetector(reporter); + testAllocator = new AllocatorForMemoryLeakDetectionTest; + detector->enable(); + detector->startChecking(); + reporter->message = new SimpleString(); + } + void teardown() + { + delete reporter->message; + delete detector; + delete reporter; + delete testAllocator; + } +}; + +TEST(MemoryLeakDetectorTest, OneLeak) +{ + char* mem = detector->allocMemory(testAllocator, 3); + detector->stopChecking(); + SimpleString output = detector->report(mem_leak_period_checking); + STRCMP_CONTAINS("Memory leak(s) found", output.asCharString()); + STRCMP_CONTAINS("size: 3", output.asCharString()); + STRCMP_CONTAINS("alloc", output.asCharString()); + STRCMP_CONTAINS(StringFromFormat("%p", mem).asCharString(), output.asCharString()); + STRCMP_CONTAINS("Total number of leaks", output.asCharString()); + PlatformSpecificFree(mem); + LONGS_EQUAL(1, testAllocator->alloc_called); + LONGS_EQUAL(0, testAllocator->free_called); +} + +TEST(MemoryLeakDetectorTest, sequenceNumbersOfMemoryLeaks) +{ + char* mem = detector->allocMemory(defaultNewAllocator(), 1); + char* mem2 = detector->allocMemory(defaultNewAllocator(), 2); + char* mem3 = detector->allocMemory(defaultNewAllocator(), 3); + SimpleString output = detector->report(mem_leak_period_checking); + + STRCMP_CONTAINS("Alloc num (1)", output.asCharString()); + STRCMP_CONTAINS("Alloc num (2)", output.asCharString()); + STRCMP_CONTAINS("Alloc num (3)", output.asCharString()); + + PlatformSpecificFree(mem); + PlatformSpecificFree(mem2); + PlatformSpecificFree(mem3); +} + + +TEST(MemoryLeakDetectorTest, OneHundredLeaks) +{ + const int amount_alloc = 100; + char *mem[amount_alloc]; + for (int i = 0; i < amount_alloc; i++) + mem[i] = detector->allocMemory(defaultMallocAllocator(), 3); + detector->stopChecking(); + + SimpleString output = detector->report(mem_leak_period_checking); + + STRCMP_CONTAINS("Memory leak(s) found", output.asCharString()); + STRCMP_CONTAINS("Total number of leaks", output.asCharString()); + STRCMP_CONTAINS("Memory leak reports about malloc and free", output.asCharString()); + + //don't reuse i for vc6 compatibility + for (int j = 0; j < amount_alloc; j++) + PlatformSpecificFree(mem[j]); +} + +TEST(MemoryLeakDetectorTest, OneLeakOutsideCheckingPeriod) +{ + detector->stopChecking(); + char* mem = detector->allocMemory(defaultNewAllocator(), 4); + SimpleString output = detector->report(mem_leak_period_all); + CHECK(output.contains("Memory leak(s) found")); + CHECK(output.contains("size: 4")); + CHECK(output.contains("new")); + CHECK(output.contains("Total number of leaks")); + PlatformSpecificFree(mem); +} + +TEST(MemoryLeakDetectorTest, NoLeaksWhatsoever) +{ + detector->stopChecking(); + STRCMP_CONTAINS("No memory leaks", detector->report(mem_leak_period_checking)); + STRCMP_CONTAINS("No memory leaks", detector->report(mem_leak_period_all)); +} + +TEST(MemoryLeakDetectorTest, TwoLeaksUsingOperatorNew) +{ + char* mem = detector->allocMemory(defaultNewAllocator(), 4); + char* mem2 = detector->allocMemory(defaultNewAllocator(), 8); + detector->stopChecking(); + SimpleString output = detector->report(mem_leak_period_checking); + LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); + CHECK(output.contains("size: 8")); + CHECK(output.contains("size: 4")); + PlatformSpecificFree(mem); + PlatformSpecificFree(mem2); +} + +TEST(MemoryLeakDetectorTest, OneAllocButNoLeak) +{ + char* mem = detector->allocMemory(testAllocator, 4); + detector->deallocMemory(testAllocator, mem); + detector->stopChecking(); + STRCMP_CONTAINS("No memory leaks", detector->report(mem_leak_period_checking)); + LONGS_EQUAL(1, testAllocator->alloc_called); + LONGS_EQUAL(1, testAllocator->free_called); +} + +TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeak) +{ + char* mem = detector->allocMemory(testAllocator, 4); + char* mem2 = detector->allocMemory(testAllocator, 12); + detector->deallocMemory(testAllocator, mem); + detector->stopChecking(); + SimpleString output = detector->report(mem_leak_period_checking); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); + CHECK(output.contains("size: 12")); + CHECK(!output.contains("size: 4")); + PlatformSpecificFree(mem2); + LONGS_EQUAL(2, testAllocator->alloc_called); + LONGS_EQUAL(1, testAllocator->free_called); +} + +TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeakReverseOrder) +{ + char* mem = detector->allocMemory(defaultNewAllocator(), 4); + char* mem2 = detector->allocMemory(defaultNewAllocator(), 12); + detector->deallocMemory(defaultNewAllocator(), mem2); + detector->stopChecking(); + SimpleString output = detector->report(mem_leak_period_checking); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); + CHECK(!output.contains("size: 12")); + CHECK(output.contains("size: 4")); + PlatformSpecificFree(mem); +} + +TEST(MemoryLeakDetectorTest, DeleteNonAlocatedMemory) +{ + char a; + char* pa = &a; + detector->deallocMemory(defaultMallocAllocator(), pa, "FREE.c", 100); + detector->stopChecking(); + CHECK(reporter->message->contains("Deallocating non-allocated memory")); + CHECK(reporter->message->contains(" allocated at file: line: 0 size: 0 type: unknown")); + CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free")); +} + +TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriod) +{ + detector->stopChecking(); + char* mem = detector->allocMemory(defaultNewAllocator(), 4); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); + detector->deallocMemory(defaultNewAllocator(), mem); +} + +TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriodComplicatedCase) +{ + char* mem = detector->allocMemory(defaultNewAllocator(), 4); + detector->stopChecking(); + + char* mem2 = detector->allocMemory(defaultNewAllocator(), 8); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); + detector->clearAllAccounting(mem_leak_period_checking); + PlatformSpecificFree(mem); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); + + detector->startChecking(); + char* mem3 = detector->allocMemory(defaultNewAllocator(), 4); + detector->stopChecking(); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); + LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); + + detector->clearAllAccounting(mem_leak_period_checking); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); + + detector->clearAllAccounting(mem_leak_period_all); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); + PlatformSpecificFree(mem2); + PlatformSpecificFree(mem3); +} + +TEST(MemoryLeakDetectorTest, OneLeakUsingOperatorNewWithFileLine) +{ + char* mem = detector->allocMemory(defaultNewAllocator(), 4, "file.cpp", 1234); + detector->stopChecking(); + SimpleString output = detector->report(mem_leak_period_checking); + CHECK(output.contains("file.cpp")); + CHECK(output.contains("1234")); + PlatformSpecificFree(mem); +} + +TEST(MemoryLeakDetectorTest, OneAllocAndFreeUsingArrayNew) +{ + char* mem = detector->allocMemory(defaultNewArrayAllocator(), 10, "file.cpp", 1234); + char* mem2 = detector->allocMemory(defaultNewArrayAllocator(), 12); + LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); + SimpleString output = detector->report(mem_leak_period_checking); + CHECK(output.contains("new []")); + detector->deallocMemory(defaultNewArrayAllocator(), mem); + detector->deallocMemory(defaultNewArrayAllocator(), mem2); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); + detector->stopChecking(); +} + +TEST(MemoryLeakDetectorTest, OneAllocAndFree) +{ + char* mem = detector->allocMemory(defaultMallocAllocator(), 10, "file.cpp", 1234); + char* mem2 = detector->allocMemory(defaultMallocAllocator(), 12); + LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); + SimpleString output = detector->report(mem_leak_period_checking); + CHECK(output.contains("malloc")); + detector->deallocMemory(defaultMallocAllocator(), mem); + detector->deallocMemory(defaultMallocAllocator(), mem2, "file.c", 5678); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); + detector->stopChecking(); +} + +TEST(MemoryLeakDetectorTest, OneRealloc) +{ + char* mem1 = detector->allocMemory(testAllocator, 10, "file.cpp", 1234, true); + + char* mem2 = detector->reallocMemory(testAllocator, mem1, 1000, "other.cpp", 5678, true); + + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); + SimpleString output = detector->report(mem_leak_period_checking); + CHECK(output.contains("other.cpp")); + + detector->deallocMemory(testAllocator, mem2, true); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); + detector->stopChecking(); + LONGS_EQUAL(1, testAllocator->alloc_called); + LONGS_EQUAL(1, testAllocator->free_called); + LONGS_EQUAL(2, testAllocator->allocMemoryLeakNodeCalled); + LONGS_EQUAL(2, testAllocator->freeMemoryLeakNodeCalled); +} + +TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherType) +{ + char* mem = detector->allocMemory(defaultNewArrayAllocator(), 100, "ALLOC.c", 10); + detector->deallocMemory(defaultMallocAllocator(), mem, "FREE.c", 100); + detector->stopChecking(); + CHECK(reporter->message->contains("Allocation/deallocation type mismatch")); + CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 100 type: new []")); + CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free")); +} + +TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherTypeWithCheckingDisabled) +{ + detector->disableAllocationTypeChecking(); + char* mem = detector->allocMemory(defaultNewArrayAllocator(), 100, "ALLOC.c", 10); + detector->deallocMemory(defaultNewAllocator(), mem, "FREE.c", 100); + detector->stopChecking(); + STRCMP_EQUAL("", reporter->message->asCharString()); + detector->enableAllocationTypeChecking(); +} + +TEST(MemoryLeakDetectorTest, mallocLeakGivesAdditionalWarning) +{ + char* mem = detector->allocMemory(defaultMallocAllocator(), 100, "ALLOC.c", 10); + detector->stopChecking(); + SimpleString output = detector->report(mem_leak_period_checking); + STRCMP_CONTAINS("Memory leak reports about malloc and free can be caused by allocating using the cpputest version of malloc", output.asCharString()); + PlatformSpecificFree(mem); +} + +TEST(MemoryLeakDetectorTest, newLeakDoesNotGiveAdditionalWarning) +{ + char* mem = detector->allocMemory(defaultNewAllocator(), 100, "ALLOC.c", 10); + detector->stopChecking(); + SimpleString output = detector->report(mem_leak_period_checking); + CHECK(! output.contains("Memory leak reports about malloc and free")); + PlatformSpecificFree(mem); +} + +TEST(MemoryLeakDetectorTest, MarkCheckingPeriodLeaksAsNonCheckingPeriod) +{ + char* mem = detector->allocMemory(defaultNewArrayAllocator(), 100); + char* mem2 = detector->allocMemory(defaultNewArrayAllocator(), 100); + detector->stopChecking(); + LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); + LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); + detector->markCheckingPeriodLeaksAsNonCheckingPeriod(); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); + LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); + PlatformSpecificFree(mem); + PlatformSpecificFree(mem2); +} + +TEST(MemoryLeakDetectorTest, memoryCorruption) +{ + char* mem = detector->allocMemory(defaultMallocAllocator(), 10, "ALLOC.c", 10); + mem[10] = 'O'; + mem[11] = 'H'; + detector->deallocMemory(defaultMallocAllocator(), mem, "FREE.c", 100); + detector->stopChecking(); + CHECK(reporter->message->contains("Memory corruption")); + CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 10 type: malloc")); + CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free")); +} + +TEST(MemoryLeakDetectorTest, safelyDeleteNULL) +{ + detector->deallocMemory(defaultNewAllocator(), 0); + STRCMP_EQUAL("", reporter->message->asCharString()); +} + +TEST(MemoryLeakDetectorTest, periodDisabled) +{ + detector->disable(); + char* mem = detector->allocMemory(defaultMallocAllocator(), 2); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_disabled)); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_enabled)); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); + detector->deallocMemory(defaultMallocAllocator(), mem); +} + +TEST(MemoryLeakDetectorTest, periodEnabled) +{ + detector->enable(); + char* mem = detector->allocMemory(defaultMallocAllocator(), 2); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled)); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled)); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); + detector->deallocMemory(defaultMallocAllocator(), mem); +} + +TEST(MemoryLeakDetectorTest, periodChecking) +{ + char* mem = detector->allocMemory(defaultMallocAllocator(), 2); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); + LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled)); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled)); + LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); + detector->deallocMemory(defaultMallocAllocator(), mem); +} + +TEST(MemoryLeakDetectorTest, allocateWithANullAllocatorCausesNoProblems) +{ + char* mem = detector->allocMemory(NullUnknownAllocator::defaultAllocator(), 2); + detector->deallocMemory(NullUnknownAllocator::defaultAllocator(), mem); +} + +TEST(MemoryLeakDetectorTest, invalidateMemory) +{ + unsigned char* mem = (unsigned char*)detector->allocMemory(defaultMallocAllocator(), 2); + + detector->invalidateMemory((char*)mem); + CHECK(mem[0] == 0xCD); + CHECK(mem[1] == 0xCD); + detector->deallocMemory(defaultMallocAllocator(), mem); +} + +TEST(MemoryLeakDetectorTest, invalidateMemoryNULLShouldWork) +{ + detector->invalidateMemory(NULL); +} + +TEST_GROUP(SimpleStringBuffer) +{ +}; + +TEST(SimpleStringBuffer, simpleTest) +{ + SimpleStringBuffer buffer; + buffer.add("Hello"); + buffer.add(" World"); + STRCMP_EQUAL("Hello World", buffer.toString()); +} + +TEST(SimpleStringBuffer, writePastLimit) +{ + SimpleStringBuffer buffer; + for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN * 2; i++) + buffer.add("h"); + SimpleString str("h", SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN-1); + STRCMP_EQUAL(str.asCharString(), buffer.toString()); +} + +TEST(SimpleStringBuffer, setWriteLimit) +{ + SimpleStringBuffer buffer; + buffer.setWriteLimit(10); + for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN ; i++) + buffer.add("h"); + SimpleString str("h", 10); + STRCMP_EQUAL(str.asCharString(), buffer.toString()); +} + +TEST(SimpleStringBuffer, setWriteLimitTooHighIsIgnored) +{ + SimpleStringBuffer buffer; + buffer.setWriteLimit(SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN+10); + for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN+10; i++) + buffer.add("h"); + SimpleString str("h", SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN-1); + STRCMP_EQUAL(str.asCharString(), buffer.toString()); +} + +TEST(SimpleStringBuffer, resetWriteLimit) +{ + SimpleStringBuffer buffer; + buffer.setWriteLimit(10); + for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN ; i++) + buffer.add("h"); + buffer.resetWriteLimit(); + buffer.add("%s", SimpleString("h", 10).asCharString()); + + SimpleString str("h", 20); + STRCMP_EQUAL(str.asCharString(), buffer.toString()); +} + +TEST_GROUP(ReallocBugReported) +{ + MemoryLeakFailureForTest reporter; +}; + +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); +} + +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); +} diff --git a/tests/NullTestTest.cpp b/tests/NullTestTest.cpp index 3db8f7b14..a966f7db9 100644 --- a/tests/NullTestTest.cpp +++ b/tests/NullTestTest.cpp @@ -1,59 +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/TestHarness.h" - -TEST_GROUP(NullTestShell) -{ - NullTestShell* nullTest; - - TEST_SETUP() - { - nullTest = new NullTestShell(); - } - - TEST_TEARDOWN() - { - delete nullTest; - } -}; - -TEST(NullTestShell, Create) -{ -} - -TEST(NullTestShell, InstanceAlwaysTheSame) -{ - NullTestShell& _instance = NullTestShell::instance(); - CHECK(&_instance == &NullTestShell::instance()); -} - -TEST(NullTestShell, NullTestsDontCount) -{ - NullTestShell& _instance = NullTestShell::instance(); - CHECK(_instance.countTests() == 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" + +TEST_GROUP(NullTestShell) +{ + NullTestShell* nullTest; + + TEST_SETUP() + { + nullTest = new NullTestShell(); + } + + TEST_TEARDOWN() + { + delete nullTest; + } +}; + +TEST(NullTestShell, Create) +{ +} + +TEST(NullTestShell, InstanceAlwaysTheSame) +{ + NullTestShell& _instance = NullTestShell::instance(); + CHECK(&_instance == &NullTestShell::instance()); +} + +TEST(NullTestShell, NullTestsDontCount) +{ + NullTestShell& _instance = NullTestShell::instance(); + CHECK(_instance.countTests() == 0); +} diff --git a/tests/PluginTest.cpp b/tests/PluginTest.cpp index 973c6b5ef..913a18b8e 100644 --- a/tests/PluginTest.cpp +++ b/tests/PluginTest.cpp @@ -1,182 +1,182 @@ -/* - * 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/TestRegistry.h" -#include "CppUTest/TestOutput.h" -#include "CppUTest/TestTestingFixture.h" - -#define GENERIC_PLUGIN "GenericPlugin" -#define GENERIC_PLUGIN2 "GenericPlugin2" -#define GENERIC_PLUGIN3 "GenericPlugin3" - -static int sequenceNumber; - -class DummyPlugin: public TestPlugin -{ -public: - DummyPlugin(const SimpleString& name) : - TestPlugin(name), preAction(0), preActionSequence(0), postAction(0), postActionSequence(0) - { - } - - virtual ~DummyPlugin() - { - } - - virtual void preTestAction(UtestShell&, TestResult&) - { - preAction++; - preActionSequence = sequenceNumber++; - } - - virtual void postTestAction(UtestShell&, TestResult&) - { - postAction++; - postActionSequence = sequenceNumber++; - } - - int preAction; - int preActionSequence; - int postAction; - int postActionSequence; -}; - -class DummyPluginWhichAcceptsParameters: public DummyPlugin -{ -public: - DummyPluginWhichAcceptsParameters(const SimpleString& name) : - DummyPlugin(name) - { - } - - virtual bool parseArguments(int ac, const char** av, int index) - { - SimpleString argument (av[index]); - if (argument == "-paccept") - return true; - return TestPlugin::parseArguments(ac, av, index); - } - -}; - - -TEST_GROUP(PluginTest) -{ - DummyPlugin* firstPlugin; - DummyPluginWhichAcceptsParameters* secondPlugin; - DummyPlugin* thirdPlugin; - TestTestingFixture *genFixture; - TestRegistry *registry; - void setup() - { - firstPlugin = new DummyPlugin(GENERIC_PLUGIN); - secondPlugin = new DummyPluginWhichAcceptsParameters(GENERIC_PLUGIN2); - thirdPlugin = new DummyPlugin(GENERIC_PLUGIN3); - genFixture = new TestTestingFixture; - registry = genFixture->registry_; - registry->installPlugin(firstPlugin); - sequenceNumber = 1; - } - - void teardown() - { - delete firstPlugin; - delete secondPlugin; - delete thirdPlugin; - delete genFixture; - } -}; - -#define GENERIC_PLUGIN "GenericPlugin" - -TEST(PluginTest, PluginHasName) -{ - STRCMP_EQUAL(GENERIC_PLUGIN, firstPlugin->getName().asCharString()); -} - -TEST(PluginTest, InstallPlugin) -{ - CHECK_EQUAL(firstPlugin, registry->getFirstPlugin()); - CHECK_EQUAL(firstPlugin, registry->getPluginByName(GENERIC_PLUGIN)); - LONGS_EQUAL(1, registry->countPlugins()); -} - -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")); -} - -TEST(PluginTest, ActionsAllRun) -{ - genFixture->runAllTests(); - genFixture->runAllTests(); - CHECK_EQUAL(2, firstPlugin->preAction); - CHECK_EQUAL(2, firstPlugin->postAction); -} - -TEST(PluginTest, Sequence) -{ - registry->installPlugin(thirdPlugin); - genFixture->runAllTests(); - CHECK_EQUAL(1, thirdPlugin->preActionSequence); - CHECK_EQUAL(2, firstPlugin->preActionSequence); - CHECK_EQUAL(3, firstPlugin->postActionSequence); - CHECK_EQUAL(4, thirdPlugin->postActionSequence); - LONGS_EQUAL(2, registry->countPlugins()); -} - -TEST(PluginTest, DisablesPluginsDontRun) -{ - registry->installPlugin(thirdPlugin); - thirdPlugin->disable(); - genFixture->runAllTests(); - CHECK(!thirdPlugin->isEnabled()); - thirdPlugin->enable(); - genFixture->runAllTests(); - CHECK_EQUAL(2, firstPlugin->preAction); - CHECK_EQUAL(1, thirdPlugin->preAction); - CHECK(thirdPlugin->isEnabled()); -} - -TEST(PluginTest, ParseArgumentsForUnknownArgumentsFails) -{ - registry->installPlugin(secondPlugin); - const char *cmd_line[] = {"nonsense", "andmorenonsense"}; - CHECK(registry->getFirstPlugin()->parseAllArguments(2, cmd_line, 0) == false ); -} - -TEST(PluginTest, ParseArgumentsContinuesAndSucceedsWhenAPluginCanParse) -{ - registry->installPlugin(secondPlugin); - const char *cmd_line[] = {"-paccept", "andmorenonsense"}; - CHECK(registry->getFirstPlugin()->parseAllArguments(2, cmd_line, 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/TestRegistry.h" +#include "CppUTest/TestOutput.h" +#include "CppUTest/TestTestingFixture.h" + +#define GENERIC_PLUGIN "GenericPlugin" +#define GENERIC_PLUGIN2 "GenericPlugin2" +#define GENERIC_PLUGIN3 "GenericPlugin3" + +static int sequenceNumber; + +class DummyPlugin: public TestPlugin +{ +public: + DummyPlugin(const SimpleString& name) : + TestPlugin(name), preAction(0), preActionSequence(0), postAction(0), postActionSequence(0) + { + } + + virtual ~DummyPlugin() + { + } + + virtual void preTestAction(UtestShell&, TestResult&) + { + preAction++; + preActionSequence = sequenceNumber++; + } + + virtual void postTestAction(UtestShell&, TestResult&) + { + postAction++; + postActionSequence = sequenceNumber++; + } + + int preAction; + int preActionSequence; + int postAction; + int postActionSequence; +}; + +class DummyPluginWhichAcceptsParameters: public DummyPlugin +{ +public: + DummyPluginWhichAcceptsParameters(const SimpleString& name) : + DummyPlugin(name) + { + } + + virtual bool parseArguments(int ac, const char** av, int index) + { + SimpleString argument (av[index]); + if (argument == "-paccept") + return true; + return TestPlugin::parseArguments(ac, av, index); + } + +}; + + +TEST_GROUP(PluginTest) +{ + DummyPlugin* firstPlugin; + DummyPluginWhichAcceptsParameters* secondPlugin; + DummyPlugin* thirdPlugin; + TestTestingFixture *genFixture; + TestRegistry *registry; + void setup() + { + firstPlugin = new DummyPlugin(GENERIC_PLUGIN); + secondPlugin = new DummyPluginWhichAcceptsParameters(GENERIC_PLUGIN2); + thirdPlugin = new DummyPlugin(GENERIC_PLUGIN3); + genFixture = new TestTestingFixture; + registry = genFixture->registry_; + registry->installPlugin(firstPlugin); + sequenceNumber = 1; + } + + void teardown() + { + delete firstPlugin; + delete secondPlugin; + delete thirdPlugin; + delete genFixture; + } +}; + +#define GENERIC_PLUGIN "GenericPlugin" + +TEST(PluginTest, PluginHasName) +{ + STRCMP_EQUAL(GENERIC_PLUGIN, firstPlugin->getName().asCharString()); +} + +TEST(PluginTest, InstallPlugin) +{ + CHECK_EQUAL(firstPlugin, registry->getFirstPlugin()); + CHECK_EQUAL(firstPlugin, registry->getPluginByName(GENERIC_PLUGIN)); + LONGS_EQUAL(1, registry->countPlugins()); +} + +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")); +} + +TEST(PluginTest, ActionsAllRun) +{ + genFixture->runAllTests(); + genFixture->runAllTests(); + CHECK_EQUAL(2, firstPlugin->preAction); + CHECK_EQUAL(2, firstPlugin->postAction); +} + +TEST(PluginTest, Sequence) +{ + registry->installPlugin(thirdPlugin); + genFixture->runAllTests(); + CHECK_EQUAL(1, thirdPlugin->preActionSequence); + CHECK_EQUAL(2, firstPlugin->preActionSequence); + CHECK_EQUAL(3, firstPlugin->postActionSequence); + CHECK_EQUAL(4, thirdPlugin->postActionSequence); + LONGS_EQUAL(2, registry->countPlugins()); +} + +TEST(PluginTest, DisablesPluginsDontRun) +{ + registry->installPlugin(thirdPlugin); + thirdPlugin->disable(); + genFixture->runAllTests(); + CHECK(!thirdPlugin->isEnabled()); + thirdPlugin->enable(); + genFixture->runAllTests(); + CHECK_EQUAL(2, firstPlugin->preAction); + CHECK_EQUAL(1, thirdPlugin->preAction); + CHECK(thirdPlugin->isEnabled()); +} + +TEST(PluginTest, ParseArgumentsForUnknownArgumentsFails) +{ + registry->installPlugin(secondPlugin); + const char *cmd_line[] = {"nonsense", "andmorenonsense"}; + CHECK(registry->getFirstPlugin()->parseAllArguments(2, cmd_line, 0) == false ); +} + +TEST(PluginTest, ParseArgumentsContinuesAndSucceedsWhenAPluginCanParse) +{ + registry->installPlugin(secondPlugin); + const char *cmd_line[] = {"-paccept", "andmorenonsense"}; + CHECK(registry->getFirstPlugin()->parseAllArguments(2, cmd_line, 0)); +} + diff --git a/tests/SetPluginTest.cpp b/tests/SetPluginTest.cpp index a10e76df3..22f31f16e 100644 --- a/tests/SetPluginTest.cpp +++ b/tests/SetPluginTest.cpp @@ -1,133 +1,133 @@ -#include "CppUTest/TestHarness.h" -#include "CppUTest/TestRegistry.h" -#include "CppUTest/TestOutput.h" -#include "CppUTest/TestPlugin.h" - -static void orig_func1() -{ -} - -static void stub_func1() -{ -} - -static void orig_func2() -{ -} - -static void stub_func2() -{ -} - -static void (*fp1)(); -static void (*fp2)(); - -TEST_GROUP(SetPointerPluginTest) -{ - SetPointerPlugin* plugin_; - TestRegistry* myRegistry_; - StringBufferTestOutput* output_; - TestResult* result_; - - void setup() - { - myRegistry_ = new TestRegistry(); - plugin_ = new SetPointerPlugin("TestSetPlugin"); - myRegistry_->setCurrentRegistry(myRegistry_); - myRegistry_->installPlugin(plugin_); - output_ = new StringBufferTestOutput(); - result_ = new TestResult(*output_); - } - - void teardown() - { - myRegistry_->setCurrentRegistry(0); - delete myRegistry_; - delete plugin_; - delete output_; - delete result_; - } -}; - -class FunctionPointerUtest: public UtestShell -{ -public: - void setup() - { - UT_PTR_SET(fp1, stub_func1); - UT_PTR_SET(fp2, stub_func2); - UT_PTR_SET(fp2, stub_func2); - } - void testBody() - { - CHECK(fp1 == stub_func1); - CHECK(fp2 == stub_func2); - } -}; - -TEST(SetPointerPluginTest, installTwoFunctionPointer) -{ - FunctionPointerUtest *tst = new FunctionPointerUtest(); - ; - - fp1 = orig_func1; - fp2 = orig_func2; - myRegistry_->addTest(tst); - myRegistry_->runAllTests(*result_); - CHECK(fp1 == orig_func1); - CHECK(fp2 == orig_func2); - LONGS_EQUAL(0, result_->getFailureCount()); - delete tst; -} - -class MaxFunctionPointerUtest: public UtestShell -{ -public: - int numOfFpSets; - MaxFunctionPointerUtest(int num) : - numOfFpSets(num) - { - } - - void setup() - { - for (int i = 0; i < numOfFpSets; ++i) - UT_PTR_SET(fp1, stub_func1); - } -}; - -IGNORE_TEST(SetPointerPluginTest, installTooMuchFunctionPointer) -{ - MaxFunctionPointerUtest *tst = new MaxFunctionPointerUtest(SetPointerPlugin::MAX_SET + 1); - myRegistry_->addTest(tst); - - myRegistry_->runAllTests(*result_); - - LONGS_EQUAL(1, result_->getFailureCount()); - delete tst; -} - -static double orig_double = 3.0; -static double* orig_double_ptr = &orig_double; -static double stub_double = 4.0; - -class SetDoublePointerUtest: public UtestShell -{ -public: - void setup() - { - UT_PTR_SET(orig_double_ptr, &stub_double); - } - void testBody() - { - CHECK(orig_double_ptr == &stub_double); - } -}; - -TEST(SetPointerPluginTest, doublePointer) -{ - SetDoublePointerUtest *doubletst = new SetDoublePointerUtest(); - myRegistry_->addTest(doubletst); - CHECK(orig_double_ptr == &orig_double); - delete doubletst; -} +#include "CppUTest/TestHarness.h" +#include "CppUTest/TestRegistry.h" +#include "CppUTest/TestOutput.h" +#include "CppUTest/TestPlugin.h" + +static void orig_func1() +{ +} + +static void stub_func1() +{ +} + +static void orig_func2() +{ +} + +static void stub_func2() +{ +} + +static void (*fp1)(); +static void (*fp2)(); + +TEST_GROUP(SetPointerPluginTest) +{ + SetPointerPlugin* plugin_; + TestRegistry* myRegistry_; + StringBufferTestOutput* output_; + TestResult* result_; + + void setup() + { + myRegistry_ = new TestRegistry(); + plugin_ = new SetPointerPlugin("TestSetPlugin"); + myRegistry_->setCurrentRegistry(myRegistry_); + myRegistry_->installPlugin(plugin_); + output_ = new StringBufferTestOutput(); + result_ = new TestResult(*output_); + } + + void teardown() + { + myRegistry_->setCurrentRegistry(0); + delete myRegistry_; + delete plugin_; + delete output_; + delete result_; + } +}; + +class FunctionPointerUtest: public UtestShell +{ +public: + void setup() + { + UT_PTR_SET(fp1, stub_func1); + UT_PTR_SET(fp2, stub_func2); + UT_PTR_SET(fp2, stub_func2); + } + void testBody() + { + CHECK(fp1 == stub_func1); + CHECK(fp2 == stub_func2); + } +}; + +TEST(SetPointerPluginTest, installTwoFunctionPointer) +{ + FunctionPointerUtest *tst = new FunctionPointerUtest(); + ; + + fp1 = orig_func1; + fp2 = orig_func2; + myRegistry_->addTest(tst); + myRegistry_->runAllTests(*result_); + CHECK(fp1 == orig_func1); + CHECK(fp2 == orig_func2); + LONGS_EQUAL(0, result_->getFailureCount()); + delete tst; +} + +class MaxFunctionPointerUtest: public UtestShell +{ +public: + int numOfFpSets; + MaxFunctionPointerUtest(int num) : + numOfFpSets(num) + { + } + + void setup() + { + for (int i = 0; i < numOfFpSets; ++i) + UT_PTR_SET(fp1, stub_func1); + } +}; + +IGNORE_TEST(SetPointerPluginTest, installTooMuchFunctionPointer) +{ + MaxFunctionPointerUtest *tst = new MaxFunctionPointerUtest(SetPointerPlugin::MAX_SET + 1); + myRegistry_->addTest(tst); + + myRegistry_->runAllTests(*result_); + + LONGS_EQUAL(1, result_->getFailureCount()); + delete tst; +} + +static double orig_double = 3.0; +static double* orig_double_ptr = &orig_double; +static double stub_double = 4.0; + +class SetDoublePointerUtest: public UtestShell +{ +public: + void setup() + { + UT_PTR_SET(orig_double_ptr, &stub_double); + } + void testBody() + { + CHECK(orig_double_ptr == &stub_double); + } +}; + +TEST(SetPointerPluginTest, doublePointer) +{ + SetDoublePointerUtest *doubletst = new SetDoublePointerUtest(); + myRegistry_->addTest(doubletst); + CHECK(orig_double_ptr == &orig_double); + delete doubletst; +} diff --git a/tests/SimpleStringTest.cpp b/tests/SimpleStringTest.cpp index d4fc44e7a..e8575b810 100644 --- a/tests/SimpleStringTest.cpp +++ b/tests/SimpleStringTest.cpp @@ -1,613 +1,613 @@ -/* - * 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/SimpleString.h" -#include "CppUTest/PlatformSpecificFunctions.h" -#include "CppUTest/TestMemoryAllocator.h" - -TEST_GROUP(SimpleString) -{ -}; - -TEST(SimpleString, defaultAllocatorIsNewArrayAllocator) -{ - POINTERS_EQUAL(getCurrentNewArrayAllocator(), SimpleString::getStringAllocator()); -} - -class MyOwnStringAllocator : public TestMemoryAllocator -{ -public: - MyOwnStringAllocator() : memoryWasAllocated(false) {} - virtual ~MyOwnStringAllocator() {} - - bool memoryWasAllocated; - char* alloc_memory(size_t size, const char* file, int line) - { - memoryWasAllocated = true; - return TestMemoryAllocator::alloc_memory(size, file, line); - } -}; - -TEST(SimpleString, allocatorForSimpleStringCanBeReplaced) -{ - MyOwnStringAllocator myOwnAllocator; - SimpleString::setStringAllocator(&myOwnAllocator); - SimpleString simpleString; - CHECK(myOwnAllocator.memoryWasAllocated); - SimpleString::setStringAllocator(NULL); -} - -TEST(SimpleString, CreateSequence) -{ - SimpleString expected("hellohello"); - SimpleString actual("hello", 2); - - CHECK_EQUAL(expected, actual); -} - -TEST(SimpleString, CreateSequenceOfZero) -{ - SimpleString expected(""); - SimpleString actual("hello", 0); - - CHECK_EQUAL(expected, actual); -} - -TEST(SimpleString, Copy) -{ - SimpleString s1("hello"); - SimpleString s2(s1); - - CHECK_EQUAL(s1, s2); -} - -TEST(SimpleString, Assignment) -{ - SimpleString s1("hello"); - SimpleString s2("goodbye"); - - s2 = s1; - - CHECK_EQUAL(s1, s2); -} - -TEST(SimpleString, Equality) -{ - SimpleString s1("hello"); - SimpleString s2("hello"); - - CHECK(s1 == s2); -} - -TEST(SimpleString, InEquality) -{ - SimpleString s1("hello"); - SimpleString s2("goodbye"); - - CHECK(s1 != s2); -} - -TEST(SimpleString, CompareNoCaseWithoutCase) -{ - SimpleString s1("hello"); - SimpleString s2("hello"); - - CHECK(s1.equalsNoCase(s2)); -} - -TEST(SimpleString, CompareNoCaseWithCase) -{ - SimpleString s1("hello"); - SimpleString s2("HELLO"); - - CHECK(s1.equalsNoCase(s2)); -} - -TEST(SimpleString, CompareNoCaseWithCaseNotEqual) -{ - SimpleString s1("hello"); - SimpleString s2("WORLD"); - - CHECK(!s1.equalsNoCase(s2)); -} - - -TEST(SimpleString, asCharString) -{ - SimpleString s1("hello"); - - STRCMP_EQUAL("hello", s1.asCharString()); -} - -TEST(SimpleString, Size) -{ - SimpleString s1("hello!"); - - LONGS_EQUAL(6, s1.size()); -} - -TEST(SimpleString, toLower) -{ - SimpleString s1("AbCdEfG"); - SimpleString s2(s1.toLower()); - STRCMP_EQUAL("abcdefg", s2.asCharString()); - STRCMP_EQUAL("AbCdEfG", s1.asCharString()); -} - -TEST(SimpleString, Addition) -{ - SimpleString s1("hello!"); - SimpleString s2("goodbye!"); - SimpleString s3("hello!goodbye!"); - SimpleString s4; - s4 = s1 + s2; - - CHECK_EQUAL(s3, s4); -} - -TEST(SimpleString, Concatenation) -{ - SimpleString s1("hello!"); - SimpleString s2("goodbye!"); - SimpleString s3("hello!goodbye!"); - SimpleString s4; - s4 += s1; - s4 += s2; - - CHECK_EQUAL(s3, s4); - - SimpleString s5("hello!goodbye!hello!goodbye!"); - s4 += s4; - - CHECK_EQUAL(s5, s4); -} - -TEST(SimpleString, Contains) -{ - SimpleString s("hello!"); - SimpleString empty(""); - SimpleString beginning("hello"); - SimpleString end("lo!"); - SimpleString mid("l"); - SimpleString notPartOfString("xxxx"); - - CHECK(s.contains(empty)); - CHECK(s.contains(beginning)); - CHECK(s.contains(end)); - CHECK(s.contains(mid)); - CHECK(!s.contains(notPartOfString)); - - CHECK(empty.contains(empty)); - CHECK(!empty.contains(s)); -} - -TEST(SimpleString, startsWith) -{ - SimpleString hi("Hi you!"); - SimpleString part("Hi"); - SimpleString diff("Hrrm Hi you! ffdsfd"); - CHECK(hi.startsWith(part)); - CHECK(!part.startsWith(hi)); - CHECK(!diff.startsWith(hi)); -} - -TEST(SimpleString, split) -{ - SimpleString hi("hello\nworld\nhow\ndo\nyou\ndo\n\n"); - - SimpleStringCollection collection; - hi.split("\n", collection); - - LONGS_EQUAL(7, collection.size()); - STRCMP_EQUAL("hello\n", collection[0].asCharString()); - STRCMP_EQUAL("world\n", collection[1].asCharString()); - STRCMP_EQUAL("how\n", collection[2].asCharString()); - STRCMP_EQUAL("do\n", collection[3].asCharString()); - STRCMP_EQUAL("you\n", collection[4].asCharString()); - STRCMP_EQUAL("do\n", collection[5].asCharString()); - STRCMP_EQUAL("\n", collection[6].asCharString()); -} - -TEST(SimpleString, splitNoTokenOnTheEnd) -{ - SimpleString string("Bah Yah oops"); - SimpleStringCollection collection; - - string.split(" ", collection); - LONGS_EQUAL(3, collection.size()); - STRCMP_EQUAL("Bah ", collection[0].asCharString()); - STRCMP_EQUAL("Yah ", collection[1].asCharString()); - STRCMP_EQUAL("oops", collection[2].asCharString()); -} - -TEST(SimpleString, count) -{ - SimpleString str("ha ha ha ha"); - LONGS_EQUAL(4, str.count("ha")); -} - -TEST(SimpleString, countTogether) -{ - SimpleString str("hahahaha"); - LONGS_EQUAL(4, str.count("ha")); -} - -TEST(SimpleString, endsWith) -{ - SimpleString str("Hello World"); - CHECK(str.endsWith("World")); - CHECK(!str.endsWith("Worl")); - CHECK(!str.endsWith("Hello")); - SimpleString str2("ah"); - CHECK(str2.endsWith("ah")); - CHECK(!str2.endsWith("baah")); - SimpleString str3(""); - CHECK(!str3.endsWith("baah")); - - SimpleString str4("ha ha ha ha"); - CHECK(str4.endsWith("ha")); -} - -TEST(SimpleString, replaceCharWithChar) -{ - SimpleString str("abcabcabca"); - str.replace('a', 'b'); - STRCMP_EQUAL("bbcbbcbbcb", str.asCharString()); -} - -TEST(SimpleString, replaceStringWithString) -{ - SimpleString str("boo baa boo baa boo"); - str.replace("boo", "boohoo"); - STRCMP_EQUAL("boohoo baa boohoo baa boohoo", str.asCharString()); -} - -TEST(SimpleString, subStringFromEmptyString) -{ - SimpleString str(""); - STRCMP_EQUAL("", str.subString(0, 1).asCharString()); -} - -TEST(SimpleString, subStringFromSmallString) -{ - SimpleString str("H"); - STRCMP_EQUAL("H", str.subString(0, 1).asCharString()); -} - -TEST(SimpleString, subStringFromPos0) -{ - SimpleString str("Hello World"); - STRCMP_EQUAL("Hello", str.subString(0, 5).asCharString()); -} - -TEST(SimpleString, subStringFromPos1) -{ - SimpleString str("Hello World"); - STRCMP_EQUAL("ello ", str.subString(1, 5).asCharString()); -} - -TEST(SimpleString, subStringFromPos5WithAmountLargerThanString) -{ - SimpleString str("Hello World"); - STRCMP_EQUAL("World", str.subString(6, 10).asCharString()); -} - -TEST(SimpleString, subStringBeginPosOutOfBounds) -{ - SimpleString str("Hello World"); - STRCMP_EQUAL("", str.subString(13, 5).asCharString()); -} - -TEST(SimpleString, subStringFromTillNormal) -{ - SimpleString str("Hello World"); - STRCMP_EQUAL("Hello", str.subStringFromTill('H', ' ').asCharString()); -} - -TEST(SimpleString, subStringFromTillOutOfBounds) -{ - SimpleString str("Hello World"); - STRCMP_EQUAL("World", str.subStringFromTill('W', '!').asCharString()); -} - -TEST(SimpleString, subStringFromTillStartDoesntExist) -{ - SimpleString str("Hello World"); - STRCMP_EQUAL("", str.subStringFromTill('!', ' ').asCharString()); -} - -TEST(SimpleString, subStringFromTillWhenTheEndAppearsBeforeTheStart) -{ - SimpleString str("Hello World"); - STRCMP_EQUAL("World", str.subStringFromTill('W', 'H').asCharString()); -} - -TEST(SimpleString, findNormal) -{ - SimpleString str("Hello World"); - LONGS_EQUAL(0, str.find('H')); - LONGS_EQUAL(1, str.find('e')); - LONGS_EQUAL(-1, str.find('!')); -} - -TEST(SimpleString, at) -{ - SimpleString str("Hello World"); - BYTES_EQUAL('H', str.at(0)); -} - -TEST(SimpleString, copyInBufferNormal) -{ - SimpleString str("Hello World"); - size_t bufferSize = str.size()+1; - char* buffer = (char*) malloc(bufferSize); - str.copyToBuffer(buffer, bufferSize); - STRCMP_EQUAL(str.asCharString(), buffer); - free(buffer); -} - -TEST(SimpleString, copyInBufferWithEmptyBuffer) -{ - SimpleString str("Hello World"); - char* buffer= NULL; - str.copyToBuffer(buffer, 0); - POINTERS_EQUAL(NULL, buffer); -} - -TEST(SimpleString, copyInBufferWithBiggerBufferThanNeeded) -{ - SimpleString str("Hello"); - size_t bufferSize = 20; - char* buffer= (char*) malloc(bufferSize); - str.copyToBuffer(buffer, bufferSize); - STRCMP_EQUAL(str.asCharString(), buffer); - free(buffer); -} - -TEST(SimpleString, ContainsNull) -{ - SimpleString s(0); - CHECK(!s.contains("something")); -} - -TEST(SimpleString, NULLReportsNullString) -{ - STRCMP_EQUAL("(null)", StringFromOrNull((char*) NULL).asCharString()); -} - -TEST(SimpleString, Characters) -{ - SimpleString s(StringFrom('a')); - SimpleString s2(StringFrom('a')); - CHECK(s == s2); -} - -TEST(SimpleString, Doubles) -{ - SimpleString s(StringFrom(1.2)); - STRCMP_EQUAL("1.2", s.asCharString()); -} - -TEST(SimpleString, SmallDoubles) -{ - SimpleString s(StringFrom(1.2e-10)); - STRCMP_CONTAINS("1.2e", s.asCharString()); -} - -TEST(SimpleString, Sizes) -{ - size_t size = 10; - STRCMP_EQUAL("10", StringFrom((int) size).asCharString()); -} - -TEST(SimpleString, HexStrings) -{ - SimpleString h1 = HexStringFrom(0xffffL); - STRCMP_EQUAL("ffff", h1.asCharString()); -} - -TEST(SimpleString, StringFromFormat) -{ - SimpleString h1 = StringFromFormat("%s %s! %d", "Hello", "World", 2009); - STRCMP_EQUAL("Hello World! 2009", h1.asCharString()); -} - -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()) - else if (h1.size() == 8) - STRCMP_EQUAL("00000001", h1.asCharString()) - else if (h1.size() == 16) - STRCMP_EQUAL("0000000000000001", h1.asCharString()) - else if (h1.size() == 1) - STRCMP_EQUAL("1", h1.asCharString()) - else - FAIL("Off %p behavior") -} - -TEST(SimpleString, StringFromFormatLarge) -{ - const char* s = "ThisIsAPrettyLargeStringAndIfWeAddThisManyTimesToABufferItWillbeFull"; - SimpleString h1 = StringFromFormat("%s%s%s%s%s%s%s%s%s%s", s, s, s, s, s, s, s, s, s, s); - LONGS_EQUAL(10, h1.count(s)); -} - -static int WrappedUpVSNPrintf(char* buf, size_t n, const char* format, ...) -{ - va_list arguments; - va_start(arguments, format); - - int result = PlatformSpecificVSNprintf(buf, n, format, arguments); - va_end(arguments); - return result; -} - -TEST(SimpleString, PlatformSpecificSprintf_fits) -{ - char buf[10]; - - int count = WrappedUpVSNPrintf(buf, sizeof(buf), "%s", "12345"); - STRCMP_EQUAL("12345", buf); - LONGS_EQUAL(5, count); -} - -TEST(SimpleString, PlatformSpecificSprintf_doesNotFit) -{ - char buf[10]; - - int count = WrappedUpVSNPrintf(buf, sizeof(buf), "%s", "12345678901"); - STRCMP_EQUAL("123456789", buf); - LONGS_EQUAL(11, count); -} - -TEST(SimpleString, PadStringsToSameLengthString1Larger) -{ - SimpleString str1("1"); - SimpleString str2("222"); - - SimpleString::padStringsToSameLength(str1, str2, '4'); - STRCMP_EQUAL("441", str1.asCharString()); - STRCMP_EQUAL("222", str2.asCharString()); -} - -TEST(SimpleString, PadStringsToSameLengthString2Larger) -{ - SimpleString str1(" "); - SimpleString str2(""); - - SimpleString::padStringsToSameLength(str1, str2, ' '); - STRCMP_EQUAL(" ", str1.asCharString()); - STRCMP_EQUAL(" ", str2.asCharString()); -} - -TEST(SimpleString, PadStringsToSameLengthWithSameLengthStrings) -{ - SimpleString str1("123"); - SimpleString str2("123"); - - SimpleString::padStringsToSameLength(str1, str2, ' '); - STRCMP_EQUAL("123", str1.asCharString()); - STRCMP_EQUAL("123", str2.asCharString()); -} - -TEST(SimpleString, NullParameters2) -{ - SimpleString* arr = new SimpleString[100]; - delete[] arr; -} - -TEST(SimpleString, CollectionMultipleAllocateNoLeaksMemory) -{ - SimpleStringCollection col; - col.allocate(5); - col.allocate(5); - // CHECK no memory leak -} - -TEST(SimpleString, CollectionReadOutOfBoundsReturnsEmptyString) -{ - SimpleStringCollection col; - col.allocate(3); - STRCMP_EQUAL("", col[3].asCharString()); -} - -TEST(SimpleString, CollectionWritingToEmptyString) -{ - SimpleStringCollection col; - col.allocate(3); - col[3] = SimpleString("HAH"); - STRCMP_EQUAL("", col[3].asCharString()); -} - -#ifdef CPPUTEST_64BIT -#ifdef CPPUTEST_64BIT_32BIT_LONGS - -/* - * 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 and then this test ought - * to be deleted. - */ -TEST(SimpleString, _64BitAddressPrintsCorrectly) -{ - char* p = (char*) 0xffffffffu; - SimpleString expected("0x23456789"); - SimpleString actual = StringFrom((void*)&p[0x2345678A]); - STRCMP_EQUAL(expected.asCharString(), actual.asCharString()); -} - -#else - -TEST(SimpleString, _64BitAddressPrintsCorrectly) -{ - char* p = (char*) 0x0012345678901234; - SimpleString expected("0x12345678901234"); - SimpleString actual = StringFrom((void*)p); - STRCMP_EQUAL(expected.asCharString(), actual.asCharString()); -} - -#endif -#endif - -TEST(SimpleString, BuildStringFromUnsignedInteger) -{ - unsigned int i = 0xffffffff; - - SimpleString result = StringFrom(i); - const char* expected_string = "4294967295 (0xffffffff)"; - CHECK_EQUAL(expected_string, result); -} - -#if CPPUTEST_USE_STD_CPP_LIB - -TEST(SimpleString, fromStdString) -{ - std::string s("hello"); - SimpleString s1(StringFrom(s)); - - STRCMP_EQUAL("hello", s1.asCharString()); -} - -TEST(SimpleString, CHECK_EQUAL_unsigned_long) -{ - unsigned long i = 0xffffffffUL; - CHECK_EQUAL(i, i); -} - -TEST(SimpleString, unsigned_long) -{ - unsigned long i = 0xffffffffUL; - - SimpleString result = StringFrom(i); - const char* expected_string = "4294967295 (0xffffffff)"; - CHECK_EQUAL(expected_string, result); -} - -#endif +/* + * 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/SimpleString.h" +#include "CppUTest/PlatformSpecificFunctions.h" +#include "CppUTest/TestMemoryAllocator.h" + +TEST_GROUP(SimpleString) +{ +}; + +TEST(SimpleString, defaultAllocatorIsNewArrayAllocator) +{ + POINTERS_EQUAL(getCurrentNewArrayAllocator(), SimpleString::getStringAllocator()); +} + +class MyOwnStringAllocator : public TestMemoryAllocator +{ +public: + MyOwnStringAllocator() : memoryWasAllocated(false) {} + virtual ~MyOwnStringAllocator() {} + + bool memoryWasAllocated; + char* alloc_memory(size_t size, const char* file, int line) + { + memoryWasAllocated = true; + return TestMemoryAllocator::alloc_memory(size, file, line); + } +}; + +TEST(SimpleString, allocatorForSimpleStringCanBeReplaced) +{ + MyOwnStringAllocator myOwnAllocator; + SimpleString::setStringAllocator(&myOwnAllocator); + SimpleString simpleString; + CHECK(myOwnAllocator.memoryWasAllocated); + SimpleString::setStringAllocator(NULL); +} + +TEST(SimpleString, CreateSequence) +{ + SimpleString expected("hellohello"); + SimpleString actual("hello", 2); + + CHECK_EQUAL(expected, actual); +} + +TEST(SimpleString, CreateSequenceOfZero) +{ + SimpleString expected(""); + SimpleString actual("hello", 0); + + CHECK_EQUAL(expected, actual); +} + +TEST(SimpleString, Copy) +{ + SimpleString s1("hello"); + SimpleString s2(s1); + + CHECK_EQUAL(s1, s2); +} + +TEST(SimpleString, Assignment) +{ + SimpleString s1("hello"); + SimpleString s2("goodbye"); + + s2 = s1; + + CHECK_EQUAL(s1, s2); +} + +TEST(SimpleString, Equality) +{ + SimpleString s1("hello"); + SimpleString s2("hello"); + + CHECK(s1 == s2); +} + +TEST(SimpleString, InEquality) +{ + SimpleString s1("hello"); + SimpleString s2("goodbye"); + + CHECK(s1 != s2); +} + +TEST(SimpleString, CompareNoCaseWithoutCase) +{ + SimpleString s1("hello"); + SimpleString s2("hello"); + + CHECK(s1.equalsNoCase(s2)); +} + +TEST(SimpleString, CompareNoCaseWithCase) +{ + SimpleString s1("hello"); + SimpleString s2("HELLO"); + + CHECK(s1.equalsNoCase(s2)); +} + +TEST(SimpleString, CompareNoCaseWithCaseNotEqual) +{ + SimpleString s1("hello"); + SimpleString s2("WORLD"); + + CHECK(!s1.equalsNoCase(s2)); +} + + +TEST(SimpleString, asCharString) +{ + SimpleString s1("hello"); + + STRCMP_EQUAL("hello", s1.asCharString()); +} + +TEST(SimpleString, Size) +{ + SimpleString s1("hello!"); + + LONGS_EQUAL(6, s1.size()); +} + +TEST(SimpleString, toLower) +{ + SimpleString s1("AbCdEfG"); + SimpleString s2(s1.toLower()); + STRCMP_EQUAL("abcdefg", s2.asCharString()); + STRCMP_EQUAL("AbCdEfG", s1.asCharString()); +} + +TEST(SimpleString, Addition) +{ + SimpleString s1("hello!"); + SimpleString s2("goodbye!"); + SimpleString s3("hello!goodbye!"); + SimpleString s4; + s4 = s1 + s2; + + CHECK_EQUAL(s3, s4); +} + +TEST(SimpleString, Concatenation) +{ + SimpleString s1("hello!"); + SimpleString s2("goodbye!"); + SimpleString s3("hello!goodbye!"); + SimpleString s4; + s4 += s1; + s4 += s2; + + CHECK_EQUAL(s3, s4); + + SimpleString s5("hello!goodbye!hello!goodbye!"); + s4 += s4; + + CHECK_EQUAL(s5, s4); +} + +TEST(SimpleString, Contains) +{ + SimpleString s("hello!"); + SimpleString empty(""); + SimpleString beginning("hello"); + SimpleString end("lo!"); + SimpleString mid("l"); + SimpleString notPartOfString("xxxx"); + + CHECK(s.contains(empty)); + CHECK(s.contains(beginning)); + CHECK(s.contains(end)); + CHECK(s.contains(mid)); + CHECK(!s.contains(notPartOfString)); + + CHECK(empty.contains(empty)); + CHECK(!empty.contains(s)); +} + +TEST(SimpleString, startsWith) +{ + SimpleString hi("Hi you!"); + SimpleString part("Hi"); + SimpleString diff("Hrrm Hi you! ffdsfd"); + CHECK(hi.startsWith(part)); + CHECK(!part.startsWith(hi)); + CHECK(!diff.startsWith(hi)); +} + +TEST(SimpleString, split) +{ + SimpleString hi("hello\nworld\nhow\ndo\nyou\ndo\n\n"); + + SimpleStringCollection collection; + hi.split("\n", collection); + + LONGS_EQUAL(7, collection.size()); + STRCMP_EQUAL("hello\n", collection[0].asCharString()); + STRCMP_EQUAL("world\n", collection[1].asCharString()); + STRCMP_EQUAL("how\n", collection[2].asCharString()); + STRCMP_EQUAL("do\n", collection[3].asCharString()); + STRCMP_EQUAL("you\n", collection[4].asCharString()); + STRCMP_EQUAL("do\n", collection[5].asCharString()); + STRCMP_EQUAL("\n", collection[6].asCharString()); +} + +TEST(SimpleString, splitNoTokenOnTheEnd) +{ + SimpleString string("Bah Yah oops"); + SimpleStringCollection collection; + + string.split(" ", collection); + LONGS_EQUAL(3, collection.size()); + STRCMP_EQUAL("Bah ", collection[0].asCharString()); + STRCMP_EQUAL("Yah ", collection[1].asCharString()); + STRCMP_EQUAL("oops", collection[2].asCharString()); +} + +TEST(SimpleString, count) +{ + SimpleString str("ha ha ha ha"); + LONGS_EQUAL(4, str.count("ha")); +} + +TEST(SimpleString, countTogether) +{ + SimpleString str("hahahaha"); + LONGS_EQUAL(4, str.count("ha")); +} + +TEST(SimpleString, endsWith) +{ + SimpleString str("Hello World"); + CHECK(str.endsWith("World")); + CHECK(!str.endsWith("Worl")); + CHECK(!str.endsWith("Hello")); + SimpleString str2("ah"); + CHECK(str2.endsWith("ah")); + CHECK(!str2.endsWith("baah")); + SimpleString str3(""); + CHECK(!str3.endsWith("baah")); + + SimpleString str4("ha ha ha ha"); + CHECK(str4.endsWith("ha")); +} + +TEST(SimpleString, replaceCharWithChar) +{ + SimpleString str("abcabcabca"); + str.replace('a', 'b'); + STRCMP_EQUAL("bbcbbcbbcb", str.asCharString()); +} + +TEST(SimpleString, replaceStringWithString) +{ + SimpleString str("boo baa boo baa boo"); + str.replace("boo", "boohoo"); + STRCMP_EQUAL("boohoo baa boohoo baa boohoo", str.asCharString()); +} + +TEST(SimpleString, subStringFromEmptyString) +{ + SimpleString str(""); + STRCMP_EQUAL("", str.subString(0, 1).asCharString()); +} + +TEST(SimpleString, subStringFromSmallString) +{ + SimpleString str("H"); + STRCMP_EQUAL("H", str.subString(0, 1).asCharString()); +} + +TEST(SimpleString, subStringFromPos0) +{ + SimpleString str("Hello World"); + STRCMP_EQUAL("Hello", str.subString(0, 5).asCharString()); +} + +TEST(SimpleString, subStringFromPos1) +{ + SimpleString str("Hello World"); + STRCMP_EQUAL("ello ", str.subString(1, 5).asCharString()); +} + +TEST(SimpleString, subStringFromPos5WithAmountLargerThanString) +{ + SimpleString str("Hello World"); + STRCMP_EQUAL("World", str.subString(6, 10).asCharString()); +} + +TEST(SimpleString, subStringBeginPosOutOfBounds) +{ + SimpleString str("Hello World"); + STRCMP_EQUAL("", str.subString(13, 5).asCharString()); +} + +TEST(SimpleString, subStringFromTillNormal) +{ + SimpleString str("Hello World"); + STRCMP_EQUAL("Hello", str.subStringFromTill('H', ' ').asCharString()); +} + +TEST(SimpleString, subStringFromTillOutOfBounds) +{ + SimpleString str("Hello World"); + STRCMP_EQUAL("World", str.subStringFromTill('W', '!').asCharString()); +} + +TEST(SimpleString, subStringFromTillStartDoesntExist) +{ + SimpleString str("Hello World"); + STRCMP_EQUAL("", str.subStringFromTill('!', ' ').asCharString()); +} + +TEST(SimpleString, subStringFromTillWhenTheEndAppearsBeforeTheStart) +{ + SimpleString str("Hello World"); + STRCMP_EQUAL("World", str.subStringFromTill('W', 'H').asCharString()); +} + +TEST(SimpleString, findNormal) +{ + SimpleString str("Hello World"); + LONGS_EQUAL(0, str.find('H')); + LONGS_EQUAL(1, str.find('e')); + LONGS_EQUAL(-1, str.find('!')); +} + +TEST(SimpleString, at) +{ + SimpleString str("Hello World"); + BYTES_EQUAL('H', str.at(0)); +} + +TEST(SimpleString, copyInBufferNormal) +{ + SimpleString str("Hello World"); + size_t bufferSize = str.size()+1; + char* buffer = (char*) malloc(bufferSize); + str.copyToBuffer(buffer, bufferSize); + STRCMP_EQUAL(str.asCharString(), buffer); + free(buffer); +} + +TEST(SimpleString, copyInBufferWithEmptyBuffer) +{ + SimpleString str("Hello World"); + char* buffer= NULL; + str.copyToBuffer(buffer, 0); + POINTERS_EQUAL(NULL, buffer); +} + +TEST(SimpleString, copyInBufferWithBiggerBufferThanNeeded) +{ + SimpleString str("Hello"); + size_t bufferSize = 20; + char* buffer= (char*) malloc(bufferSize); + str.copyToBuffer(buffer, bufferSize); + STRCMP_EQUAL(str.asCharString(), buffer); + free(buffer); +} + +TEST(SimpleString, ContainsNull) +{ + SimpleString s(0); + CHECK(!s.contains("something")); +} + +TEST(SimpleString, NULLReportsNullString) +{ + STRCMP_EQUAL("(null)", StringFromOrNull((char*) NULL).asCharString()); +} + +TEST(SimpleString, Characters) +{ + SimpleString s(StringFrom('a')); + SimpleString s2(StringFrom('a')); + CHECK(s == s2); +} + +TEST(SimpleString, Doubles) +{ + SimpleString s(StringFrom(1.2)); + STRCMP_EQUAL("1.2", s.asCharString()); +} + +TEST(SimpleString, SmallDoubles) +{ + SimpleString s(StringFrom(1.2e-10)); + STRCMP_CONTAINS("1.2e", s.asCharString()); +} + +TEST(SimpleString, Sizes) +{ + size_t size = 10; + STRCMP_EQUAL("10", StringFrom((int) size).asCharString()); +} + +TEST(SimpleString, HexStrings) +{ + SimpleString h1 = HexStringFrom(0xffffL); + STRCMP_EQUAL("ffff", h1.asCharString()); +} + +TEST(SimpleString, StringFromFormat) +{ + SimpleString h1 = StringFromFormat("%s %s! %d", "Hello", "World", 2009); + STRCMP_EQUAL("Hello World! 2009", h1.asCharString()); +} + +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()) + else if (h1.size() == 8) + STRCMP_EQUAL("00000001", h1.asCharString()) + else if (h1.size() == 16) + STRCMP_EQUAL("0000000000000001", h1.asCharString()) + else if (h1.size() == 1) + STRCMP_EQUAL("1", h1.asCharString()) + else + FAIL("Off %p behavior") +} + +TEST(SimpleString, StringFromFormatLarge) +{ + const char* s = "ThisIsAPrettyLargeStringAndIfWeAddThisManyTimesToABufferItWillbeFull"; + SimpleString h1 = StringFromFormat("%s%s%s%s%s%s%s%s%s%s", s, s, s, s, s, s, s, s, s, s); + LONGS_EQUAL(10, h1.count(s)); +} + +static int WrappedUpVSNPrintf(char* buf, size_t n, const char* format, ...) +{ + va_list arguments; + va_start(arguments, format); + + int result = PlatformSpecificVSNprintf(buf, n, format, arguments); + va_end(arguments); + return result; +} + +TEST(SimpleString, PlatformSpecificSprintf_fits) +{ + char buf[10]; + + int count = WrappedUpVSNPrintf(buf, sizeof(buf), "%s", "12345"); + STRCMP_EQUAL("12345", buf); + LONGS_EQUAL(5, count); +} + +TEST(SimpleString, PlatformSpecificSprintf_doesNotFit) +{ + char buf[10]; + + int count = WrappedUpVSNPrintf(buf, sizeof(buf), "%s", "12345678901"); + STRCMP_EQUAL("123456789", buf); + LONGS_EQUAL(11, count); +} + +TEST(SimpleString, PadStringsToSameLengthString1Larger) +{ + SimpleString str1("1"); + SimpleString str2("222"); + + SimpleString::padStringsToSameLength(str1, str2, '4'); + STRCMP_EQUAL("441", str1.asCharString()); + STRCMP_EQUAL("222", str2.asCharString()); +} + +TEST(SimpleString, PadStringsToSameLengthString2Larger) +{ + SimpleString str1(" "); + SimpleString str2(""); + + SimpleString::padStringsToSameLength(str1, str2, ' '); + STRCMP_EQUAL(" ", str1.asCharString()); + STRCMP_EQUAL(" ", str2.asCharString()); +} + +TEST(SimpleString, PadStringsToSameLengthWithSameLengthStrings) +{ + SimpleString str1("123"); + SimpleString str2("123"); + + SimpleString::padStringsToSameLength(str1, str2, ' '); + STRCMP_EQUAL("123", str1.asCharString()); + STRCMP_EQUAL("123", str2.asCharString()); +} + +TEST(SimpleString, NullParameters2) +{ + SimpleString* arr = new SimpleString[100]; + delete[] arr; +} + +TEST(SimpleString, CollectionMultipleAllocateNoLeaksMemory) +{ + SimpleStringCollection col; + col.allocate(5); + col.allocate(5); + // CHECK no memory leak +} + +TEST(SimpleString, CollectionReadOutOfBoundsReturnsEmptyString) +{ + SimpleStringCollection col; + col.allocate(3); + STRCMP_EQUAL("", col[3].asCharString()); +} + +TEST(SimpleString, CollectionWritingToEmptyString) +{ + SimpleStringCollection col; + col.allocate(3); + col[3] = SimpleString("HAH"); + STRCMP_EQUAL("", col[3].asCharString()); +} + +#ifdef CPPUTEST_64BIT +#ifdef CPPUTEST_64BIT_32BIT_LONGS + +/* + * 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 and then this test ought + * to be deleted. + */ +TEST(SimpleString, _64BitAddressPrintsCorrectly) +{ + char* p = (char*) 0xffffffffu; + SimpleString expected("0x23456789"); + SimpleString actual = StringFrom((void*)&p[0x2345678A]); + STRCMP_EQUAL(expected.asCharString(), actual.asCharString()); +} + +#else + +TEST(SimpleString, _64BitAddressPrintsCorrectly) +{ + char* p = (char*) 0x0012345678901234; + SimpleString expected("0x12345678901234"); + SimpleString actual = StringFrom((void*)p); + STRCMP_EQUAL(expected.asCharString(), actual.asCharString()); +} + +#endif +#endif + +TEST(SimpleString, BuildStringFromUnsignedInteger) +{ + unsigned int i = 0xffffffff; + + SimpleString result = StringFrom(i); + const char* expected_string = "4294967295 (0xffffffff)"; + CHECK_EQUAL(expected_string, result); +} + +#if CPPUTEST_USE_STD_CPP_LIB + +TEST(SimpleString, fromStdString) +{ + std::string s("hello"); + SimpleString s1(StringFrom(s)); + + STRCMP_EQUAL("hello", s1.asCharString()); +} + +TEST(SimpleString, CHECK_EQUAL_unsigned_long) +{ + unsigned long i = 0xffffffffUL; + CHECK_EQUAL(i, i); +} + +TEST(SimpleString, unsigned_long) +{ + unsigned long i = 0xffffffffUL; + + SimpleString result = StringFrom(i); + const char* expected_string = "4294967295 (0xffffffff)"; + CHECK_EQUAL(expected_string, result); +} + +#endif diff --git a/tests/TestFailureNaNTest.cpp b/tests/TestFailureNaNTest.cpp index 6c84b5cee..adffc2bfa 100644 --- a/tests/TestFailureNaNTest.cpp +++ b/tests/TestFailureNaNTest.cpp @@ -1,78 +1,78 @@ -/* - * 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" - -namespace -{ -const int failLineNumber = 2; -const char* failFileName = "fail.cpp"; -} - -static double zero = 0.0; -static const double not_a_number = zero / zero; - -TEST_GROUP(TestFailureNaN) -{ - UtestShell* test; - - void setup() - { - test = new NullTestShell(failFileName, failLineNumber-1); - } - void teardown() - { - delete test; - } -}; -#define FAILURE_EQUAL(a, b) STRCMP_EQUAL_LOCATION(a, b.getMessage().asCharString(), __FILE__, __LINE__) - - -TEST(TestFailureNaN, DoublesEqualExpectedIsNaN) -{ - DoublesEqualFailure f(test, failFileName, failLineNumber, not_a_number, 2.0, 3.0); - FAILURE_EQUAL("expected \n" - "\tbut was <2> threshold used was <3>\n" - "\tCannot make comparisons with Nan", f); -} - -TEST(TestFailureNaN, DoublesEqualActualIsNaN) -{ - DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, not_a_number, 3.0); - FAILURE_EQUAL("expected <1>\n" - "\tbut was threshold used was <3>\n" - "\tCannot make comparisons with Nan", f); -} - -TEST(TestFailureNaN, DoublesEqualThresholdIsNaN) -{ - DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, 2.0, not_a_number); - FAILURE_EQUAL("expected <1>\n" - "\tbut was <2> threshold used was \n" - "\tCannot make comparisons with Nan", f); -} +/* + * 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" + +namespace +{ +const int failLineNumber = 2; +const char* failFileName = "fail.cpp"; +} + +static double zero = 0.0; +static const double not_a_number = zero / zero; + +TEST_GROUP(TestFailureNaN) +{ + UtestShell* test; + + void setup() + { + test = new NullTestShell(failFileName, failLineNumber-1); + } + void teardown() + { + delete test; + } +}; +#define FAILURE_EQUAL(a, b) STRCMP_EQUAL_LOCATION(a, b.getMessage().asCharString(), __FILE__, __LINE__) + + +TEST(TestFailureNaN, DoublesEqualExpectedIsNaN) +{ + DoublesEqualFailure f(test, failFileName, failLineNumber, not_a_number, 2.0, 3.0); + FAILURE_EQUAL("expected \n" + "\tbut was <2> threshold used was <3>\n" + "\tCannot make comparisons with Nan", f); +} + +TEST(TestFailureNaN, DoublesEqualActualIsNaN) +{ + DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, not_a_number, 3.0); + FAILURE_EQUAL("expected <1>\n" + "\tbut was threshold used was <3>\n" + "\tCannot make comparisons with Nan", f); +} + +TEST(TestFailureNaN, DoublesEqualThresholdIsNaN) +{ + DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, 2.0, not_a_number); + FAILURE_EQUAL("expected <1>\n" + "\tbut was <2> threshold used was \n" + "\tCannot make comparisons with Nan", f); +} diff --git a/tests/TestFailureTest.cpp b/tests/TestFailureTest.cpp index 7753c207d..962db28c3 100644 --- a/tests/TestFailureTest.cpp +++ b/tests/TestFailureTest.cpp @@ -1,199 +1,199 @@ -/* - * 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" - -namespace -{ -const int failLineNumber = 2; -const char* failFileName = "fail.cpp"; -} - -TEST_GROUP(TestFailure) -{ - UtestShell* test; - - void setup() - { - test = new NullTestShell(failFileName, failLineNumber-1); - } - void teardown() - { - delete test; - } -}; -#define FAILURE_EQUAL(a, b) STRCMP_EQUAL_LOCATION(a, b.getMessage().asCharString(), __FILE__, __LINE__) - -TEST(TestFailure, CreateFailure) -{ - TestFailure f1(test, failFileName, failLineNumber, "the failure message"); - TestFailure f2(test, "the failure message"); - TestFailure f3(test, failFileName, failLineNumber); -} - -TEST(TestFailure, GetTestFileAndLineFromFailure) -{ - TestFailure f1(test, failFileName, failLineNumber, "the failure message"); - STRCMP_EQUAL(failFileName, f1.getTestFileName().asCharString()); - LONGS_EQUAL(1, f1.getTestLineNumber()); -} - -TEST(TestFailure, CreatePassingEqualsFailure) -{ - EqualsFailure f(test, failFileName, failLineNumber, "expected", "actual"); - FAILURE_EQUAL("expected \n\tbut was ", f); -} - -TEST(TestFailure, EqualsFailureWithNullAsActual) -{ - EqualsFailure f(test, failFileName, failLineNumber, "expected", NULL); - FAILURE_EQUAL("expected \n\tbut was <(null)>", f); -} - -TEST(TestFailure, EqualsFailureWithNullAsExpected) -{ - EqualsFailure f(test, failFileName, failLineNumber, NULL, "actual"); - FAILURE_EQUAL("expected <(null)>\n\tbut was ", f); -} - -TEST(TestFailure, CheckEqualFailure) -{ - CheckEqualFailure f(test, failFileName, failLineNumber, "expected", "actual"); - FAILURE_EQUAL("expected \n" - "\tbut was \n" - "\tdifference starts at position 0 at: < actual >\n" - "\t ^", f); -} - -TEST(TestFailure, CheckFailure) -{ - CheckFailure f(test, failFileName, failLineNumber, "CHECK", "chk"); - FAILURE_EQUAL("CHECK(chk) failed", f); -} - -TEST(TestFailure, CheckFailureWithText) -{ - CheckFailure f(test, failFileName, failLineNumber, "CHECK", "chk", "text"); - FAILURE_EQUAL("Message: text\n" - "\tCHECK(chk) failed", f); -} - -TEST(TestFailure, FailFailure) -{ - FailFailure f(test, failFileName, failLineNumber, "chk"); - FAILURE_EQUAL("chk", f); -} - -TEST(TestFailure, LongsEqualFailure) -{ - LongsEqualFailure f(test, failFileName, failLineNumber, 1, 2); - FAILURE_EQUAL("expected <1 0x1>\n\tbut was <2 0x2>", f); -} - -TEST(TestFailure, StringsEqualFailure) -{ - StringEqualFailure f(test, failFileName, failLineNumber, "abc", "abd"); - FAILURE_EQUAL("expected \n" - "\tbut was \n" - "\tdifference starts at position 2 at: < abd >\n" - "\t ^", f); -} - -TEST(TestFailure, StringsEqualFailureAtTheEnd) -{ - StringEqualFailure f(test, failFileName, failLineNumber, "abc", "ab"); - FAILURE_EQUAL("expected \n" - "\tbut was \n" - "\tdifference starts at position 2 at: < ab >\n" - "\t ^", f); -} - -TEST(TestFailure, StringsEqualFailureNewVariantAtTheEnd) -{ - StringEqualFailure f(test, failFileName, failLineNumber, "EndOfALongerString", "EndOfALongerStrinG"); - FAILURE_EQUAL("expected \n" - "\tbut was \n" - "\tdifference starts at position 17 at: \n" - "\t ^", f); -} - -TEST(TestFailure, StringsEqualFailureWithNewLinesAndTabs) -{ - StringEqualFailure f(test, failFileName, failLineNumber, - "StringWith\t\nDifferentString", - "StringWith\t\ndifferentString"); - - FAILURE_EQUAL("expected \n" - "\tbut was \n" - "\tdifference starts at position 12 at: \n" - "\t \t\n^", f); -} - -TEST(TestFailure, StringsEqualFailureInTheMiddle) -{ - StringEqualFailure f(test, failFileName, failLineNumber, "aa", "ab"); - FAILURE_EQUAL("expected \n" - "\tbut was \n" - "\tdifference starts at position 1 at: < ab >\n" - "\t ^", f); -} - - -TEST(TestFailure, StringsEqualFailureAtTheBeginning) -{ - StringEqualFailure f(test, failFileName, failLineNumber, "aaa", "bbb"); - FAILURE_EQUAL("expected \n" - "\tbut was \n" - "\tdifference starts at position 0 at: < bbb >\n" - "\t ^", f); -} - -TEST(TestFailure, StringsEqualNoCaseFailure) -{ - StringEqualNoCaseFailure f(test, failFileName, failLineNumber, "ABC", "abd"); - FAILURE_EQUAL("expected \n" - "\tbut was \n" - "\tdifference starts at position 2 at: < abd >\n" - "\t ^", f); -} - -TEST(TestFailure, StringsEqualNoCaseFailure2) -{ - StringEqualNoCaseFailure f(test, failFileName, failLineNumber, "ac", "AB"); - FAILURE_EQUAL("expected \n" - "\tbut was \n" - "\tdifference starts at position 1 at: < AB >\n" - "\t ^", f); -} - -TEST(TestFailure, DoublesEqualNormal) -{ - DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, 2.0, 3.0); - FAILURE_EQUAL("expected <1>\n" - "\tbut was <2> threshold used was <3>", f); -} +/* + * 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" + +namespace +{ +const int failLineNumber = 2; +const char* failFileName = "fail.cpp"; +} + +TEST_GROUP(TestFailure) +{ + UtestShell* test; + + void setup() + { + test = new NullTestShell(failFileName, failLineNumber-1); + } + void teardown() + { + delete test; + } +}; +#define FAILURE_EQUAL(a, b) STRCMP_EQUAL_LOCATION(a, b.getMessage().asCharString(), __FILE__, __LINE__) + +TEST(TestFailure, CreateFailure) +{ + TestFailure f1(test, failFileName, failLineNumber, "the failure message"); + TestFailure f2(test, "the failure message"); + TestFailure f3(test, failFileName, failLineNumber); +} + +TEST(TestFailure, GetTestFileAndLineFromFailure) +{ + TestFailure f1(test, failFileName, failLineNumber, "the failure message"); + STRCMP_EQUAL(failFileName, f1.getTestFileName().asCharString()); + LONGS_EQUAL(1, f1.getTestLineNumber()); +} + +TEST(TestFailure, CreatePassingEqualsFailure) +{ + EqualsFailure f(test, failFileName, failLineNumber, "expected", "actual"); + FAILURE_EQUAL("expected \n\tbut was ", f); +} + +TEST(TestFailure, EqualsFailureWithNullAsActual) +{ + EqualsFailure f(test, failFileName, failLineNumber, "expected", NULL); + FAILURE_EQUAL("expected \n\tbut was <(null)>", f); +} + +TEST(TestFailure, EqualsFailureWithNullAsExpected) +{ + EqualsFailure f(test, failFileName, failLineNumber, NULL, "actual"); + FAILURE_EQUAL("expected <(null)>\n\tbut was ", f); +} + +TEST(TestFailure, CheckEqualFailure) +{ + CheckEqualFailure f(test, failFileName, failLineNumber, "expected", "actual"); + FAILURE_EQUAL("expected \n" + "\tbut was \n" + "\tdifference starts at position 0 at: < actual >\n" + "\t ^", f); +} + +TEST(TestFailure, CheckFailure) +{ + CheckFailure f(test, failFileName, failLineNumber, "CHECK", "chk"); + FAILURE_EQUAL("CHECK(chk) failed", f); +} + +TEST(TestFailure, CheckFailureWithText) +{ + CheckFailure f(test, failFileName, failLineNumber, "CHECK", "chk", "text"); + FAILURE_EQUAL("Message: text\n" + "\tCHECK(chk) failed", f); +} + +TEST(TestFailure, FailFailure) +{ + FailFailure f(test, failFileName, failLineNumber, "chk"); + FAILURE_EQUAL("chk", f); +} + +TEST(TestFailure, LongsEqualFailure) +{ + LongsEqualFailure f(test, failFileName, failLineNumber, 1, 2); + FAILURE_EQUAL("expected <1 0x1>\n\tbut was <2 0x2>", f); +} + +TEST(TestFailure, StringsEqualFailure) +{ + StringEqualFailure f(test, failFileName, failLineNumber, "abc", "abd"); + FAILURE_EQUAL("expected \n" + "\tbut was \n" + "\tdifference starts at position 2 at: < abd >\n" + "\t ^", f); +} + +TEST(TestFailure, StringsEqualFailureAtTheEnd) +{ + StringEqualFailure f(test, failFileName, failLineNumber, "abc", "ab"); + FAILURE_EQUAL("expected \n" + "\tbut was \n" + "\tdifference starts at position 2 at: < ab >\n" + "\t ^", f); +} + +TEST(TestFailure, StringsEqualFailureNewVariantAtTheEnd) +{ + StringEqualFailure f(test, failFileName, failLineNumber, "EndOfALongerString", "EndOfALongerStrinG"); + FAILURE_EQUAL("expected \n" + "\tbut was \n" + "\tdifference starts at position 17 at: \n" + "\t ^", f); +} + +TEST(TestFailure, StringsEqualFailureWithNewLinesAndTabs) +{ + StringEqualFailure f(test, failFileName, failLineNumber, + "StringWith\t\nDifferentString", + "StringWith\t\ndifferentString"); + + FAILURE_EQUAL("expected \n" + "\tbut was \n" + "\tdifference starts at position 12 at: \n" + "\t \t\n^", f); +} + +TEST(TestFailure, StringsEqualFailureInTheMiddle) +{ + StringEqualFailure f(test, failFileName, failLineNumber, "aa", "ab"); + FAILURE_EQUAL("expected \n" + "\tbut was \n" + "\tdifference starts at position 1 at: < ab >\n" + "\t ^", f); +} + + +TEST(TestFailure, StringsEqualFailureAtTheBeginning) +{ + StringEqualFailure f(test, failFileName, failLineNumber, "aaa", "bbb"); + FAILURE_EQUAL("expected \n" + "\tbut was \n" + "\tdifference starts at position 0 at: < bbb >\n" + "\t ^", f); +} + +TEST(TestFailure, StringsEqualNoCaseFailure) +{ + StringEqualNoCaseFailure f(test, failFileName, failLineNumber, "ABC", "abd"); + FAILURE_EQUAL("expected \n" + "\tbut was \n" + "\tdifference starts at position 2 at: < abd >\n" + "\t ^", f); +} + +TEST(TestFailure, StringsEqualNoCaseFailure2) +{ + StringEqualNoCaseFailure f(test, failFileName, failLineNumber, "ac", "AB"); + FAILURE_EQUAL("expected \n" + "\tbut was \n" + "\tdifference starts at position 1 at: < AB >\n" + "\t ^", f); +} + +TEST(TestFailure, DoublesEqualNormal) +{ + DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, 2.0, 3.0); + FAILURE_EQUAL("expected <1>\n" + "\tbut was <2> threshold used was <3>", f); +} diff --git a/tests/TestHarness_cTest.cpp b/tests/TestHarness_cTest.cpp index ce2861304..a19f609cf 100644 --- a/tests/TestHarness_cTest.cpp +++ b/tests/TestHarness_cTest.cpp @@ -1,306 +1,306 @@ -/* - * 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(TestGroupInC) -{ - TEST_GROUP_C_SETUP_WRAPPER(TestGroupInC) - TEST_GROUP_C_TEARDOWN_WRAPPER(TestGroupInC) -}; - -TEST_GROUP_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); -} - -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); -} - -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 _failStringMethod() -{ - HasTheDestructorBeenCalledChecker checker; - CHECK_EQUAL_C_STRING("Hello", "Hello World"); -} - -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 _failTextMethod() -{ - HasTheDestructorBeenCalledChecker checker; - FAIL_TEXT_C("Booo"); -} - -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(); -} - -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); -} - -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); - - PlatformSpecificStrCpy(mem1, number_string); - 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 - +/* + * 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(TestGroupInC) +{ + TEST_GROUP_C_SETUP_WRAPPER(TestGroupInC) + TEST_GROUP_C_TEARDOWN_WRAPPER(TestGroupInC) +}; + +TEST_GROUP_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); +} + +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); +} + +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 _failStringMethod() +{ + HasTheDestructorBeenCalledChecker checker; + CHECK_EQUAL_C_STRING("Hello", "Hello World"); +} + +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 _failTextMethod() +{ + HasTheDestructorBeenCalledChecker checker; + FAIL_TEXT_C("Booo"); +} + +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(); +} + +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); +} + +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); + + PlatformSpecificStrCpy(mem1, number_string); + 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/TestInstallerTest.cpp b/tests/TestInstallerTest.cpp index 4ff269c40..166b1f50a 100644 --- a/tests/TestInstallerTest.cpp +++ b/tests/TestInstallerTest.cpp @@ -1,63 +1,63 @@ -/* - * 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/TestRegistry.h" - -class TestInstallerTestUtestShell : public UtestShell -{ -}; - - -// this is file scope because the test is installed -// with all other tests, which also happen to be -// created as static instances at file scope - -TEST_GROUP(TestInstaller) -{ - TestInstaller* testInstaller; - TestRegistry* myRegistry; - TestInstallerTestUtestShell shell; - void setup() - { - myRegistry = new TestRegistry(); - myRegistry->setCurrentRegistry(myRegistry); - testInstaller = new TestInstaller(shell, "TestInstaller", "test", __FILE__, __LINE__); - } - void teardown() - { - myRegistry->setCurrentRegistry(0); - testInstaller->unDo(); - delete testInstaller; - delete myRegistry; - } -}; - -TEST(TestInstaller, Create) -{ -} - +/* + * 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/TestRegistry.h" + +class TestInstallerTestUtestShell : public UtestShell +{ +}; + + +// this is file scope because the test is installed +// with all other tests, which also happen to be +// created as static instances at file scope + +TEST_GROUP(TestInstaller) +{ + TestInstaller* testInstaller; + TestRegistry* myRegistry; + TestInstallerTestUtestShell shell; + void setup() + { + myRegistry = new TestRegistry(); + myRegistry->setCurrentRegistry(myRegistry); + testInstaller = new TestInstaller(shell, "TestInstaller", "test", __FILE__, __LINE__); + } + void teardown() + { + myRegistry->setCurrentRegistry(0); + testInstaller->unDo(); + delete testInstaller; + delete myRegistry; + } +}; + +TEST(TestInstaller, Create) +{ +} + diff --git a/tests/TestMemoryAllocatorTest.cpp b/tests/TestMemoryAllocatorTest.cpp index a4ce1483c..2a129f2de 100644 --- a/tests/TestMemoryAllocatorTest.cpp +++ b/tests/TestMemoryAllocatorTest.cpp @@ -1,113 +1,113 @@ -/* - * 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() - { - if (allocator) 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()); -} +/* + * 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() + { + if (allocator) 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()); +} diff --git a/tests/TestRegistryTest.cpp b/tests/TestRegistryTest.cpp index 440b9287a..58be09bdd 100644 --- a/tests/TestRegistryTest.cpp +++ b/tests/TestRegistryTest.cpp @@ -1,285 +1,285 @@ -/* - * 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/TestRegistry.h" -#include "CppUTest/TestOutput.h" - -namespace -{ -const int testLineNumber = 1; -} - -class MockTest: public UtestShell -{ -public: - MockTest(const char* group = "Group") : - UtestShell(group, "Name", "File", testLineNumber), hasRun_(false) - { - } - virtual void runOneTest(TestPlugin*, TestResult&) - { - hasRun_ = true; - } - - bool hasRun_; -}; - -class MockTestResult: public TestResult -{ -public: - - int countTestsStarted; - int countTestsEnded; - int countCurrentTestStarted; - int countCurrentTestEnded; - int countCurrentGroupStarted; - int countCurrentGroupEnded; - - MockTestResult(TestOutput& p) : - TestResult(p) - { - resetCount(); - } - - virtual ~MockTestResult() - { - } - - void resetCount() - { - countTestsStarted = 0; - countTestsEnded = 0; - countCurrentTestStarted = 0; - countCurrentTestEnded = 0; - countCurrentGroupStarted = 0; - countCurrentGroupEnded = 0; - } - - virtual void testsStarted() - { - countTestsStarted++; - } - virtual void testsEnded() - { - countTestsEnded++; - } - virtual void currentTestStarted(UtestShell* /*test*/) - { - countCurrentTestStarted++; - } - virtual void currentTestEnded(UtestShell* /*test*/) - { - countCurrentTestEnded++; - } - virtual void currentGroupStarted(UtestShell* /*test*/) - { - countCurrentGroupStarted++; - } - virtual void currentGroupEnded(UtestShell* /*test*/) - { - countCurrentGroupEnded++; - } - -}; - -TEST_GROUP(TestRegistry) -{ - TestRegistry* myRegistry; - StringBufferTestOutput* output; - MockTest* test1; - MockTest* test2; - MockTest* test3; - TestResult *result; - MockTestResult *mockResult; - void setup() - { - output = new StringBufferTestOutput(); - mockResult = new MockTestResult(*output); - result = mockResult; - test1 = new MockTest(); - test2 = new MockTest(); - test3 = new MockTest("group2"); - myRegistry = new TestRegistry(); - myRegistry->setCurrentRegistry(myRegistry); - } - - void teardown() - { - myRegistry->setCurrentRegistry(0); - delete myRegistry; - delete test1; - delete test2; - delete test3; - delete result; - delete output; - } - - void addAndRunAllTests() - { - myRegistry->addTest(test1); - myRegistry->addTest(test2); - myRegistry->addTest(test3); - myRegistry->runAllTests(*result); - } -}; - -TEST(TestRegistry, registryMyRegistryAndReset) -{ - CHECK(myRegistry->getCurrentRegistry() == myRegistry); -} - -TEST(TestRegistry, emptyRegistryIsEmpty) -{ - CHECK(myRegistry->countTests() == 0); -} - -TEST(TestRegistry, addOneTestIsNotEmpty) -{ - myRegistry->addTest(test1); - CHECK(myRegistry->countTests() == 1); -} - -TEST(TestRegistry, addOneTwoTests) -{ - myRegistry->addTest(test1); - myRegistry->addTest(test2); - CHECK(myRegistry->countTests() == 2); -} - -TEST(TestRegistry, runTwoTests) -{ - myRegistry->addTest(test1); - myRegistry->addTest(test2); - CHECK(!test1->hasRun_); - CHECK(!test2->hasRun_); - myRegistry->runAllTests(*result); - CHECK(test1->hasRun_); - CHECK(test2->hasRun_); -} - -TEST(TestRegistry, runTwoTestsCheckResultFunctionsCalled) -{ - myRegistry->addTest(test1); - myRegistry->addTest(test2); - myRegistry->runAllTests(*result); - LONGS_EQUAL(1, mockResult->countTestsStarted); - LONGS_EQUAL(1, mockResult->countTestsEnded); - LONGS_EQUAL(1, mockResult->countCurrentGroupStarted); - LONGS_EQUAL(1, mockResult->countCurrentGroupEnded); - LONGS_EQUAL(2, mockResult->countCurrentTestStarted); - LONGS_EQUAL(2, mockResult->countCurrentTestEnded); -} - -TEST(TestRegistry, runThreeTestsandTwoGroupsCheckResultFunctionsCalled) -{ - addAndRunAllTests(); - LONGS_EQUAL(2, mockResult->countCurrentGroupStarted); - LONGS_EQUAL(2, mockResult->countCurrentGroupEnded); - LONGS_EQUAL(3, mockResult->countCurrentTestStarted); - LONGS_EQUAL(3, mockResult->countCurrentTestEnded); -} - -TEST(TestRegistry, unDoTest) -{ - myRegistry->addTest(test1); - CHECK(myRegistry->countTests() == 1); - myRegistry->unDoLastAddTest(); - CHECK(myRegistry->countTests() == 0); -} - -TEST(TestRegistry, unDoButNoTest) -{ - CHECK(myRegistry->countTests() == 0); - myRegistry->unDoLastAddTest(); - CHECK(myRegistry->countTests() == 0); -} - -TEST(TestRegistry, reallyUndoLastTest) -{ - myRegistry->addTest(test1); - myRegistry->addTest(test2); - CHECK(myRegistry->countTests() == 2); - myRegistry->unDoLastAddTest(); - CHECK(myRegistry->countTests() == 1); - myRegistry->runAllTests(*result); - CHECK(test1->hasRun_); - CHECK(!test2->hasRun_); -} - -TEST(TestRegistry, findTestWithNameDoesntExist) -{ - CHECK(myRegistry->findTestWithName("ThisTestDoesntExists") == NULL); -} - -TEST(TestRegistry, findTestWithName) -{ - test1->setTestName("NameOfATestThatDoesExist"); - myRegistry->addTest(test1); - CHECK(myRegistry->findTestWithName("NameOfATestThatDoesExist")); -} - -TEST(TestRegistry, findTestWithGroupDoesntExist) -{ - CHECK(myRegistry->findTestWithGroup("ThisTestGroupDoesntExists") == NULL); -} - -TEST(TestRegistry, findTestWithGroup) -{ - test1->setGroupName("GroupOfATestThatDoesExist"); - myRegistry->addTest(test1); - CHECK(myRegistry->findTestWithGroup("GroupOfATestThatDoesExist")); -} - -TEST(TestRegistry, nameFilterWorks) -{ - test1->setTestName("testname"); - test2->setTestName("noname"); - myRegistry->nameFilter("testname"); - addAndRunAllTests(); - CHECK(test1->hasRun_); - CHECK(!test2->hasRun_); -} - -TEST(TestRegistry, groupFilterWorks) -{ - test1->setGroupName("groupname"); - test2->setGroupName("noname"); - myRegistry->groupFilter("groupname"); - addAndRunAllTests(); - CHECK(test1->hasRun_); - CHECK(!test2->hasRun_); -} - -TEST(TestRegistry, runTestInSeperateProcess) -{ - myRegistry->setRunTestsInSeperateProcess(); - myRegistry->addTest(test1); - myRegistry->runAllTests(*result); - CHECK(test1->isRunInSeperateProcess()); -} - +/* + * 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/TestRegistry.h" +#include "CppUTest/TestOutput.h" + +namespace +{ +const int testLineNumber = 1; +} + +class MockTest: public UtestShell +{ +public: + MockTest(const char* group = "Group") : + UtestShell(group, "Name", "File", testLineNumber), hasRun_(false) + { + } + virtual void runOneTest(TestPlugin*, TestResult&) + { + hasRun_ = true; + } + + bool hasRun_; +}; + +class MockTestResult: public TestResult +{ +public: + + int countTestsStarted; + int countTestsEnded; + int countCurrentTestStarted; + int countCurrentTestEnded; + int countCurrentGroupStarted; + int countCurrentGroupEnded; + + MockTestResult(TestOutput& p) : + TestResult(p) + { + resetCount(); + } + + virtual ~MockTestResult() + { + } + + void resetCount() + { + countTestsStarted = 0; + countTestsEnded = 0; + countCurrentTestStarted = 0; + countCurrentTestEnded = 0; + countCurrentGroupStarted = 0; + countCurrentGroupEnded = 0; + } + + virtual void testsStarted() + { + countTestsStarted++; + } + virtual void testsEnded() + { + countTestsEnded++; + } + virtual void currentTestStarted(UtestShell* /*test*/) + { + countCurrentTestStarted++; + } + virtual void currentTestEnded(UtestShell* /*test*/) + { + countCurrentTestEnded++; + } + virtual void currentGroupStarted(UtestShell* /*test*/) + { + countCurrentGroupStarted++; + } + virtual void currentGroupEnded(UtestShell* /*test*/) + { + countCurrentGroupEnded++; + } + +}; + +TEST_GROUP(TestRegistry) +{ + TestRegistry* myRegistry; + StringBufferTestOutput* output; + MockTest* test1; + MockTest* test2; + MockTest* test3; + TestResult *result; + MockTestResult *mockResult; + void setup() + { + output = new StringBufferTestOutput(); + mockResult = new MockTestResult(*output); + result = mockResult; + test1 = new MockTest(); + test2 = new MockTest(); + test3 = new MockTest("group2"); + myRegistry = new TestRegistry(); + myRegistry->setCurrentRegistry(myRegistry); + } + + void teardown() + { + myRegistry->setCurrentRegistry(0); + delete myRegistry; + delete test1; + delete test2; + delete test3; + delete result; + delete output; + } + + void addAndRunAllTests() + { + myRegistry->addTest(test1); + myRegistry->addTest(test2); + myRegistry->addTest(test3); + myRegistry->runAllTests(*result); + } +}; + +TEST(TestRegistry, registryMyRegistryAndReset) +{ + CHECK(myRegistry->getCurrentRegistry() == myRegistry); +} + +TEST(TestRegistry, emptyRegistryIsEmpty) +{ + CHECK(myRegistry->countTests() == 0); +} + +TEST(TestRegistry, addOneTestIsNotEmpty) +{ + myRegistry->addTest(test1); + CHECK(myRegistry->countTests() == 1); +} + +TEST(TestRegistry, addOneTwoTests) +{ + myRegistry->addTest(test1); + myRegistry->addTest(test2); + CHECK(myRegistry->countTests() == 2); +} + +TEST(TestRegistry, runTwoTests) +{ + myRegistry->addTest(test1); + myRegistry->addTest(test2); + CHECK(!test1->hasRun_); + CHECK(!test2->hasRun_); + myRegistry->runAllTests(*result); + CHECK(test1->hasRun_); + CHECK(test2->hasRun_); +} + +TEST(TestRegistry, runTwoTestsCheckResultFunctionsCalled) +{ + myRegistry->addTest(test1); + myRegistry->addTest(test2); + myRegistry->runAllTests(*result); + LONGS_EQUAL(1, mockResult->countTestsStarted); + LONGS_EQUAL(1, mockResult->countTestsEnded); + LONGS_EQUAL(1, mockResult->countCurrentGroupStarted); + LONGS_EQUAL(1, mockResult->countCurrentGroupEnded); + LONGS_EQUAL(2, mockResult->countCurrentTestStarted); + LONGS_EQUAL(2, mockResult->countCurrentTestEnded); +} + +TEST(TestRegistry, runThreeTestsandTwoGroupsCheckResultFunctionsCalled) +{ + addAndRunAllTests(); + LONGS_EQUAL(2, mockResult->countCurrentGroupStarted); + LONGS_EQUAL(2, mockResult->countCurrentGroupEnded); + LONGS_EQUAL(3, mockResult->countCurrentTestStarted); + LONGS_EQUAL(3, mockResult->countCurrentTestEnded); +} + +TEST(TestRegistry, unDoTest) +{ + myRegistry->addTest(test1); + CHECK(myRegistry->countTests() == 1); + myRegistry->unDoLastAddTest(); + CHECK(myRegistry->countTests() == 0); +} + +TEST(TestRegistry, unDoButNoTest) +{ + CHECK(myRegistry->countTests() == 0); + myRegistry->unDoLastAddTest(); + CHECK(myRegistry->countTests() == 0); +} + +TEST(TestRegistry, reallyUndoLastTest) +{ + myRegistry->addTest(test1); + myRegistry->addTest(test2); + CHECK(myRegistry->countTests() == 2); + myRegistry->unDoLastAddTest(); + CHECK(myRegistry->countTests() == 1); + myRegistry->runAllTests(*result); + CHECK(test1->hasRun_); + CHECK(!test2->hasRun_); +} + +TEST(TestRegistry, findTestWithNameDoesntExist) +{ + CHECK(myRegistry->findTestWithName("ThisTestDoesntExists") == NULL); +} + +TEST(TestRegistry, findTestWithName) +{ + test1->setTestName("NameOfATestThatDoesExist"); + myRegistry->addTest(test1); + CHECK(myRegistry->findTestWithName("NameOfATestThatDoesExist")); +} + +TEST(TestRegistry, findTestWithGroupDoesntExist) +{ + CHECK(myRegistry->findTestWithGroup("ThisTestGroupDoesntExists") == NULL); +} + +TEST(TestRegistry, findTestWithGroup) +{ + test1->setGroupName("GroupOfATestThatDoesExist"); + myRegistry->addTest(test1); + CHECK(myRegistry->findTestWithGroup("GroupOfATestThatDoesExist")); +} + +TEST(TestRegistry, nameFilterWorks) +{ + test1->setTestName("testname"); + test2->setTestName("noname"); + myRegistry->nameFilter("testname"); + addAndRunAllTests(); + CHECK(test1->hasRun_); + CHECK(!test2->hasRun_); +} + +TEST(TestRegistry, groupFilterWorks) +{ + test1->setGroupName("groupname"); + test2->setGroupName("noname"); + myRegistry->groupFilter("groupname"); + addAndRunAllTests(); + CHECK(test1->hasRun_); + CHECK(!test2->hasRun_); +} + +TEST(TestRegistry, runTestInSeperateProcess) +{ + myRegistry->setRunTestsInSeperateProcess(); + myRegistry->addTest(test1); + myRegistry->runAllTests(*result); + CHECK(test1->isRunInSeperateProcess()); +} + diff --git a/tests/TestResultTest.cpp b/tests/TestResultTest.cpp index 3bed83b25..271b0e2ff 100644 --- a/tests/TestResultTest.cpp +++ b/tests/TestResultTest.cpp @@ -1,67 +1,67 @@ -/* - * 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/PlatformSpecificFunctions.h" -#include "CppUTest/TestOutput.h" - -extern "C" { - - static long MockGetPlatformSpecificTimeInMillis() - { - return 10; - } - -} - -TEST_GROUP(TestResult) -{ - TestOutput* printer; - StringBufferTestOutput* mock; - - TestResult* res; - - void setup() - { - mock = new StringBufferTestOutput(); - printer = mock; - res = new TestResult(*printer); - SetPlatformSpecificTimeInMillisMethod(MockGetPlatformSpecificTimeInMillis); - } - void teardown() - { - SetPlatformSpecificTimeInMillisMethod(0); - delete printer; - delete res; - } -}; - -TEST(TestResult, TestEndedWillPrintResultsAndExecutionTime) -{ - res->testsEnded(); - CHECK(mock->getOutput().contains("10 ms")); -} +/* + * 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/PlatformSpecificFunctions.h" +#include "CppUTest/TestOutput.h" + +extern "C" { + + static long MockGetPlatformSpecificTimeInMillis() + { + return 10; + } + +} + +TEST_GROUP(TestResult) +{ + TestOutput* printer; + StringBufferTestOutput* mock; + + TestResult* res; + + void setup() + { + mock = new StringBufferTestOutput(); + printer = mock; + res = new TestResult(*printer); + SetPlatformSpecificTimeInMillisMethod(MockGetPlatformSpecificTimeInMillis); + } + void teardown() + { + SetPlatformSpecificTimeInMillisMethod(0); + delete printer; + delete res; + } +}; + +TEST(TestResult, TestEndedWillPrintResultsAndExecutionTime) +{ + res->testsEnded(); + CHECK(mock->getOutput().contains("10 ms")); +} diff --git a/tests/UtestTest.cpp b/tests/UtestTest.cpp index 470e2ce76..d0a13bbe1 100644 --- a/tests/UtestTest.cpp +++ b/tests/UtestTest.cpp @@ -1,243 +1,243 @@ -/* - * 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); -} - -TEST(UtestShell, compareDoubles) -{ - double zero = 0.0; - double not_a_number = zero / 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)); - - 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 != 0); -} - -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()); -} - -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_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_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 */ - TestRegistry* reg = TestRegistry::getCurrentRegistry(); - nullTest.shouldRun(reg->getGroupFilter(), reg->getNameFilter()); -} - -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(); -} - +/* + * 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); +} + +TEST(UtestShell, compareDoubles) +{ + double zero = 0.0; + double not_a_number = zero / 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)); + + 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 != 0); +} + +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()); +} + +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_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_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 */ + TestRegistry* reg = TestRegistry::getCurrentRegistry(); + nullTest.shouldRun(reg->getGroupFilter(), reg->getNameFilter()); +} + +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(); +} +