ID
int64
1
1.09k
Language
stringclasses
1 value
Repository Name
stringclasses
8 values
File Name
stringlengths
3
35
File Path in Repository
stringlengths
9
82
File Path for Unit Test
stringclasses
5 values
Code
stringlengths
17
1.91M
Unit Test - (Ground Truth)
stringclasses
5 values
101
cpp
cpputest
StandardCLibrary.h
include/CppUTest/StandardCLibrary.h
null
/* Must include this first to ensure the StandardC include in CppUTestConfig still happens at the right moment */ #include "CppUTestConfig.h" #ifndef STANDARDCLIBRARY_H_ #define STANDARDCLIBRARY_H_ #if CPPUTEST_USE_STD_C_LIB /* Needed for size_t */ #include <stddef.h> /* Sometimes the C++ library does an #undef in stdlib of malloc and free. We want to prevent that */ #ifdef __cplusplus #if CPPUTEST_USE_STD_CPP_LIB #include <cstdlib> #include <cstring> #include <string> #endif #endif /* Needed for malloc */ #include <stdlib.h> /* Needed for std::nullptr */ #ifdef __cplusplus #if CPPUTEST_USE_STD_CPP_LIB #include <cstddef> #endif #endif /* Needed for ... */ #include <stdarg.h> /* Kludge to get a va_copy in VC++ V6 and in GCC 98 */ #ifndef va_copy #ifdef __GNUC__ #define va_copy __va_copy #else #define va_copy(copy, original) copy = original; #endif #endif /* Needed for some detection of long long and 64 bit */ #include <limits.h> /* Needed to ensure that string.h is included prior to strdup redefinition */ #ifdef CPPUTEST_HAVE_STRDUP #include <string.h> #endif #else #ifdef __KERNEL__ /* Unfinished and not working! Hacking hacking hacking. Why bother make the header files C++ safe! */ #define false kernel_false #define true kernel_true #define bool kernel_bool #define new kernel_new #define _Bool int #include <linux/acpi.h> #include <linux/types.h> #undef false #undef true #undef bool #undef new #else /* * #warning "These definitions in StandardCLibrary.h are pure (educated, from linux kernel) guesses at the moment. Replace with your platform includes." * Not on as warning are as errors :P */ #ifdef __SIZE_TYPE__ typedef __SIZE_TYPE__ size_t; #else typedef long unsigned int size_t; #endif #define NULL (0) #ifdef __cplusplus extern "C" { #endif extern void* malloc(size_t); extern void free(void *); #ifdef __cplusplus } #endif #define _bnd(X, bnd) (((sizeof (X)) + (bnd)) & (~(bnd))) #define va_list __builtin_va_list #define va_copy __builtin_va_copy #define va_start __builtin_va_start #define va_end __builtin_va_end #endif #endif #endif
null
102
cpp
cpputest
MemoryLeakWarningPlugin.h
include/CppUTest/MemoryLeakWarningPlugin.h
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 <organization> 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 <copyright holder> 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_MemoryLeakWarningPlugin_h #define D_MemoryLeakWarningPlugin_h #include "TestPlugin.h" #include "MemoryLeakDetectorNewMacros.h" #define IGNORE_ALL_LEAKS_IN_TEST() if (MemoryLeakWarningPlugin::getFirstPlugin()) MemoryLeakWarningPlugin::getFirstPlugin()->ignoreAllLeaksInTest() #define EXPECT_N_LEAKS(n) if (MemoryLeakWarningPlugin::getFirstPlugin()) MemoryLeakWarningPlugin::getFirstPlugin()->expectLeaksInTest(n) extern void crash_on_allocation_number(unsigned alloc_number); class MemoryLeakDetector; class MemoryLeakFailure; class MemoryLeakWarningPlugin: public TestPlugin { public: MemoryLeakWarningPlugin(const SimpleString& name, MemoryLeakDetector* localDetector = NULLPTR); virtual ~MemoryLeakWarningPlugin() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void preTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; virtual void postTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; virtual const char* FinalReport(size_t toBeDeletedLeaks = 0); void ignoreAllLeaksInTest(); void expectLeaksInTest(size_t n); void destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(bool des); MemoryLeakDetector* getMemoryLeakDetector(); static MemoryLeakWarningPlugin* getFirstPlugin(); static MemoryLeakDetector* getGlobalDetector(); static MemoryLeakFailure* getGlobalFailureReporter(); static void setGlobalDetector(MemoryLeakDetector* detector, MemoryLeakFailure* reporter); static void destroyGlobalDetector(); static void turnOffNewDeleteOverloads(); static void turnOnDefaultNotThreadSafeNewDeleteOverloads(); static void turnOnThreadSafeNewDeleteOverloads(); static bool areNewDeleteOverloaded(); static void saveAndDisableNewDeleteOverloads(); static void restoreNewDeleteOverloads(); private: MemoryLeakDetector* memLeakDetector_; bool ignoreAllWarnings_; bool destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_; size_t expectedLeaks_; size_t failureCount_; static MemoryLeakWarningPlugin* firstPlugin_; }; extern void* cpputest_malloc_location_with_leak_detection(size_t size, const char* file, size_t line); extern void* cpputest_realloc_location_with_leak_detection(void* memory, size_t size, const char* file, size_t line); extern void cpputest_free_location_with_leak_detection(void* buffer, const char* file, size_t line); #endif
null
103
cpp
cpputest
UtestMacros.h
include/CppUTest/UtestMacros.h
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 <organization> 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 <copyright holder> 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_UTestMacros_h #define D_UTestMacros_h /*! \brief Define a group of tests * * All tests in a TEST_GROUP share the same setup() * and teardown(). setup() is run before the opening * curly brace of each TEST and teardown() is * called after the closing curly brace of TEST. * */ #define TEST_GROUP_BASE(testGroup, baseclass) \ extern int externTestGroup##testGroup; \ int externTestGroup##testGroup = 0; \ struct TEST_GROUP_##CppUTestGroup##testGroup : public baseclass #define TEST_BASE(testBaseClass) \ struct testBaseClass : public Utest #define TEST_GROUP(testGroup) \ TEST_GROUP_BASE(testGroup, Utest) #define TEST_SETUP() \ virtual void setup() CPPUTEST_OVERRIDE #define TEST_TEARDOWN() \ virtual void teardown() CPPUTEST_OVERRIDE #define TEST(testGroup, testName) \ /* External declarations for strict compilers */ \ class TEST_##testGroup##_##testName##_TestShell; \ extern TEST_##testGroup##_##testName##_TestShell TEST_##testGroup##_##testName##_TestShell_instance; \ \ class TEST_##testGroup##_##testName##_Test : public TEST_GROUP_##CppUTestGroup##testGroup \ { public: TEST_##testGroup##_##testName##_Test () : TEST_GROUP_##CppUTestGroup##testGroup () {} \ void testBody() CPPUTEST_OVERRIDE; }; \ class TEST_##testGroup##_##testName##_TestShell : public UtestShell { \ virtual Utest* createTest() CPPUTEST_OVERRIDE { return new TEST_##testGroup##_##testName##_Test; } \ } TEST_##testGroup##_##testName##_TestShell_instance; \ static TestInstaller TEST_##testGroup##_##testName##_Installer(TEST_##testGroup##_##testName##_TestShell_instance, #testGroup, #testName, __FILE__,__LINE__); \ void TEST_##testGroup##_##testName##_Test::testBody() #define IGNORE_TEST(testGroup, testName)\ /* External declarations for strict compilers */ \ class IGNORE##testGroup##_##testName##_TestShell; \ extern IGNORE##testGroup##_##testName##_TestShell IGNORE##testGroup##_##testName##_TestShell_instance; \ \ class IGNORE##testGroup##_##testName##_Test : public TEST_GROUP_##CppUTestGroup##testGroup \ { public: IGNORE##testGroup##_##testName##_Test () : TEST_GROUP_##CppUTestGroup##testGroup () {} \ public: void testBody() CPPUTEST_OVERRIDE; }; \ class IGNORE##testGroup##_##testName##_TestShell : public IgnoredUtestShell { \ virtual Utest* createTest() CPPUTEST_OVERRIDE { return new IGNORE##testGroup##_##testName##_Test; } \ } IGNORE##testGroup##_##testName##_TestShell_instance; \ static TestInstaller TEST_##testGroup##testName##_Installer(IGNORE##testGroup##_##testName##_TestShell_instance, #testGroup, #testName, __FILE__,__LINE__); \ void IGNORE##testGroup##_##testName##_Test::testBody () #define IMPORT_TEST_GROUP(testGroup) \ extern int externTestGroup##testGroup;\ extern int* p##testGroup; \ int* p##testGroup = &externTestGroup##testGroup #define CPPUTEST_DEFAULT_MAIN \ /*#include <CppUTest/CommandLineTestRunner.h>*/ \ int main(int argc, char** argv) \ { \ return CommandLineTestRunner::RunAllTests(argc, argv); \ } // Different checking macros #define CHECK(condition)\ CHECK_TRUE_LOCATION(condition, "CHECK", #condition, NULLPTR, __FILE__, __LINE__) #define CHECK_TEXT(condition, text) \ CHECK_TRUE_LOCATION((bool)(condition), "CHECK", #condition, text, __FILE__, __LINE__) #define CHECK_TRUE(condition)\ CHECK_TRUE_LOCATION((bool) (condition), "CHECK_TRUE", #condition, NULLPTR, __FILE__, __LINE__) #define CHECK_TRUE_TEXT(condition, text)\ CHECK_TRUE_LOCATION(condition, "CHECK_TRUE", #condition, text, __FILE__, __LINE__) #define CHECK_FALSE(condition)\ CHECK_FALSE_LOCATION(condition, "CHECK_FALSE", #condition, NULLPTR, __FILE__, __LINE__) #define CHECK_FALSE_TEXT(condition, text)\ CHECK_FALSE_LOCATION(condition, "CHECK_FALSE", #condition, text, __FILE__, __LINE__) #define CHECK_TRUE_LOCATION(condition, checkString, conditionString, text, file, line)\ do { UtestShell::getCurrent()->assertTrue((condition), checkString, conditionString, text, file, line); } while(0) #define CHECK_FALSE_LOCATION(condition, checkString, conditionString, text, file, line)\ do { UtestShell::getCurrent()->assertTrue(!(condition), checkString, conditionString, text, file, line); } while(0) //This check needs the operator!=(), and a StringFrom(YourType) function #define CHECK_EQUAL(expected, actual)\ CHECK_EQUAL_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define CHECK_EQUAL_TEXT(expected, actual, text)\ CHECK_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define CHECK_EQUAL_LOCATION(expected, actual, text, file, line)\ do { if ((expected) != (actual)) { \ if ((actual) != (actual)) \ UtestShell::getCurrent()->print("WARNING:\n\tThe \"Actual Parameter\" parameter is evaluated multiple times resulting in different values.\n\tThus the value in the error message is probably incorrect.", file, line); \ if ((expected) != (expected)) \ UtestShell::getCurrent()->print("WARNING:\n\tThe \"Expected Parameter\" parameter is evaluated multiple times resulting in different values.\n\tThus the value in the error message is probably incorrect.", file, line); \ UtestShell::getCurrent()->assertEquals(true, StringFrom(expected).asCharString(), StringFrom(actual).asCharString(), text, file, line); \ } \ else \ { \ UtestShell::getCurrent()->assertLongsEqual((long)0, (long)0, NULLPTR, file, line); \ } } while(0) #define CHECK_EQUAL_ZERO(actual) CHECK_EQUAL(0, (actual)) #define CHECK_EQUAL_ZERO_TEXT(actual, text) CHECK_EQUAL_TEXT(0, (actual), (text)) #define CHECK_COMPARE(first, relop, second)\ CHECK_COMPARE_TEXT(first, relop, second, NULLPTR) #define CHECK_COMPARE_TEXT(first, relop, second, text)\ CHECK_COMPARE_LOCATION(first, relop, second, text, __FILE__, __LINE__) #define CHECK_COMPARE_LOCATION(first, relop, second, text, file, line)\ do {\ bool success = (first) relop (second);\ if (!success) {\ SimpleString conditionString;\ conditionString += StringFrom(first); conditionString += " ";\ conditionString += #relop; conditionString += " ";\ conditionString += StringFrom(second);\ UtestShell::getCurrent()->assertCompare(false, "CHECK_COMPARE", conditionString.asCharString(), text, __FILE__, __LINE__);\ }\ } while(0) //This check checks for char* string equality using strcmp. //This makes up for the fact that CHECK_EQUAL only compares the pointers to char*'s #define STRCMP_EQUAL(expected, actual)\ STRCMP_EQUAL_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define STRCMP_EQUAL_TEXT(expected, actual, text)\ STRCMP_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_EQUAL_LOCATION(expected, actual, text, file, line)\ do { UtestShell::getCurrent()->assertCstrEqual(expected, actual, text, file, line); } while(0) #define STRNCMP_EQUAL(expected, actual, length)\ STRNCMP_EQUAL_LOCATION(expected, actual, length, NULLPTR, __FILE__, __LINE__) #define STRNCMP_EQUAL_TEXT(expected, actual, length, text)\ STRNCMP_EQUAL_LOCATION(expected, actual, length, text, __FILE__, __LINE__) #define STRNCMP_EQUAL_LOCATION(expected, actual, length, text, file, line)\ do { UtestShell::getCurrent()->assertCstrNEqual(expected, actual, length, text, file, line); } while(0) #define STRCMP_NOCASE_EQUAL(expected, actual)\ STRCMP_NOCASE_EQUAL_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define STRCMP_NOCASE_EQUAL_TEXT(expected, actual, text)\ STRCMP_NOCASE_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_NOCASE_EQUAL_LOCATION(expected, actual, text, file, line)\ do { UtestShell::getCurrent()->assertCstrNoCaseEqual(expected, actual, text, file, line); } while(0) #define STRCMP_CONTAINS(expected, actual)\ STRCMP_CONTAINS_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define STRCMP_CONTAINS_TEXT(expected, actual, text)\ STRCMP_CONTAINS_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_CONTAINS_LOCATION(expected, actual, text, file, line)\ do { UtestShell::getCurrent()->assertCstrContains(expected, actual, text, file, line); } while(0) #define STRCMP_NOCASE_CONTAINS(expected, actual)\ STRCMP_NOCASE_CONTAINS_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define STRCMP_NOCASE_CONTAINS_TEXT(expected, actual, text)\ STRCMP_NOCASE_CONTAINS_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_NOCASE_CONTAINS_LOCATION(expected, actual, text, file, line)\ do { UtestShell::getCurrent()->assertCstrNoCaseContains(expected, actual, text, file, line); } while(0) //Check two long integers for equality #define LONGS_EQUAL(expected, actual)\ LONGS_EQUAL_LOCATION((expected), (actual), "LONGS_EQUAL(" #expected ", " #actual ") failed", __FILE__, __LINE__) #define LONGS_EQUAL_TEXT(expected, actual, text)\ LONGS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define UNSIGNED_LONGS_EQUAL(expected, actual)\ UNSIGNED_LONGS_EQUAL_LOCATION((expected), (actual), NULLPTR, __FILE__, __LINE__) #define UNSIGNED_LONGS_EQUAL_TEXT(expected, actual, text)\ UNSIGNED_LONGS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define LONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ do { UtestShell::getCurrent()->assertLongsEqual((long)(expected), (long)(actual), text, file, line); } while(0) #define UNSIGNED_LONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ do { UtestShell::getCurrent()->assertUnsignedLongsEqual((unsigned long)(expected), (unsigned long)(actual), text, file, line); } while(0) #if CPPUTEST_USE_LONG_LONG #define LONGLONGS_EQUAL(expected, actual)\ LONGLONGS_EQUAL_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define LONGLONGS_EQUAL_TEXT(expected, actual, text)\ LONGLONGS_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define UNSIGNED_LONGLONGS_EQUAL(expected, actual)\ UNSIGNED_LONGLONGS_EQUAL_LOCATION(expected, actual, NULLPTR, __FILE__, __LINE__) #define UNSIGNED_LONGLONGS_EQUAL_TEXT(expected, actual, text)\ UNSIGNED_LONGLONGS_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define LONGLONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ do { UtestShell::getCurrent()->assertLongLongsEqual((cpputest_longlong)(expected), (cpputest_longlong)(actual), text, file, line); } while(0) #define UNSIGNED_LONGLONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ do { UtestShell::getCurrent()->assertUnsignedLongLongsEqual((cpputest_ulonglong)(expected), (cpputest_ulonglong)(actual), text, file, line); } while(0) #endif // CPPUTEST_USE_LONG_LONG #define BYTES_EQUAL(expected, actual)\ LONGS_EQUAL((expected) & 0xff,(actual) & 0xff) #define BYTES_EQUAL_TEXT(expected, actual, text)\ LONGS_EQUAL_TEXT((expected) & 0xff, (actual) & 0xff, text) #define SIGNED_BYTES_EQUAL(expected, actual)\ SIGNED_BYTES_EQUAL_LOCATION(expected, actual, __FILE__, __LINE__) #define SIGNED_BYTES_EQUAL_LOCATION(expected, actual, file, line) \ do { UtestShell::getCurrent()->assertSignedBytesEqual(expected, actual, NULLPTR, file, line); } while(0) #define SIGNED_BYTES_EQUAL_TEXT(expected, actual, text)\ SIGNED_BYTES_EQUAL_TEXT_LOCATION(expected, actual, text, __FILE__, __LINE__) #define SIGNED_BYTES_EQUAL_TEXT_LOCATION(expected, actual, text, file, line) \ do { UtestShell::getCurrent()->assertSignedBytesEqual(expected, actual, text, file, line); } while(0) #define POINTERS_EQUAL(expected, actual)\ POINTERS_EQUAL_LOCATION((expected), (actual), NULLPTR, __FILE__, __LINE__) #define POINTERS_EQUAL_TEXT(expected, actual, text)\ POINTERS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define POINTERS_EQUAL_LOCATION(expected, actual, text, file, line)\ do { UtestShell::getCurrent()->assertPointersEqual((const void *)(expected), (const void *)(actual), text, file, line); } while(0) #define FUNCTIONPOINTERS_EQUAL(expected, actual)\ FUNCTIONPOINTERS_EQUAL_LOCATION((expected), (actual), NULLPTR, __FILE__, __LINE__) #define FUNCTIONPOINTERS_EQUAL_TEXT(expected, actual, text)\ FUNCTIONPOINTERS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define FUNCTIONPOINTERS_EQUAL_LOCATION(expected, actual, text, file, line)\ do { UtestShell::getCurrent()->assertFunctionPointersEqual((void (*)())(expected), (void (*)())(actual), text, file, line); } while(0) //Check two doubles for equality within a tolerance threshold #define DOUBLES_EQUAL(expected, actual, threshold)\ DOUBLES_EQUAL_LOCATION(expected, actual, threshold, NULLPTR, __FILE__, __LINE__) #define DOUBLES_EQUAL_TEXT(expected, actual, threshold, text)\ DOUBLES_EQUAL_LOCATION(expected, actual, threshold, text, __FILE__, __LINE__) #define DOUBLES_EQUAL_LOCATION(expected, actual, threshold, text, file, line)\ do { UtestShell::getCurrent()->assertDoublesEqual(expected, actual, threshold, text, file, line); } while(0) #define MEMCMP_EQUAL(expected, actual, size)\ MEMCMP_EQUAL_LOCATION(expected, actual, size, NULLPTR, __FILE__, __LINE__) #define MEMCMP_EQUAL_TEXT(expected, actual, size, text)\ MEMCMP_EQUAL_LOCATION(expected, actual, size, text, __FILE__, __LINE__) #define MEMCMP_EQUAL_LOCATION(expected, actual, size, text, file, line)\ do { UtestShell::getCurrent()->assertBinaryEqual(expected, actual, size, text, file, line); } while(0) #define BITS_EQUAL(expected, actual, mask)\ BITS_LOCATION(expected, actual, mask, NULLPTR, __FILE__, __LINE__) #define BITS_EQUAL_TEXT(expected, actual, mask, text)\ BITS_LOCATION(expected, actual, mask, text, __FILE__, __LINE__) #define BITS_LOCATION(expected, actual, mask, text, file, line)\ do { UtestShell::getCurrent()->assertBitsEqual(expected, actual, mask, sizeof(actual), text, file, line); } while(0) // NOLINT(bugprone-sizeof-expression) #define ENUMS_EQUAL_INT(expected, actual)\ ENUMS_EQUAL_TYPE(int, expected, actual) #define ENUMS_EQUAL_INT_TEXT(expected, actual, text)\ ENUMS_EQUAL_TYPE_TEXT(int, expected, actual, text) #define ENUMS_EQUAL_TYPE(underlying_type, expected, actual)\ ENUMS_EQUAL_TYPE_LOCATION(underlying_type, expected, actual, NULLPTR, __FILE__, __LINE__) #define ENUMS_EQUAL_TYPE_TEXT(underlying_type, expected, actual, text)\ ENUMS_EQUAL_TYPE_LOCATION(underlying_type, expected, actual, text, __FILE__, __LINE__) #define ENUMS_EQUAL_TYPE_LOCATION(underlying_type, expected, actual, text, file, line)\ do { underlying_type expected_underlying_value = (underlying_type)(expected); \ underlying_type actual_underlying_value = (underlying_type)(actual); \ if (expected_underlying_value != actual_underlying_value) { \ UtestShell::getCurrent()->assertEquals(true, StringFrom(expected_underlying_value).asCharString(), StringFrom(actual_underlying_value).asCharString(), text, file, line); \ } \ else \ { \ UtestShell::getCurrent()->assertLongsEqual((long)0, long(0), NULLPTR, file, line); \ } \ } while(0) //Fail if you get to this macro //The macro FAIL may already be taken, so allow FAIL_TEST too #ifndef FAIL #define FAIL(text)\ FAIL_LOCATION(text, __FILE__,__LINE__) #define FAIL_LOCATION(text, file, line)\ do { UtestShell::getCurrent()->fail(text, file, line); } while(0) #endif #define FAIL_TEST(text)\ FAIL_TEST_LOCATION(text, __FILE__,__LINE__) #define FAIL_TEST_LOCATION(text, file,line)\ do { UtestShell::getCurrent()->fail(text, file, line); } while(0) #define TEST_EXIT\ do { UtestShell::getCurrent()->exitTest(); } while(0) #define UT_PRINT_LOCATION(text, file, line) \ do { UtestShell::getCurrent()->print(text, file, line); } while(0) #define UT_PRINT(text) \ UT_PRINT_LOCATION(text, __FILE__, __LINE__) #if CPPUTEST_HAVE_EXCEPTIONS #define CHECK_THROWS(expected, expression) \ do { \ SimpleString failure_msg("expected to throw "#expected "\nbut threw nothing"); \ bool caught_expected = false; \ try { \ (expression); \ } catch(const expected &) { \ caught_expected = true; \ } catch(...) { \ failure_msg = "expected to throw " #expected "\nbut threw a different type"; \ } \ if (!caught_expected) { \ UtestShell::getCurrent()->fail(failure_msg.asCharString(), __FILE__, __LINE__); \ } \ else { \ UtestShell::getCurrent()->countCheck(); \ } \ } while(0) #endif /* CPPUTEST_HAVE_EXCEPTIONS */ #define UT_CRASH() do { UtestShell::crash(); } while(0) #define RUN_ALL_TESTS(ac, av) CommandLineTestRunner::RunAllTests(ac, av) #endif /*D_UTestMacros_h*/
null
104
cpp
cpputest
MemoryLeakDetectorNewMacros.h
include/CppUTest/MemoryLeakDetectorNewMacros.h
null
/* * This file can be used to get extra debugging information about memory leaks in your production code. * It defines a preprocessor macro for operator new. This will pass additional information to the * operator new and this will give the line/file information of the memory leaks in your code. * * You can use this by including this file to all your production code. When using gcc, you can use * the -include file to do this for you. * * Warning: Using the new macro can cause a conflict with newly declared operator news. This can be * resolved by: * 1. #undef operator new before including this file * 2. Including the files that override operator new before this file. * This can be done by creating your own NewMacros.h file that includes your operator new overrides * and THEN this file. * * STL (or StdC++ lib) also does overrides for operator new. Therefore, you'd need to include the STL * files *before* this file too. * */ #include "CppUTestConfig.h" /* Make sure that mem leak detection is on and that this is being included from a C++ file */ #if CPPUTEST_USE_MEM_LEAK_DETECTION && defined(__cplusplus) /* This #ifndef prevents <new> from being included twice and enables the file to be included anywhere */ #ifndef CPPUTEST_USE_NEW_MACROS #if CPPUTEST_USE_STD_CPP_LIB #ifdef CPPUTEST_USE_STRDUP_MACROS #if CPPUTEST_USE_STRDUP_MACROS == 1 /* * Some platforms (OSx, i.e.) will get <string.h> or <cstring> included when using <memory> header, * in order to avoid conflicts with strdup and strndup macros defined by MemoryLeakDetectorMallocMacros.h * we will undefined those macros, include the C++ headers and then reinclude MemoryLeakDetectorMallocMacros.h. * The check '#if CPPUTEST_USE_STRDUP_MACROS' will ensure we only include MemoryLeakDetectorMallocMacros.h if * it has already been includeded earlier. */ #undef strdup #undef strndup #undef CPPUTEST_USE_STRDUP_MACROS #endif #endif #include <new> #include <memory> #include <string> #endif /* Some toolkits, e.g. MFC, provide their own new overloads with signature (size_t, const char *, int). * If we don't provide them, in addition to the (size_t, const char *, size_t) version, we don't get to * know about all allocations and report freeing of unallocated blocks. Hence, provide both overloads. */ void* operator new(size_t size, const char* file, int line) UT_THROW (CPPUTEST_BAD_ALLOC); void* operator new(size_t size, const char* file, size_t line) UT_THROW (CPPUTEST_BAD_ALLOC); void* operator new[](size_t size, const char* file, int line) UT_THROW (CPPUTEST_BAD_ALLOC); void* operator new[](size_t size, const char* file, size_t line) UT_THROW (CPPUTEST_BAD_ALLOC); void* operator new(size_t size) UT_THROW(CPPUTEST_BAD_ALLOC); void* operator new[](size_t size) UT_THROW(CPPUTEST_BAD_ALLOC); void operator delete(void* mem, const char* file, int line) UT_NOTHROW; void operator delete(void* mem, const char* file, size_t line) UT_NOTHROW; void operator delete[](void* mem, const char* file, int line) UT_NOTHROW; void operator delete[](void* mem, const char* file, size_t line) UT_NOTHROW; void operator delete(void* mem) UT_NOTHROW; void operator delete[](void* mem) UT_NOTHROW; #if __cplusplus >= 201402L void operator delete (void* mem, size_t size) UT_NOTHROW; void operator delete[] (void* mem, size_t size) UT_NOTHROW; #endif #endif #ifdef __clang__ #pragma clang diagnostic push #if (__clang_major__ == 3 && __clang_minor__ >= 6) || __clang_major__ >= 4 #pragma clang diagnostic ignored "-Wkeyword-macro" #endif #endif #define new new(__FILE__, __LINE__) #ifdef __clang__ #pragma clang diagnostic pop #endif #define CPPUTEST_USE_NEW_MACROS 1 #endif #include "MemoryLeakDetectorMallocMacros.h"
null
105
cpp
cpputest
Utest.h
include/CppUTest/Utest.h
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 <organization> 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 <copyright holder> 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. */ // This file contains the Test class along with the macros which make effective // in the harness. #ifndef D_UTest_h #define D_UTest_h #include "SimpleString.h" class TestResult; class TestPlugin; class TestFailure; class TestFilter; class TestTerminator; extern bool doubles_equal(double d1, double d2, double threshold); //////////////////// Utest class UtestShell; class Utest { public: Utest(); virtual ~Utest(); virtual void run(); virtual void setup(); virtual void teardown(); virtual void testBody(); }; //////////////////// TestTerminator class TestTerminator { public: virtual void exitCurrentTest() const=0; virtual ~TestTerminator(); }; class NormalTestTerminator : public TestTerminator { public: virtual void exitCurrentTest() const CPPUTEST_OVERRIDE; virtual ~NormalTestTerminator() CPPUTEST_DESTRUCTOR_OVERRIDE; }; class TestTerminatorWithoutExceptions : public TestTerminator { public: virtual void exitCurrentTest() const CPPUTEST_OVERRIDE; virtual ~TestTerminatorWithoutExceptions() CPPUTEST_DESTRUCTOR_OVERRIDE; }; class CrashingTestTerminator : public NormalTestTerminator { public: virtual void exitCurrentTest() const CPPUTEST_OVERRIDE; virtual ~CrashingTestTerminator() CPPUTEST_DESTRUCTOR_OVERRIDE; }; class CrashingTestTerminatorWithoutExceptions : public TestTerminatorWithoutExceptions { public: virtual void exitCurrentTest() const CPPUTEST_OVERRIDE; virtual ~CrashingTestTerminatorWithoutExceptions() CPPUTEST_DESTRUCTOR_OVERRIDE; }; //////////////////// UtestShell class UtestShell { public: static UtestShell *getCurrent(); static const TestTerminator &getCurrentTestTerminator(); static const TestTerminator &getCurrentTestTerminatorWithoutExceptions(); static void setCrashOnFail(); static void restoreDefaultTestTerminator(); static void setRethrowExceptions(bool rethrowExceptions); static bool isRethrowingExceptions(); public: UtestShell(const char* groupName, const char* testName, const char* fileName, size_t lineNumber); virtual ~UtestShell(); virtual UtestShell* addTest(UtestShell* test); virtual UtestShell *getNext() const; virtual size_t countTests(); bool shouldRun(const TestFilter* groupFilters, const TestFilter* nameFilters) const; const SimpleString getName() const; const SimpleString getGroup() const; virtual SimpleString getFormattedName() const; const SimpleString getFile() const; size_t getLineNumber() const; virtual bool willRun() const; virtual bool hasFailed() const; void countCheck(); virtual void assertTrue(bool condition, const char *checkString, const char *conditionString, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertCstrEqual(const char *expected, const char *actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertCstrNEqual(const char *expected, const char *actual, size_t length, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertCstrNoCaseEqual(const char *expected, const char *actual, const char* text, const char *fileName, size_t lineNumber); virtual void assertCstrContains(const char *expected, const char *actual, const char* text, const char *fileName, size_t lineNumber); virtual void assertCstrNoCaseContains(const char *expected, const char *actual, const char* text, const char *fileName, size_t lineNumber); virtual void assertLongsEqual(long expected, long actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertUnsignedLongsEqual(unsigned long expected, unsigned long actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertLongLongsEqual(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertUnsignedLongLongsEqual(cpputest_ulonglong expected, cpputest_ulonglong actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertSignedBytesEqual(signed char expected, signed char actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertPointersEqual(const void *expected, const void *actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertFunctionPointersEqual(void (*expected)(), void (*actual)(), const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertDoublesEqual(double expected, double actual, double threshold, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertEquals(bool failed, const char* expected, const char* actual, const char* text, const char* file, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertBinaryEqual(const void *expected, const void *actual, size_t length, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertBitsEqual(unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void assertCompare(bool comparison, const char *checkString, const char *comparisonString, const char *text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void fail(const char *text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void exitTest(const TestTerminator& testTerminator = getCurrentTestTerminator()); virtual void print(const char *text, const char *fileName, size_t lineNumber); virtual void print(const SimpleString & text, const char *fileName, size_t lineNumber); virtual void printVeryVerbose(const char* text); void setFileName(const char *fileName); void setLineNumber(size_t lineNumber); void setGroupName(const char *groupName); void setTestName(const char *testName); static void crash(); static void setCrashMethod(void (*crashme)()); static void resetCrashMethod(); virtual bool isRunInSeperateProcess() const; virtual void setRunInSeperateProcess(); virtual void setRunIgnored(); virtual Utest* createTest(); virtual void destroyTest(Utest* test); virtual void runOneTest(TestPlugin* plugin, TestResult& result); virtual void runOneTestInCurrentProcess(TestPlugin *plugin, TestResult & result); virtual void failWith(const TestFailure& failure); virtual void failWith(const TestFailure& failure, const TestTerminator& terminator); virtual void addFailure(const TestFailure& failure); protected: UtestShell(); UtestShell(const char *groupName, const char *testName, const char *fileName, size_t lineNumber, UtestShell *nextTest); virtual SimpleString getMacroName() const; TestResult *getTestResult(); private: const char *group_; const char *name_; const char *file_; size_t lineNumber_; UtestShell *next_; bool isRunAsSeperateProcess_; bool hasFailed_; void setTestResult(TestResult* result); void setCurrentTest(UtestShell* test); bool match(const char* target, const TestFilter* filters) const; static UtestShell* currentTest_; static TestResult* testResult_; static const TestTerminator *currentTestTerminator_; static const TestTerminator *currentTestTerminatorWithoutExceptions_; static bool rethrowExceptions_; }; //////////////////// ExecFunctionTest class ExecFunctionTestShell; class ExecFunctionTest : public Utest { public: ExecFunctionTest(ExecFunctionTestShell* shell); void testBody() CPPUTEST_OVERRIDE; virtual void setup() CPPUTEST_OVERRIDE; virtual void teardown() CPPUTEST_OVERRIDE; private: ExecFunctionTestShell* shell_; }; //////////////////// ExecFunction class ExecFunction { public: ExecFunction(); virtual ~ExecFunction(); virtual void exec()=0; }; class ExecFunctionWithoutParameters : public ExecFunction { public: void (*testFunction_)(); ExecFunctionWithoutParameters(void(*testFunction)()); virtual ~ExecFunctionWithoutParameters() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void exec() CPPUTEST_OVERRIDE; }; //////////////////// ExecFunctionTestShell class ExecFunctionTestShell : public UtestShell { public: void (*setup_)(); void (*teardown_)(); ExecFunction* testFunction_; ExecFunctionTestShell(void(*set)() = NULLPTR, void(*tear)() = NULLPTR) : UtestShell("ExecFunction", "ExecFunction", "ExecFunction", 1), setup_(set), teardown_(tear), testFunction_(NULLPTR) { } Utest* createTest() CPPUTEST_OVERRIDE { return new ExecFunctionTest(this); } virtual ~ExecFunctionTestShell() CPPUTEST_DESTRUCTOR_OVERRIDE; }; //////////////////// CppUTestFailedException class CppUTestFailedException { public: int dummy_; }; //////////////////// IgnoredTest class IgnoredUtestShell : public UtestShell { public: IgnoredUtestShell(); virtual ~IgnoredUtestShell() CPPUTEST_DESTRUCTOR_OVERRIDE; explicit IgnoredUtestShell(const char* groupName, const char* testName, const char* fileName, size_t lineNumber); virtual bool willRun() const CPPUTEST_OVERRIDE; virtual void setRunIgnored() CPPUTEST_OVERRIDE; protected: virtual SimpleString getMacroName() const CPPUTEST_OVERRIDE; virtual void runOneTest(TestPlugin* plugin, TestResult& result) CPPUTEST_OVERRIDE; private: IgnoredUtestShell(const IgnoredUtestShell&); IgnoredUtestShell& operator=(const IgnoredUtestShell&); bool runIgnored_; }; //////////////////// UtestShellPointerArray class UtestShellPointerArray { public: UtestShellPointerArray(UtestShell* firstTest); ~UtestShellPointerArray(); void shuffle(size_t seed); void reverse(); void relinkTestsInOrder(); UtestShell* getFirstTest() const; UtestShell* get(size_t index) const; private: void swap(size_t index1, size_t index2); UtestShell** arrayOfTests_; size_t count_; }; //////////////////// TestInstaller class TestInstaller { public: explicit TestInstaller(UtestShell& shell, const char* groupName, const char* testName, const char* fileName, size_t lineNumber); virtual ~TestInstaller(); void unDo(); private: TestInstaller(const TestInstaller&); TestInstaller& operator=(const TestInstaller&); }; #endif
null
106
cpp
cpputest
TestMemoryAllocator.h
include/CppUTest/TestMemoryAllocator.h
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 <organization> 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 <copyright holder> 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_TestMemoryAllocator_h #define D_TestMemoryAllocator_h struct MemoryLeakNode; class TestMemoryAllocator; extern void setCurrentNewAllocator(TestMemoryAllocator* allocator); extern TestMemoryAllocator* getCurrentNewAllocator(); extern void setCurrentNewAllocatorToDefault(); extern TestMemoryAllocator* defaultNewAllocator(); extern void setCurrentNewArrayAllocator(TestMemoryAllocator* allocator); extern TestMemoryAllocator* getCurrentNewArrayAllocator(); extern void setCurrentNewArrayAllocatorToDefault(); extern TestMemoryAllocator* defaultNewArrayAllocator(); extern void setCurrentMallocAllocator(TestMemoryAllocator* allocator); extern TestMemoryAllocator* getCurrentMallocAllocator(); extern void setCurrentMallocAllocatorToDefault(); extern TestMemoryAllocator* defaultMallocAllocator(); class GlobalMemoryAllocatorStash { public: GlobalMemoryAllocatorStash(); void save(); void restore(); private: TestMemoryAllocator* originalMallocAllocator; TestMemoryAllocator* originalNewAllocator; TestMemoryAllocator* originalNewArrayAllocator; }; class TestMemoryAllocator { public: TestMemoryAllocator(const char* name_str = "generic", const char* alloc_name_str = "alloc", const char* free_name_str = "free"); virtual ~TestMemoryAllocator(); bool hasBeenDestroyed(); virtual char* alloc_memory(size_t size, const char* file, size_t line); virtual void free_memory(char* memory, size_t size, const char* file, size_t line); virtual const char* name() const; virtual const char* alloc_name() const; virtual const char* free_name() const; virtual bool isOfEqualType(TestMemoryAllocator* allocator); virtual char* allocMemoryLeakNode(size_t size); virtual void freeMemoryLeakNode(char* memory); virtual TestMemoryAllocator* actualAllocator(); protected: const char* name_; const char* alloc_name_; const char* free_name_; bool hasBeenDestroyed_; }; class MemoryLeakAllocator : public TestMemoryAllocator { public: MemoryLeakAllocator(TestMemoryAllocator* originalAllocator); virtual ~MemoryLeakAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual const char* name() const CPPUTEST_OVERRIDE; virtual const char* alloc_name() const CPPUTEST_OVERRIDE; virtual const char* free_name() const CPPUTEST_OVERRIDE; virtual TestMemoryAllocator* actualAllocator() CPPUTEST_OVERRIDE; private: TestMemoryAllocator* originalAllocator_; }; class CrashOnAllocationAllocator : public TestMemoryAllocator { unsigned allocationToCrashOn_; public: CrashOnAllocationAllocator(); virtual ~CrashOnAllocationAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void setNumberToCrashOn(unsigned allocationToCrashOn); virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; }; class NullUnknownAllocator: public TestMemoryAllocator { public: NullUnknownAllocator(); virtual ~NullUnknownAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; static TestMemoryAllocator* defaultAllocator(); }; class LocationToFailAllocNode; class FailableMemoryAllocator: public TestMemoryAllocator { public: FailableMemoryAllocator(const char* name_str = "failable alloc", const char* alloc_name_str = "alloc", const char* free_name_str = "free"); virtual ~FailableMemoryAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual char* allocMemoryLeakNode(size_t size) CPPUTEST_OVERRIDE; virtual void failAllocNumber(int number); virtual void failNthAllocAt(int allocationNumber, const char* file, size_t line); virtual void checkAllFailedAllocsWereDone(); virtual void clearFailedAllocs(); protected: LocationToFailAllocNode* head_; int currentAllocNumber_; }; struct MemoryAccountantAllocationNode; class MemoryAccountant { public: MemoryAccountant(); ~MemoryAccountant(); void useCacheSizes(size_t sizes[], size_t length); void clear(); void alloc(size_t size); void dealloc(size_t size); size_t totalAllocationsOfSize(size_t size) const; size_t totalDeallocationsOfSize(size_t size) const; size_t maximumAllocationAtATimeOfSize(size_t size) const; size_t totalAllocations() const; size_t totalDeallocations() const; SimpleString report() const; void setAllocator(TestMemoryAllocator* allocator); private: MemoryAccountantAllocationNode* findOrCreateNodeOfSize(size_t size); MemoryAccountantAllocationNode* findNodeOfSize(size_t size) const; MemoryAccountantAllocationNode* createNewAccountantAllocationNode(size_t size, MemoryAccountantAllocationNode* next) const; void destroyAccountantAllocationNode(MemoryAccountantAllocationNode* node) const; void createCacheSizeNodes(size_t sizes[], size_t length); MemoryAccountantAllocationNode* head_; TestMemoryAllocator* allocator_; bool useCacheSizes_; SimpleString reportNoAllocations() const; SimpleString reportTitle() const; SimpleString reportHeader() const; SimpleString reportFooter() const; SimpleString stringSize(size_t size) const; }; struct AccountingTestMemoryAllocatorMemoryNode; class AccountingTestMemoryAllocator : public TestMemoryAllocator { public: AccountingTestMemoryAllocator(MemoryAccountant& accountant, TestMemoryAllocator* originalAllocator); virtual ~AccountingTestMemoryAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual TestMemoryAllocator* actualAllocator() CPPUTEST_OVERRIDE; TestMemoryAllocator* originalAllocator(); virtual const char* alloc_name() const CPPUTEST_OVERRIDE; virtual const char* free_name() const CPPUTEST_OVERRIDE; private: void addMemoryToMemoryTrackingToKeepTrackOfSize(char* memory, size_t size); size_t removeMemoryFromTrackingAndReturnAllocatedSize(char* memory); size_t removeNextNodeAndReturnSize(AccountingTestMemoryAllocatorMemoryNode* node); size_t removeHeadAndReturnSize(); MemoryAccountant& accountant_; TestMemoryAllocator* originalAllocator_; AccountingTestMemoryAllocatorMemoryNode* head_; }; class GlobalMemoryAccountant { public: GlobalMemoryAccountant(); ~GlobalMemoryAccountant(); void useCacheSizes(size_t sizes[], size_t length); void start(); void stop(); SimpleString report(); SimpleString reportWithCacheSizes(size_t sizes[], size_t length); TestMemoryAllocator* getMallocAllocator(); TestMemoryAllocator* getNewAllocator(); TestMemoryAllocator* getNewArrayAllocator(); private: void restoreMemoryAllocators(); MemoryAccountant accountant_; AccountingTestMemoryAllocator* mallocAllocator_; AccountingTestMemoryAllocator* newAllocator_; AccountingTestMemoryAllocator* newArrayAllocator_; }; #endif
null
107
cpp
cpputest
TestFilter.h
include/CppUTest/TestFilter.h
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 <organization> 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 <copyright holder> 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 TESTFILTER_H_ #define TESTFILTER_H_ #include "SimpleString.h" class TestFilter { public: TestFilter(); TestFilter(const char* filter); TestFilter(const SimpleString& filter); TestFilter* add(TestFilter* filter); TestFilter* getNext() const; bool match(const SimpleString& name) const; void strictMatching(); void invertMatching(); bool operator==(const TestFilter& filter) const; bool operator!=(const TestFilter& filter) const; SimpleString asString() const; private: SimpleString filter_; bool strictMatching_; bool invertMatching_; TestFilter* next_; }; SimpleString StringFrom(const TestFilter& filter); #endif
null
108
cpp
cpputest
CppUTestConfig.h
include/CppUTest/CppUTestConfig.h
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 <organization> 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 <copyright holder> 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 CPPUTESTCONFIG_H_ #define CPPUTESTCONFIG_H_ #ifndef CPPUTEST_USE_OWN_CONFIGURATION // The autotools generated header uses reserved names in macros #ifdef __clang__ #pragma clang diagnostic push #if __clang_major__ >= 13 #pragma clang diagnostic ignored "-Wreserved-identifier" #endif #endif #include "CppUTestGeneratedConfig.h" #ifdef __clang__ #pragma clang diagnostic pop #endif #endif /* * This file is added for some specific CppUTest configurations that earlier were spread out into multiple files. * * The goal of this file is to stay really small and not to include other things, but mainly to remove duplication * from other files and resolve dependencies in #includes. * */ /* * Lib C dependencies that are currently still left: * * stdarg.h -> We use formatting functions and va_list requires to include stdarg.h in SimpleString * stdlib.h -> The TestHarness_c.h includes this to try to avoid conflicts in its malloc #define. This dependency can * easily be removed by not enabling the MALLOC overrides. * * Lib C++ dependencies are all under the CPPUTEST_USE_STD_CPP_LIB. * The only dependency is to <new> which has the bad_alloc struct * */ /* Do we use Standard C or not? When doing Kernel development, standard C usage is out. */ #ifndef CPPUTEST_USE_STD_C_LIB #ifdef CPPUTEST_STD_C_LIB_DISABLED #define CPPUTEST_USE_STD_C_LIB 0 #else #define CPPUTEST_USE_STD_C_LIB 1 #endif #endif /* Do we use Standard C++ or not? */ #ifndef CPPUTEST_USE_STD_CPP_LIB #ifdef CPPUTEST_STD_CPP_LIB_DISABLED #define CPPUTEST_USE_STD_CPP_LIB 0 #else #define CPPUTEST_USE_STD_CPP_LIB 1 #endif #endif /* Is memory leak detection enabled? * Controls the override of the global operator new/deleted and malloc/free. * Without this, there will be no memory leak detection in C/C++. */ #ifndef CPPUTEST_USE_MEM_LEAK_DETECTION #ifdef CPPUTEST_MEM_LEAK_DETECTION_DISABLED #define CPPUTEST_USE_MEM_LEAK_DETECTION 0 #else #define CPPUTEST_USE_MEM_LEAK_DETECTION 1 #endif #endif /* Should be the only #include here. Standard C library wrappers */ #include "StandardCLibrary.h" /* Create a CPPUTEST_NORETURN macro, which is used to flag a function as not returning. * Used for functions that always throws for instance. * * This is needed for compiling with clang, without breaking other compilers. */ #ifndef __has_attribute #define CPPUTEST_HAS_ATTRIBUTE(x) 0 #else #define CPPUTEST_HAS_ATTRIBUTE(x) __has_attribute(x) #endif #if defined (__cplusplus) && __cplusplus >= 201103L #define CPPUTEST_NORETURN [[noreturn]] #elif CPPUTEST_HAS_ATTRIBUTE(noreturn) #define CPPUTEST_NORETURN __attribute__((noreturn)) #else #define CPPUTEST_NORETURN #endif #if defined(__MINGW32__) #define CPPUTEST_CHECK_FORMAT_TYPE __MINGW_PRINTF_FORMAT #else #define CPPUTEST_CHECK_FORMAT_TYPE printf #endif #if CPPUTEST_HAS_ATTRIBUTE(format) #define CPPUTEST_CHECK_FORMAT(type, format_parameter, other_parameters) __attribute__ ((format (type, format_parameter, other_parameters))) #else #define CPPUTEST_CHECK_FORMAT(type, format_parameter, other_parameters) /* type, format_parameter, other_parameters */ #endif #if defined(__cplusplus) && __cplusplus >= 201103L #define DEFAULT_COPY_CONSTRUCTOR(classname) classname(const classname &) = default; #else #define DEFAULT_COPY_CONSTRUCTOR(classname) #endif /* * Address sanitizer is a good thing... and it causes some conflicts with the CppUTest tests * To check whether it is on or off, we create a CppUTest define here. */ #if defined(__has_feature) #if __has_feature(address_sanitizer) #define CPPUTEST_SANITIZE_ADDRESS 1 #endif #elif defined(__SANITIZE_ADDRESS__) #define CPPUTEST_SANITIZE_ADDRESS 1 #endif #ifndef CPPUTEST_SANITIZE_ADDRESS #define CPPUTEST_SANITIZE_ADDRESS 0 #endif #if CPPUTEST_SANITIZE_ADDRESS #if defined(__linux__) && defined(__clang__) && CPPUTEST_USE_STD_CPP_LIB && CPPUTEST_USE_MEM_LEAK_DETECTION #warning Compiling with Address Sanitizer with clang on linux may cause duplicate symbols for operator new. Turning off memory leak detection. Compile with -DCPPUTEST_MEM_LEAK_DETECTION_DISABLED to get rid of this warning. #endif #define CPPUTEST_DO_NOT_SANITIZE_ADDRESS __attribute__((no_sanitize_address)) #else #define CPPUTEST_DO_NOT_SANITIZE_ADDRESS #endif /* * Handling of IEEE754 (IEC559) floating point exceptions via fenv.h * Predominantly works on non-Visual C++ compilers and Visual C++ 2008 and newer */ #ifndef CPPUTEST_HAVE_FENV #if (defined(__STDC_IEC_559__) && __STDC_IEC_559__) && CPPUTEST_USE_STD_C_LIB #define CPPUTEST_HAVE_FENV 1 #else #define CPPUTEST_HAVE_FENV 0 #endif #endif #ifdef __cplusplus /* * Detection of run-time type information (RTTI) presence. Since it's a * standard language feature, assume it is enabled unless we see otherwise. */ #ifndef CPPUTEST_HAVE_RTTI #if ((__cplusplus >= 202002L) && !__cpp_rtti) || \ (defined(_MSC_VER) && !_CPPRTTI) || \ (defined(__GNUC__) && !__GXX_RTTI) || \ (defined(__ghs__) && !__RTTI) || \ (defined(__WATCOMC__) && !_CPPRTTI) #define CPPUTEST_HAVE_RTTI 0 #else #define CPPUTEST_HAVE_RTTI 1 #endif #endif /* * Detection of exception support. Since it's a standard language feature, * assume it is enabled unless we see otherwise. */ #ifndef CPPUTEST_HAVE_EXCEPTIONS #if ((__cplusplus >= 202002L) && !__cpp_exceptions) || \ (defined(_MSC_VER) && !_CPPUNWIND) || \ (defined(__GNUC__) && !__EXCEPTIONS) || \ (defined(__ghs__) && !__EXCEPTION_HANDLING) || \ (defined(__WATCOMC__) && !_CPPUNWIND) #define CPPUTEST_HAVE_EXCEPTIONS 0 #else #define CPPUTEST_HAVE_EXCEPTIONS 1 #endif #endif #if CPPUTEST_HAVE_EXCEPTIONS #if defined(__cplusplus) && __cplusplus >= 201103L #define UT_THROW(exception) #define UT_NOTHROW noexcept #else #define UT_THROW(exception) throw (exception) #define UT_NOTHROW throw() #endif #else #define UT_THROW(exception) #if defined(__clang__) || defined(__GNUC__) #if defined(__cplusplus) && __cplusplus >= 201103L #define UT_NOTHROW noexcept #else #define UT_NOTHROW throw() #endif #else #define UT_NOTHROW #endif #endif /* * Visual C++ doesn't define __cplusplus as C++11 yet (201103), however it doesn't want the throw(exception) either, but * it does want throw(). */ #ifdef _MSC_VER #undef UT_THROW #define UT_THROW(exception) #endif /* * g++-4.7 with stdc++11 enabled On MacOSX! will have a different exception specifier for operator new (and thank you!) * I assume they'll fix this in the future, but for now, we'll change that here. * (This should perhaps also be done in the configure.ac) */ #if defined(__GXX_EXPERIMENTAL_CXX0X__) && \ defined(__APPLE__) && \ defined(_GLIBCXX_THROW) #undef UT_THROW #define UT_THROW(exception) _GLIBCXX_THROW(exception) #endif #if CPPUTEST_USE_STD_CPP_LIB #define CPPUTEST_BAD_ALLOC std::bad_alloc #else class CppUTestBadAlloc {}; #define CPPUTEST_BAD_ALLOC CppUTestBadAlloc #endif #endif /* * Detection of different 64 bit environments */ #if defined(__LP64__) || defined(_LP64) || (defined(__WORDSIZE) && (__WORDSIZE == 64 )) || defined(__x86_64) || defined(_WIN64) #define CPPUTEST_64BIT #if defined(_WIN64) #define CPPUTEST_64BIT_32BIT_LONGS #endif #endif /* Handling of systems with a different byte-width (e.g. 16 bit). Since * CHAR_BIT is defined in limits.h (ANSI C), the user must provide a definition * when building without Std C library. */ #ifndef CPPUTEST_CHAR_BIT #if defined(CHAR_BIT) #define CPPUTEST_CHAR_BIT CHAR_BIT #else #error "Provide a definition for CPPUTEST_CHAR_BIT" #endif #endif /* Handling of systems with a different int-width (e.g. 16 bit). */ #if CPPUTEST_USE_STD_C_LIB && (INT_MAX == 0x7fff) #define CPPUTEST_16BIT_INTS #endif /* * Support for "long long" type. * * Not supported when CPPUTEST_LONG_LONG_DISABLED is set. * Can be overridden by using CPPUTEST_USE_LONG_LONG * * CPPUTEST_HAVE_LONG_LONG_INT is set by configure or CMake. * LLONG_MAX is set in limits.h. This is a crude attempt to detect long long support when no configure is used * */ #ifndef CPPUTEST_USE_LONG_LONG #if !defined(CPPUTEST_LONG_LONG_DISABLED) && (defined(CPPUTEST_HAVE_LONG_LONG_INT) || defined(LLONG_MAX)) #define CPPUTEST_USE_LONG_LONG 1 #else #define CPPUTEST_USE_LONG_LONG 0 #endif #endif #if CPPUTEST_USE_LONG_LONG typedef long long cpputest_longlong; typedef unsigned long long cpputest_ulonglong; #else /* Define some placeholders to disable the overloaded methods. * It's not required to have these match the size of the "real" type, but it's occasionally convenient. */ #if defined(CPPUTEST_64BIT) && !defined(CPPUTEST_64BIT_32BIT_LONGS) #define CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE 16 #else #define CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE 8 #endif #if defined(__cplusplus) extern "C" { #endif typedef struct { char dummy[CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE]; } cpputest_longlong; typedef struct { char dummy[CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE]; } cpputest_ulonglong; #if defined(__cplusplus) } /* extern "C" */ #endif #endif #ifdef __cplusplus /* Visual C++ 10.0+ (2010+) supports the override keyword, but doesn't define the C++ version as C++11 */ #if (__cplusplus >= 201103L) || (defined(_MSC_VER) && (_MSC_VER >= 1600)) #define CPPUTEST_OVERRIDE override #define NULLPTR nullptr #else #define CPPUTEST_OVERRIDE #define NULLPTR NULL #endif #endif #ifdef __cplusplus /* Visual C++ 11.0+ (2012+) supports the override keyword on destructors */ #if (__cplusplus >= 201103L) || (defined(_MSC_VER) && (_MSC_VER >= 1700)) #define CPPUTEST_DESTRUCTOR_OVERRIDE override #else #define CPPUTEST_DESTRUCTOR_OVERRIDE #endif #endif #endif
null
109
cpp
cpputest
SimpleStringInternalCache.h
include/CppUTest/SimpleStringInternalCache.h
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 <organization> 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 <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_SimpleStringInternalCache_h #define D_SimpleStringInternalCache_h #include "CppUTest/TestMemoryAllocator.h" struct SimpleStringMemoryBlock; struct SimpleStringInternalCacheNode; class SimpleStringInternalCache { public: SimpleStringInternalCache(); ~SimpleStringInternalCache(); void setAllocator(TestMemoryAllocator* allocator); char* alloc(size_t size); void dealloc(char* memory, size_t size); bool hasFreeBlocksOfSize(size_t size); void clearCache(); void clearAllIncludingCurrentlyUsedMemory(); private: void printDeallocatingUnknownMemory(char* memory); enum { amountOfInternalCacheNodes = 5}; bool isCached(size_t size); size_t getIndexForCache(size_t size); SimpleStringInternalCacheNode* getCacheNodeFromSize(size_t size); SimpleStringInternalCacheNode* createInternalCacheNodes(); void destroyInternalCacheNode(SimpleStringInternalCacheNode * node); SimpleStringMemoryBlock* createSimpleStringMemoryBlock(size_t sizeOfString, SimpleStringMemoryBlock* next); void destroySimpleStringMemoryBlock(SimpleStringMemoryBlock * block, size_t size); void destroySimpleStringMemoryBlockList(SimpleStringMemoryBlock * block, size_t size); SimpleStringMemoryBlock* reserveCachedBlockFrom(SimpleStringInternalCacheNode* node); void releaseCachedBlockFrom(char* memory, SimpleStringInternalCacheNode* node); void releaseNonCachedMemory(char* memory, size_t size); SimpleStringMemoryBlock* allocateNewCacheBlockFrom(SimpleStringInternalCacheNode* node); SimpleStringMemoryBlock* addToSimpleStringMemoryBlockList(SimpleStringMemoryBlock* newBlock, SimpleStringMemoryBlock* previousHead); TestMemoryAllocator* allocator_; SimpleStringInternalCacheNode* cache_; SimpleStringMemoryBlock* nonCachedAllocations_; bool hasWarnedAboutDeallocations; }; class SimpleStringCacheAllocator : public TestMemoryAllocator { public: SimpleStringCacheAllocator(SimpleStringInternalCache& cache, TestMemoryAllocator* previousAllocator); virtual ~SimpleStringCacheAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual const char* name() const CPPUTEST_OVERRIDE; virtual const char* alloc_name() const CPPUTEST_OVERRIDE; virtual const char* free_name() const CPPUTEST_OVERRIDE; virtual TestMemoryAllocator* actualAllocator() CPPUTEST_OVERRIDE; TestMemoryAllocator* originalAllocator(); private: SimpleStringInternalCache& cache_; TestMemoryAllocator* originalAllocator_; }; class GlobalSimpleStringCache { SimpleStringCacheAllocator* allocator_; SimpleStringInternalCache cache_; public: GlobalSimpleStringCache(); ~GlobalSimpleStringCache(); TestMemoryAllocator* getAllocator(); }; #endif
null
110
cpp
cpputest
TestHarness_c.h
include/CppUTest/TestHarness_c.h
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 <organization> 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 <copyright holder> 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. */ /****************************************************************************** * * Provides an interface for when working with pure C * *******************************************************************************/ #ifndef D_TestHarness_c_h #define D_TestHarness_c_h #include "CppUTestConfig.h" #define CHECK_EQUAL_C_BOOL(expected,actual) \ CHECK_EQUAL_C_BOOL_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_BOOL_TEXT(expected,actual,text) \ CHECK_EQUAL_C_BOOL_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_INT(expected,actual) \ CHECK_EQUAL_C_INT_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_INT_TEXT(expected,actual,text) \ CHECK_EQUAL_C_INT_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_UINT(expected,actual) \ CHECK_EQUAL_C_UINT_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_UINT_TEXT(expected,actual,text) \ CHECK_EQUAL_C_UINT_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_LONG(expected,actual) \ CHECK_EQUAL_C_LONG_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_LONG_TEXT(expected,actual,text) \ CHECK_EQUAL_C_LONG_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_ULONG(expected,actual) \ CHECK_EQUAL_C_ULONG_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_ULONG_TEXT(expected,actual,text) \ CHECK_EQUAL_C_ULONG_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_LONGLONG(expected,actual) \ CHECK_EQUAL_C_LONGLONG_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_LONGLONG_TEXT(expected,actual,text) \ CHECK_EQUAL_C_LONGLONG_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_ULONGLONG(expected,actual) \ CHECK_EQUAL_C_ULONGLONG_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_ULONGLONG_TEXT(expected,actual,text) \ CHECK_EQUAL_C_ULONGLONG_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_REAL(expected,actual,threshold) \ CHECK_EQUAL_C_REAL_LOCATION(expected,actual,threshold,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_REAL_TEXT(expected,actual,threshold,text) \ CHECK_EQUAL_C_REAL_LOCATION(expected,actual,threshold,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_CHAR(expected,actual) \ CHECK_EQUAL_C_CHAR_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_CHAR_TEXT(expected,actual,text) \ CHECK_EQUAL_C_CHAR_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_UBYTE(expected,actual) \ CHECK_EQUAL_C_UBYTE_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_UBYTE_TEXT(expected,actual,text) \ CHECK_EQUAL_C_UBYTE_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_SBYTE(expected,actual) \ CHECK_EQUAL_C_SBYTE_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_SBYTE_TEXT(expected,actual,text) \ CHECK_EQUAL_C_SBYTE_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_STRING(expected,actual) \ CHECK_EQUAL_C_STRING_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_STRING_TEXT(expected,actual,text) \ CHECK_EQUAL_C_STRING_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_POINTER(expected,actual) \ CHECK_EQUAL_C_POINTER_LOCATION(expected,actual,NULL,__FILE__,__LINE__) #define CHECK_EQUAL_C_POINTER_TEXT(expected,actual,text) \ CHECK_EQUAL_C_POINTER_LOCATION(expected,actual,text,__FILE__,__LINE__) #define CHECK_EQUAL_C_MEMCMP(expected, actual, size) \ CHECK_EQUAL_C_MEMCMP_LOCATION(expected, actual, size, NULL, __FILE__, __LINE__) #define CHECK_EQUAL_C_MEMCMP_TEXT(expected, actual, size, text) \ CHECK_EQUAL_C_MEMCMP_LOCATION(expected, actual, size, text, __FILE__, __LINE__) #define CHECK_EQUAL_C_BITS(expected, actual, mask) \ CHECK_EQUAL_C_BITS_LOCATION(expected, actual, mask, sizeof(actual), NULL, __FILE__, __LINE__) #define CHECK_EQUAL_C_BITS_TEXT(expected, actual, mask, text) \ CHECK_EQUAL_C_BITS_LOCATION(expected, actual, mask, sizeof(actual), text, __FILE__, __LINE__) #define FAIL_TEXT_C(text) \ FAIL_TEXT_C_LOCATION(text,__FILE__,__LINE__) #define FAIL_C() \ FAIL_C_LOCATION(__FILE__,__LINE__) #define CHECK_C(condition) \ CHECK_C_LOCATION(condition, #condition, NULL, __FILE__,__LINE__) #define CHECK_C_TEXT(condition, text) \ CHECK_C_LOCATION(condition, #condition, text, __FILE__, __LINE__) /****************************************************************************** * * TEST macros for in C. * *******************************************************************************/ /* For use in C file */ #define TEST_GROUP_C_SETUP(group_name) \ extern void group_##group_name##_setup_wrapper_c(void); \ void group_##group_name##_setup_wrapper_c(void) #define TEST_GROUP_C_TEARDOWN(group_name) \ extern void group_##group_name##_teardown_wrapper_c(void); \ void group_##group_name##_teardown_wrapper_c(void) #define TEST_C(group_name, test_name) \ extern void test_##group_name##_##test_name##_wrapper_c(void);\ void test_##group_name##_##test_name##_wrapper_c(void) #define IGNORE_TEST_C(group_name, test_name) \ extern void ignore_##group_name##_##test_name##_wrapper_c(void);\ void ignore_##group_name##_##test_name##_wrapper_c(void) /* For use in C++ file */ #define TEST_GROUP_C_WRAPPER(group_name) \ extern "C" void group_##group_name##_setup_wrapper_c(void); \ extern "C" void group_##group_name##_teardown_wrapper_c(void); \ TEST_GROUP(group_name) #define TEST_GROUP_C_SETUP_WRAPPER(group_name) \ void setup() CPPUTEST_OVERRIDE { \ group_##group_name##_setup_wrapper_c(); \ } #define TEST_GROUP_C_TEARDOWN_WRAPPER(group_name) \ void teardown() CPPUTEST_OVERRIDE { \ group_##group_name##_teardown_wrapper_c(); \ } #define TEST_C_WRAPPER(group_name, test_name) \ extern "C" void test_##group_name##_##test_name##_wrapper_c(); \ TEST(group_name, test_name) { \ test_##group_name##_##test_name##_wrapper_c(); \ } #define IGNORE_TEST_C_WRAPPER(group_name, test_name) \ extern "C" void ignore_##group_name##_##test_name##_wrapper_c(); \ IGNORE_TEST(group_name, test_name) { \ ignore_##group_name##_##test_name##_wrapper_c(); \ } #ifdef __cplusplus extern "C" { #endif /* CHECKS that can be used from C code */ extern void CHECK_EQUAL_C_BOOL_LOCATION(int expected, int actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_UINT_LOCATION(unsigned int expected, unsigned int actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_LONG_LOCATION(long expected, long actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_ULONG_LOCATION(unsigned long expected, unsigned long actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_LONGLONG_LOCATION(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_ULONGLONG_LOCATION(cpputest_ulonglong expected, cpputest_ulonglong actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_UBYTE_LOCATION(unsigned char expected, unsigned char actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_SBYTE_LOCATION(signed char expected, signed char actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_POINTER_LOCATION(const void* expected, const void* actual, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_MEMCMP_LOCATION(const void* expected, const void* actual, size_t size, const char* text, const char* fileName, size_t lineNumber); extern void CHECK_EQUAL_C_BITS_LOCATION(unsigned int expected, unsigned int actual, unsigned int mask, size_t size, const char* text, const char* fileName, size_t lineNumber); extern void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, size_t lineNumber); extern void FAIL_C_LOCATION(const char* fileName, size_t lineNumber); extern void CHECK_C_LOCATION(int condition, const char* conditionString, const char* text, const char* fileName, size_t lineNumber); extern void* cpputest_malloc(size_t size); extern char* cpputest_strdup(const char* str); extern char* cpputest_strndup(const char* str, size_t n); extern void* cpputest_calloc(size_t num, size_t size); extern void* cpputest_realloc(void* ptr, size_t size); extern void cpputest_free(void* buffer); extern void* cpputest_malloc_location(size_t size, const char* file, size_t line); extern char* cpputest_strdup_location(const char* str, const char* file, size_t line); extern char* cpputest_strndup_location(const char* str, size_t n, const char* file, size_t line); extern void* cpputest_calloc_location(size_t num, size_t size, const char* file, size_t line); extern void* cpputest_realloc_location(void* memory, size_t size, const char* file, size_t line); extern void cpputest_free_location(void* buffer, const char* file, size_t line); void cpputest_malloc_set_out_of_memory(void); void cpputest_malloc_set_not_out_of_memory(void); void cpputest_malloc_set_out_of_memory_countdown(int); void cpputest_malloc_count_reset(void); int cpputest_malloc_get_count(void); #ifdef __cplusplus } #endif /* * Small additional macro for unused arguments. This is common when stubbing, but in C you cannot remove the * name of the parameter (as in C++). */ #ifndef PUNUSED #if defined(__GNUC__) || defined(__clang__) # define PUNUSED(x) PUNUSED_ ##x __attribute__((unused)) #else # define PUNUSED(x) x #endif #endif #endif
null
111
cpp
cpputest
TestOutput.h
include/CppUTest/TestOutput.h
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 <organization> 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 <copyright holder> 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_TestOutput_h #define D_TestOutput_h /////////////////////////////////////////////////////////////////////////////// // // This is a minimal printer interface. // We kept streams out to keep footprint small, and so the test // harness could be used with less capable compilers so more // platforms could use this test harness // /////////////////////////////////////////////////////////////////////////////// #include "SimpleString.h" class UtestShell; class TestFailure; class TestResult; class TestOutput { public: enum WorkingEnvironment {visualStudio, eclipse, detectEnvironment}; enum VerbosityLevel {level_quiet, level_verbose, level_veryVerbose}; explicit TestOutput(); virtual ~TestOutput(); virtual void printTestsStarted(); virtual void printTestsEnded(const TestResult& result); virtual void printCurrentTestStarted(const UtestShell& test); virtual void printCurrentTestEnded(const TestResult& res); virtual void printCurrentGroupStarted(const UtestShell& test); virtual void printCurrentGroupEnded(const TestResult& res); virtual void verbose(VerbosityLevel level); virtual void color(); virtual void printBuffer(const char*)=0; virtual void print(const char*); virtual void print(long); virtual void print(size_t); virtual void printDouble(double); virtual void printFailure(const TestFailure& failure); virtual void printTestRun(size_t number, size_t total); virtual void setProgressIndicator(const char*); virtual void printVeryVerbose(const char*); virtual void flush()=0; static void setWorkingEnvironment(WorkingEnvironment workEnvironment); static WorkingEnvironment getWorkingEnvironment(); protected: virtual void printEclipseErrorInFileOnLine(SimpleString file, size_t lineNumber); virtual void printVisualStudioErrorInFileOnLine(SimpleString file, size_t lineNumber); virtual void printProgressIndicator(); void printFileAndLineForTestAndFailure(const TestFailure& failure); void printFileAndLineForFailure(const TestFailure& failure); void printFailureInTest(SimpleString testName); void printFailureMessage(SimpleString reason); void printErrorInFileOnLineFormattedForWorkingEnvironment(SimpleString testFile, size_t lineNumber); TestOutput(const TestOutput&); TestOutput& operator=(const TestOutput&); int dotCount_; VerbosityLevel verbose_; bool color_; const char* progressIndication_; static WorkingEnvironment workingEnvironment_; }; TestOutput& operator<<(TestOutput&, const char*); TestOutput& operator<<(TestOutput&, long); /////////////////////////////////////////////////////////////////////////////// // // ConsoleTestOutput.h // // Printf Based Solution // /////////////////////////////////////////////////////////////////////////////// class ConsoleTestOutput: public TestOutput { public: explicit ConsoleTestOutput() { } virtual ~ConsoleTestOutput() CPPUTEST_DESTRUCTOR_OVERRIDE { } virtual void printBuffer(const char* s) CPPUTEST_OVERRIDE; virtual void flush() CPPUTEST_OVERRIDE; private: ConsoleTestOutput(const ConsoleTestOutput&); ConsoleTestOutput& operator=(const ConsoleTestOutput&); }; /////////////////////////////////////////////////////////////////////////////// // // StringBufferTestOutput.h // // TestOutput for test purposes // /////////////////////////////////////////////////////////////////////////////// class StringBufferTestOutput: public TestOutput { public: explicit StringBufferTestOutput() { } virtual ~StringBufferTestOutput() CPPUTEST_DESTRUCTOR_OVERRIDE; void printBuffer(const char* s) CPPUTEST_OVERRIDE { output += s; } void flush() CPPUTEST_OVERRIDE { output = ""; } const SimpleString& getOutput() { return output; } protected: SimpleString output; private: StringBufferTestOutput(const StringBufferTestOutput&); StringBufferTestOutput& operator=(const StringBufferTestOutput&); }; class CompositeTestOutput : public TestOutput { public: virtual void setOutputOne(TestOutput* output); virtual void setOutputTwo(TestOutput* output); CompositeTestOutput(); virtual ~CompositeTestOutput() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void printTestsStarted() CPPUTEST_OVERRIDE; virtual void printTestsEnded(const TestResult& result) CPPUTEST_OVERRIDE; virtual void printCurrentTestStarted(const UtestShell& test) CPPUTEST_OVERRIDE; virtual void printCurrentTestEnded(const TestResult& res) CPPUTEST_OVERRIDE; virtual void printCurrentGroupStarted(const UtestShell& test) CPPUTEST_OVERRIDE; virtual void printCurrentGroupEnded(const TestResult& res) CPPUTEST_OVERRIDE; virtual void verbose(VerbosityLevel level) CPPUTEST_OVERRIDE; virtual void color() CPPUTEST_OVERRIDE; virtual void printBuffer(const char*) CPPUTEST_OVERRIDE; virtual void print(const char*) CPPUTEST_OVERRIDE; virtual void print(long) CPPUTEST_OVERRIDE; virtual void print(size_t) CPPUTEST_OVERRIDE; virtual void printDouble(double) CPPUTEST_OVERRIDE; virtual void printFailure(const TestFailure& failure) CPPUTEST_OVERRIDE; virtual void setProgressIndicator(const char*) CPPUTEST_OVERRIDE; virtual void printVeryVerbose(const char*) CPPUTEST_OVERRIDE; virtual void flush() CPPUTEST_OVERRIDE; protected: CompositeTestOutput(const TestOutput&); CompositeTestOutput& operator=(const TestOutput&); private: TestOutput* outputOne_; TestOutput* outputTwo_; }; #endif
null
112
cpp
cpputest
TestRegistry.h
include/CppUTest/TestRegistry.h
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 <organization> 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 <copyright holder> 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. */ /////////////////////////////////////////////////////////////////////////////// // // TestRegistry is a collection of tests that can be run // #ifndef D_TestRegistry_h #define D_TestRegistry_h #include "StandardCLibrary.h" #include "SimpleString.h" #include "TestFilter.h" class UtestShell; class TestResult; class TestPlugin; class TestRegistry { public: TestRegistry(); virtual ~TestRegistry(); virtual void addTest(UtestShell *test); virtual void unDoLastAddTest(); virtual size_t countTests(); virtual void runAllTests(TestResult& result); virtual void shuffleTests(size_t seed); virtual void reverseTests(); virtual void listTestGroupNames(TestResult& result); virtual void listTestGroupAndCaseNames(TestResult& result); virtual void listTestLocations(TestResult& result); virtual void setNameFilters(const TestFilter* filters); virtual void setGroupFilters(const TestFilter* filters); virtual void installPlugin(TestPlugin* plugin); virtual void resetPlugins(); virtual TestPlugin* getFirstPlugin(); virtual TestPlugin* getPluginByName(const SimpleString& name); virtual void removePluginByName(const SimpleString& name); virtual int countPlugins(); virtual UtestShell* getFirstTest(); virtual UtestShell* getTestWithNext(UtestShell* test); virtual UtestShell* findTestWithName(const SimpleString& name); virtual UtestShell* findTestWithGroup(const SimpleString& name); static TestRegistry* getCurrentRegistry(); virtual void setCurrentRegistry(TestRegistry* registry); virtual void setRunTestsInSeperateProcess(); int getCurrentRepetition(); void setRunIgnored(); private: bool testShouldRun(UtestShell* test, TestResult& result); bool endOfGroup(UtestShell* test); UtestShell * tests_; const TestFilter* nameFilters_; const TestFilter* groupFilters_; TestPlugin* firstPlugin_; static TestRegistry* currentRegistry_; bool runInSeperateProcess_; int currentRepetition_; bool runIgnored_; }; #endif
null
113
cpp
cpputest
TeamCityTestOutput.h
include/CppUTest/TeamCityTestOutput.h
null
#ifndef D_TeamCityTestOutput_h #define D_TeamCityTestOutput_h #include "TestOutput.h" #include "SimpleString.h" class TeamCityTestOutput: public ConsoleTestOutput { public: TeamCityTestOutput(void); virtual ~TeamCityTestOutput(void) CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void printCurrentTestStarted(const UtestShell& test) CPPUTEST_OVERRIDE; virtual void printCurrentTestEnded(const TestResult& res) CPPUTEST_OVERRIDE; virtual void printCurrentGroupStarted(const UtestShell& test) CPPUTEST_OVERRIDE; virtual void printCurrentGroupEnded(const TestResult& res) CPPUTEST_OVERRIDE; virtual void printFailure(const TestFailure& failure) CPPUTEST_OVERRIDE; protected: private: void printEscaped(const char* s); const UtestShell *currtest_; SimpleString currGroup_; }; #endif
null
114
cpp
cpputest
SimpleString.h
include/CppUTest/SimpleString.h
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 <organization> 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 <copyright holder> 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. */ /////////////////////////////////////////////////////////////////////////////// // // SIMPLESTRING.H // // One of the design goals of CppUnitLite is to compilation with very old C++ // compilers. For that reason, the simple string class that provides // only the operations needed in CppUnitLite. // /////////////////////////////////////////////////////////////////////////////// #ifndef D_SimpleString_h #define D_SimpleString_h #include "StandardCLibrary.h" class SimpleStringCollection; class TestMemoryAllocator; class SimpleString { friend bool operator==(const SimpleString& left, const SimpleString& right); friend bool operator!=(const SimpleString& left, const SimpleString& right); public: SimpleString(const char *value = ""); SimpleString(const char *value, size_t repeatCount); SimpleString(const SimpleString& other); ~SimpleString(); SimpleString& operator=(const SimpleString& other); SimpleString operator+(const SimpleString&) const; SimpleString& operator+=(const SimpleString&); SimpleString& operator+=(const char*); static const size_t npos = (size_t) -1; char at(size_t pos) const; size_t find(char ch) const; size_t findFrom(size_t starting_position, char ch) const; bool contains(const SimpleString& other) const; bool containsNoCase(const SimpleString& other) const; bool startsWith(const SimpleString& other) const; bool endsWith(const SimpleString& other) const; void split(const SimpleString& split, SimpleStringCollection& outCollection) const; bool equalsNoCase(const SimpleString& str) const; size_t count(const SimpleString& str) const; void replace(char to, char with); void replace(const char* to, const char* with); SimpleString lowerCase() const; SimpleString subString(size_t beginPos) const; SimpleString subString(size_t beginPos, size_t amount) const; SimpleString subStringFromTill(char startChar, char lastExcludedChar) const; void copyToBuffer(char* buffer, size_t bufferSize) const; SimpleString printable() const; const char *asCharString() const; size_t size() const; bool isEmpty() const; static void padStringsToSameLength(SimpleString& str1, SimpleString& str2, char ch); static TestMemoryAllocator* getStringAllocator(); static void setStringAllocator(TestMemoryAllocator* allocator); static int AtoI(const char*str); static unsigned AtoU(const char*str); static int StrCmp(const char* s1, const char* s2); static size_t StrLen(const char*); static int StrNCmp(const char* s1, const char* s2, size_t n); static char* StrNCpy(char* s1, const char* s2, size_t n); static const char* StrStr(const char* s1, const char* s2); static char ToLower(char ch); static int MemCmp(const void* s1, const void *s2, size_t n); static char* allocStringBuffer(size_t size, const char* file, size_t line); static void deallocStringBuffer(char* str, size_t size, const char* file, size_t line); private: const char* getBuffer() const; void deallocateInternalBuffer(); void setInternalBufferAsEmptyString(); void setInternalBufferToNewBuffer(size_t bufferSize); void setInternalBufferTo(char* buffer, size_t bufferSize); void copyBufferToNewInternalBuffer(const char* otherBuffer); void copyBufferToNewInternalBuffer(const char* otherBuffer, size_t bufferSize); void copyBufferToNewInternalBuffer(const SimpleString& otherBuffer); char *buffer_; size_t bufferSize_; static TestMemoryAllocator* stringAllocator_; char* getEmptyString() const; static char* copyToNewBuffer(const char* bufferToCopy, size_t bufferSize); static bool isDigit(char ch); static bool isSpace(char ch); static bool isUpper(char ch); static bool isControl(char ch); static bool isControlWithShortEscapeSequence(char ch); size_t getPrintableSize() const; }; class SimpleStringCollection { public: SimpleStringCollection(); ~SimpleStringCollection(); void allocate(size_t size); size_t size() const; SimpleString& operator[](size_t index); private: SimpleString* collection_; SimpleString empty_; size_t size_; void operator =(SimpleStringCollection&); SimpleStringCollection(SimpleStringCollection&); }; class GlobalSimpleStringAllocatorStash { public: GlobalSimpleStringAllocatorStash(); void save(); void restore(); private: TestMemoryAllocator* originalAllocator_; }; class MemoryAccountant; class AccountingTestMemoryAllocator; class GlobalSimpleStringMemoryAccountant { public: GlobalSimpleStringMemoryAccountant(); ~GlobalSimpleStringMemoryAccountant(); void useCacheSizes(size_t cacheSizes[], size_t length); void start(); void stop(); SimpleString report(); AccountingTestMemoryAllocator* getAllocator(); private: void restoreAllocator(); AccountingTestMemoryAllocator* allocator_; MemoryAccountant* accountant_; }; SimpleString StringFrom(bool value); SimpleString StringFrom(const void* value); SimpleString StringFrom(void (*value)()); SimpleString StringFrom(char value); SimpleString StringFrom(const char *value); SimpleString StringFromOrNull(const char * value); SimpleString StringFrom(int value); SimpleString StringFrom(unsigned int value); SimpleString StringFrom(long value); SimpleString StringFrom(unsigned long value); SimpleString StringFrom(cpputest_longlong value); SimpleString StringFrom(cpputest_ulonglong value); SimpleString HexStringFrom(unsigned int value); SimpleString HexStringFrom(int value); SimpleString HexStringFrom(signed char value); SimpleString HexStringFrom(long value); SimpleString HexStringFrom(unsigned long value); SimpleString HexStringFrom(cpputest_longlong value); SimpleString HexStringFrom(cpputest_ulonglong value); SimpleString HexStringFrom(const void* value); SimpleString HexStringFrom(void (*value)()); SimpleString StringFrom(double value, int precision = 6); SimpleString StringFrom(const SimpleString& other); SimpleString StringFromFormat(const char* format, ...) CPPUTEST_CHECK_FORMAT(CPPUTEST_CHECK_FORMAT_TYPE, 1, 2); SimpleString VStringFromFormat(const char* format, va_list args); SimpleString StringFromBinary(const unsigned char* value, size_t size); SimpleString StringFromBinaryOrNull(const unsigned char* value, size_t size); SimpleString StringFromBinaryWithSize(const unsigned char* value, size_t size); SimpleString StringFromBinaryWithSizeOrNull(const unsigned char* value, size_t size); SimpleString StringFromMaskedBits(unsigned long value, unsigned long mask, size_t byteCount); SimpleString StringFromOrdinalNumber(unsigned int number); SimpleString BracketsFormattedHexStringFrom(int value); SimpleString BracketsFormattedHexStringFrom(unsigned int value); SimpleString BracketsFormattedHexStringFrom(long value); SimpleString BracketsFormattedHexStringFrom(unsigned long value); SimpleString BracketsFormattedHexStringFrom(cpputest_longlong value); SimpleString BracketsFormattedHexStringFrom(cpputest_ulonglong value); SimpleString BracketsFormattedHexStringFrom(signed char value); SimpleString BracketsFormattedHexString(SimpleString hexString); SimpleString PrintableStringFromOrNull(const char * expected); /* * ARM compiler has only partial support for C++11. * Specifically nullptr_t is not officially supported */ #if __cplusplus > 199711L && !defined __arm__ && CPPUTEST_USE_STD_CPP_LIB SimpleString StringFrom(const std::nullptr_t value); #endif #if CPPUTEST_USE_STD_CPP_LIB SimpleString StringFrom(const std::string& other); #endif #endif
null
115
cpp
cpputest
MemoryLeakDetector.h
include/CppUTest/MemoryLeakDetector.h
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 <organization> 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 <copyright holder> 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_MemoryLeakDetector_h #define D_MemoryLeakDetector_h enum MemLeakPeriod { mem_leak_period_all, mem_leak_period_disabled, mem_leak_period_enabled, mem_leak_period_checking }; class TestMemoryAllocator; class SimpleMutex; class MemoryLeakFailure { public: virtual ~MemoryLeakFailure() { } virtual void fail(char* fail_string)=0; }; struct SimpleStringBuffer { enum { SIMPLE_STRING_BUFFER_LEN = 4096 }; SimpleStringBuffer(); void clear(); void add(const char* format, ...) CPPUTEST_CHECK_FORMAT(CPPUTEST_CHECK_FORMAT_TYPE, 2, 3); void addMemoryDump(const void* memory, size_t memorySize); char* toString(); void setWriteLimit(size_t write_limit); void resetWriteLimit(); bool reachedItsCapacity(); private: char buffer_[SIMPLE_STRING_BUFFER_LEN]; size_t positions_filled_; size_t write_limit_; }; struct MemoryLeakDetectorNode; class MemoryLeakOutputStringBuffer { public: MemoryLeakOutputStringBuffer(); void clear(); void startMemoryLeakReporting(); void stopMemoryLeakReporting(); void reportMemoryLeak(MemoryLeakDetectorNode* leak); void reportDeallocateNonAllocatedMemoryFailure(const char* freeFile, size_t freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); void reportMemoryCorruptionFailure(MemoryLeakDetectorNode* node, const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); void reportAllocationDeallocationMismatchFailure(MemoryLeakDetectorNode* node, const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); char* toString(); private: void addAllocationLocation(const char* allocationFile, size_t allocationLineNumber, size_t allocationSize, TestMemoryAllocator* allocator); void addDeallocationLocation(const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* allocator); void addMemoryLeakHeader(); void addMemoryLeakFooter(size_t totalAmountOfLeaks); void addWarningForUsingMalloc(); void addNoMemoryLeaksMessage(); void addErrorMessageForTooMuchLeaks(); private: size_t total_leaks_; bool giveWarningOnUsingMalloc_; void reportFailure(const char* message, const char* allocFile, size_t allocLine, size_t allocSize, TestMemoryAllocator* allocAllocator, const char* freeFile, size_t freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); SimpleStringBuffer outputBuffer_; }; struct MemoryLeakDetectorNode { MemoryLeakDetectorNode() : size_(0), number_(0), memory_(NULLPTR), file_(NULLPTR), line_(0), allocator_(NULLPTR), period_(mem_leak_period_enabled), allocation_stage_(0), next_(NULLPTR) { } void init(char* memory, unsigned number, size_t size, TestMemoryAllocator* allocator, MemLeakPeriod period, unsigned char allocation_stage, const char* file, size_t line); size_t size_; unsigned number_; char* memory_; const char* file_; size_t line_; TestMemoryAllocator* allocator_; MemLeakPeriod period_; unsigned char allocation_stage_; private: friend struct MemoryLeakDetectorList; MemoryLeakDetectorNode* next_; }; struct MemoryLeakDetectorList { MemoryLeakDetectorList() : head_(NULLPTR) {} void addNewNode(MemoryLeakDetectorNode* node); MemoryLeakDetectorNode* retrieveNode(char* memory); MemoryLeakDetectorNode* removeNode(char* memory); MemoryLeakDetectorNode* getFirstLeak(MemLeakPeriod period); MemoryLeakDetectorNode* getFirstLeakForAllocationStage(unsigned char allocation_stage); MemoryLeakDetectorNode* getNextLeak(MemoryLeakDetectorNode* node, MemLeakPeriod period); MemoryLeakDetectorNode* getNextLeakForAllocationStage(MemoryLeakDetectorNode* node, unsigned char allocation_stage); MemoryLeakDetectorNode* getLeakFrom(MemoryLeakDetectorNode* node, MemLeakPeriod period); MemoryLeakDetectorNode* getLeakForAllocationStageFrom(MemoryLeakDetectorNode* node, unsigned char allocation_stage); size_t getTotalLeaks(MemLeakPeriod period); void clearAllAccounting(MemLeakPeriod period); bool isInPeriod(MemoryLeakDetectorNode* node, MemLeakPeriod period); bool isInAllocationStage(MemoryLeakDetectorNode* node, unsigned char allocation_stage); private: MemoryLeakDetectorNode* head_; }; struct MemoryLeakDetectorTable { void clearAllAccounting(MemLeakPeriod period); void addNewNode(MemoryLeakDetectorNode* node); MemoryLeakDetectorNode* retrieveNode(char* memory); MemoryLeakDetectorNode* removeNode(char* memory); size_t getTotalLeaks(MemLeakPeriod period); MemoryLeakDetectorNode* getFirstLeak(MemLeakPeriod period); MemoryLeakDetectorNode* getFirstLeakForAllocationStage(unsigned char allocation_stage); MemoryLeakDetectorNode* getNextLeak(MemoryLeakDetectorNode* leak, MemLeakPeriod period); MemoryLeakDetectorNode* getNextLeakForAllocationStage(MemoryLeakDetectorNode* leak, unsigned char allocation_stage); private: unsigned long hash(char* memory); enum { hash_prime = MEMORY_LEAK_HASH_TABLE_SIZE }; MemoryLeakDetectorList table_[hash_prime]; }; class MemoryLeakDetector { public: MemoryLeakDetector(MemoryLeakFailure* reporter); virtual ~MemoryLeakDetector(); void enable(); void disable(); void disableAllocationTypeChecking(); void enableAllocationTypeChecking(); void startChecking(); void stopChecking(); unsigned char getCurrentAllocationStage() const; void increaseAllocationStage(); void decreaseAllocationStage(); const char* report(MemLeakPeriod period); void markCheckingPeriodLeaksAsNonCheckingPeriod(); size_t totalMemoryLeaks(MemLeakPeriod period); void clearAllAccounting(MemLeakPeriod period); char* allocMemory(TestMemoryAllocator* allocator, size_t size, bool allocatNodesSeperately = false); char* allocMemory(TestMemoryAllocator* allocator, size_t size, const char* file, size_t line, bool allocatNodesSeperately = false); void deallocMemory(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately = false); void deallocMemory(TestMemoryAllocator* allocator, void* memory, const char* file, size_t line, bool allocatNodesSeperately = false); void deallocAllMemoryInCurrentAllocationStage(); char* reallocMemory(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, size_t line, bool allocatNodesSeperately = false); void invalidateMemory(char* memory); void removeMemoryLeakInformationWithoutCheckingOrDeallocatingTheMemoryButDeallocatingTheAccountInformation(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately); enum { #ifdef CPPUTEST_DISABLE_MEM_CORRUPTION_CHECK memory_corruption_buffer_size = 0 #else memory_corruption_buffer_size = 3 #endif }; unsigned getCurrentAllocationNumber(); SimpleMutex* getMutex(void); private: MemoryLeakFailure* reporter_; MemLeakPeriod current_period_; MemoryLeakOutputStringBuffer outputBuffer_; MemoryLeakDetectorTable memoryTable_; bool doAllocationTypeChecking_; unsigned allocationSequenceNumber_; unsigned char current_allocation_stage_; SimpleMutex* mutex_; char* allocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, size_t size, const char* file, size_t line, bool allocatNodesSeperately); char* reallocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, size_t line, bool allocatNodesSeperately); MemoryLeakDetectorNode* createMemoryLeakAccountingInformation(TestMemoryAllocator* allocator, size_t size, char* memory, bool allocatNodesSeperately); bool validMemoryCorruptionInformation(char* memory); bool matchingAllocation(TestMemoryAllocator *alloc_allocator, TestMemoryAllocator *free_allocator); void storeLeakInformation(MemoryLeakDetectorNode * node, char *new_memory, size_t size, TestMemoryAllocator *allocator, const char *file, size_t line); void ConstructMemoryLeakReport(MemLeakPeriod period); size_t sizeOfMemoryWithCorruptionInfo(size_t size); MemoryLeakDetectorNode* getNodeFromMemoryPointer(char* memory, size_t size); char* reallocateMemoryAndLeakInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, size_t line, bool allocatNodesSeperately); void addMemoryCorruptionInformation(char* memory); void checkForCorruption(MemoryLeakDetectorNode* node, const char* file, size_t line, TestMemoryAllocator* allocator, bool allocateNodesSeperately); }; #endif
null
116
cpp
cpputest
CppUTestGeneratedConfig.h
include/CppUTest/CppUTestGeneratedConfig.h
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 <organization> 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 <copyright holder> 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. */ /* * This file is confusing, sorry for that :) Please never edit this file. * * It serves 3 purposes * * 1) When you installed CppUTest on your system (make install), then this file should be overwritten by one that * actually contains some configuration of your system. Mostly info such as availability of types, headers, etc. * 2) When you build CppUTest using autotools, this file will be included and it will include the generated file. * That should be the same file as will be installed if you run make install * 3) When you use CppUTest on another platform that doesn't require configuration, then this file does nothing and * should be harmless. * * If you have done make install and you still found this text, then please report a bug :) * */ #ifdef HAVE_CONFIG_H #include "generated/CppUTestGeneratedConfig.h" #endif
null
117
cpp
cpputest
GTestConvertor.h
include/CppUTestExt/GTestConvertor.h
null
/* * Copyright (c) 2011, 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 <organization> 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 <copyright holder> 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 GTESTCONVERTOR_H_ #define GTESTCONVERTOR_H_ #include "CppUTest/Utest.h" #ifdef GTEST_H_ #error "Please include this file before you include any other GTest files" #endif /* * Usage: * * This file must only be included in the main. The whole implementation is inline so that this can * be compiled on usage and not on CppUTest compile-time. This avoids a hard dependency with CppUTest * and with GTest * * Add the following lines to your main: * * GTestConvertor convertor; * convertor.addAllGTestToTestRegistry(); * * */ class GTestResultReporter; class GTestFlagsThatAllocateMemory; namespace testing { class TestInfo; class TestCase; class Test; } class GTestShell : public UtestShell { ::testing::TestInfo* testinfo_; GTestShell* next_; GTestFlagsThatAllocateMemory* flags_; public: GTestShell(::testing::TestInfo* testinfo, GTestShell* next, GTestFlagsThatAllocateMemory* flags); virtual Utest* createTest() CPPUTEST_OVERRIDE; GTestShell* nextGTest() { return next_; } }; /* Enormous hack! * * This sucks enormously. We need to do two things in GTest that seem to not be possible without * this hack. Hopefully there is *another way*. * * We need to access the factory in the TestInfo in order to be able to create tests. The factory * is private and there seems to be no way to access it... * * We need to be able to call the Test SetUp and TearDown methods, but they are protected for * some reason. We can't subclass either as the tests are created with the TEST macro. * * If anyone knows how to get the above things done *without* these ugly #defines, let me know! * */ #define private public #define protected public #include "CppUTestExt/GTest.h" #include "CppUTestExt/GMock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest-death-test.h" /* * We really need some of its internals as they don't have a public interface. * */ #define GTEST_IMPLEMENTATION_ 1 #include "../src/gtest-internal-inl.h" #include "CppUTest/TestRegistry.h" #include "CppUTest/TestFailure.h" #include "CppUTest/TestResult.h" #ifdef GTEST_VERSION_GTEST_1_7 #define GTEST_STRING std::string #define GTEST_NO_STRING_VALUE "" #else #define GTEST_STRING ::testing::internal::String #define GTEST_NO_STRING_VALUE NULL #endif /* Store some of the flags as we'll need to reset them each test to avoid leaking memory */ class GTestFlagsThatAllocateMemory { public: void storeValuesOfGTestFlags() { GTestFlagcolor = ::testing::GTEST_FLAG(color); GTestFlagfilter = ::testing::GTEST_FLAG(filter); GTestFlagoutput = ::testing::GTEST_FLAG(output); GTestFlagdeath_test_style = ::testing::GTEST_FLAG(death_test_style); GTestFlaginternal_run_death_test = ::testing::internal::GTEST_FLAG(internal_run_death_test); #ifndef GTEST_VERSION_GTEST_1_5 GTestFlagstream_result_to = ::testing::GTEST_FLAG(stream_result_to); #endif } void resetValuesOfGTestFlags() { ::testing::GTEST_FLAG(color) = GTestFlagcolor; ::testing::GTEST_FLAG(filter) = GTestFlagfilter; ::testing::GTEST_FLAG(output) = GTestFlagoutput; ::testing::GTEST_FLAG(death_test_style) = GTestFlagdeath_test_style; ::testing::internal::GTEST_FLAG(internal_run_death_test) = GTestFlaginternal_run_death_test; #ifndef GTEST_VERSION_GTEST_1_5 ::testing::GTEST_FLAG(stream_result_to) = GTestFlagstream_result_to; #endif } void setGTestFlagValuesToNULLToAvoidMemoryLeaks() { #ifndef GTEST_VERSION_GTEST_1_7 ::testing::GTEST_FLAG(color) = GTEST_NO_STRING_VALUE; ::testing::GTEST_FLAG(filter) = GTEST_NO_STRING_VALUE; ::testing::GTEST_FLAG(output) = GTEST_NO_STRING_VALUE; ::testing::GTEST_FLAG(death_test_style) = GTEST_NO_STRING_VALUE; ::testing::internal::GTEST_FLAG(internal_run_death_test) = GTEST_NO_STRING_VALUE; #ifndef GTEST_VERSION_GTEST_1_5 ::testing::GTEST_FLAG(stream_result_to) = GTEST_NO_STRING_VALUE; #endif #endif } private: GTEST_STRING GTestFlagcolor; GTEST_STRING GTestFlagfilter; GTEST_STRING GTestFlagoutput; GTEST_STRING GTestFlagdeath_test_style; GTEST_STRING GTestFlaginternal_run_death_test; #ifndef GTEST_VERSION_GTEST_1_5 GTEST_STRING GTestFlagstream_result_to; #endif }; class GTestConvertor { public: GTestConvertor(bool shouldSimulateFailureAtCreationToAllocateThreadLocalData = true); virtual ~GTestConvertor(); virtual void addAllGTestToTestRegistry(); protected: virtual void simulateGTestFailureToPreAllocateAllTheThreadLocalData(); virtual void addNewTestCaseForTestInfo(::testing::TestInfo* testinfo); virtual void addAllTestsFromTestCaseToTestRegistry(::testing::TestCase* testcase); virtual void createDummyInSequenceToAndFailureReporterAvoidMemoryLeakInGMock(); private: GTestResultReporter* reporter_; GTestShell* first_; GTestFlagsThatAllocateMemory flags_; }; class GTestDummyResultReporter : public ::testing::ScopedFakeTestPartResultReporter { public: GTestDummyResultReporter () : ::testing::ScopedFakeTestPartResultReporter(INTERCEPT_ALL_THREADS, NULL) {} virtual void ReportTestPartResult(const ::testing::TestPartResult& /*result*/) {} }; class GMockTestTerminator : public TestTerminator { public: GMockTestTerminator(const ::testing::TestPartResult& result) : result_(result) { } virtual void exitCurrentTest() const { /* * When using GMock, it throws an exception from the destructor leaving * the system in an unstable state. * Therefore, when the test fails because of failed gmock expectation * then don't throw the exception, but let it return. Usually this should * already be at the end of the test, so it doesn't matter much */ /* * TODO: We probably want this check here, however the tests fail when putting it there. Also, we'll need to * check how to get all the gTest tests to run within CppUTest. At the moment, the 'death tests' seem to fail * still. * * if (result_.type() == ::testing::TestPartResult::kFatalFailure) { */ if (!SimpleString(result_.message()).contains("Actual: never called") && !SimpleString(result_.message()).contains("Actual function call count doesn't match")) throw CppUTestFailedException(); } virtual ~GMockTestTerminator() { } private: const ::testing::TestPartResult& result_; }; class GTestResultReporter : public ::testing::ScopedFakeTestPartResultReporter { public: GTestResultReporter () : ::testing::ScopedFakeTestPartResultReporter(INTERCEPT_ALL_THREADS, NULL) {} virtual void ReportTestPartResult(const ::testing::TestPartResult& result) { FailFailure failure(UtestShell::getCurrent(), result.file_name(), result.line_number(), result.message()); UtestShell::getCurrent()->failWith(failure, GMockTestTerminator(result)); } }; inline GTestShell::GTestShell(::testing::TestInfo* testinfo, GTestShell* next, GTestFlagsThatAllocateMemory* flags) : testinfo_(testinfo), next_(next), flags_(flags) { setGroupName(testinfo->test_case_name()); setTestName(testinfo->name()); } class GTestUTest: public Utest { public: GTestUTest(::testing::TestInfo* testinfo, GTestFlagsThatAllocateMemory* flags) : testinfo_(testinfo), test_(NULL), flags_(flags) { } void testBody() { try { test_->TestBody(); } catch (CppUTestFailedException& ex) { } } void setup() { flags_->resetValuesOfGTestFlags(); #ifdef GTEST_VERSION_GTEST_1_5 test_ = testinfo_->impl()->factory_->CreateTest(); #else test_ = testinfo_->factory_->CreateTest(); #endif ::testing::UnitTest::GetInstance()->impl()->set_current_test_info(testinfo_); try { test_->SetUp(); } catch (CppUTestFailedException& ex) { } } void teardown() { try { test_->TearDown(); } catch (CppUTestFailedException& ex) { } ::testing::UnitTest::GetInstance()->impl()->set_current_test_info(NULL); delete test_; flags_->setGTestFlagValuesToNULLToAvoidMemoryLeaks(); ::testing::internal::DeathTest::set_last_death_test_message(GTEST_NO_STRING_VALUE); } private: ::testing::Test* test_; ::testing::TestInfo* testinfo_; GTestFlagsThatAllocateMemory* flags_; }; inline Utest* GTestShell::createTest() { return new GTestUTest(testinfo_, flags_); }; inline void GTestConvertor::simulateGTestFailureToPreAllocateAllTheThreadLocalData() { GTestDummyResultReporter *dummyReporter = new GTestDummyResultReporter(); ASSERT_TRUE(false); delete dummyReporter; } inline GTestConvertor::GTestConvertor(bool shouldSimulateFailureAtCreationToAllocateThreadLocalData) : first_(NULL) { if (shouldSimulateFailureAtCreationToAllocateThreadLocalData) simulateGTestFailureToPreAllocateAllTheThreadLocalData(); reporter_ = new GTestResultReporter(); } inline GTestConvertor::~GTestConvertor() { delete reporter_; while (first_) { GTestShell* next = first_->nextGTest(); delete first_; first_ = next; } } inline void GTestConvertor::addNewTestCaseForTestInfo(::testing::TestInfo* testinfo) { first_ = new GTestShell(testinfo, first_, &flags_); TestRegistry::getCurrentRegistry()->addTest(first_); } inline void GTestConvertor::addAllTestsFromTestCaseToTestRegistry(::testing::TestCase* testcase) { int currentTestCount = 0; ::testing::TestInfo* currentTest = (::testing::TestInfo*) testcase->GetTestInfo(currentTestCount); while (currentTest) { addNewTestCaseForTestInfo(currentTest); currentTestCount++; currentTest = (::testing::TestInfo*) testcase->GetTestInfo(currentTestCount); } } inline void GTestConvertor::createDummyInSequenceToAndFailureReporterAvoidMemoryLeakInGMock() { ::testing::InSequence seq; ::testing::internal::GetFailureReporter(); } inline void GTestConvertor::addAllGTestToTestRegistry() { createDummyInSequenceToAndFailureReporterAvoidMemoryLeakInGMock(); flags_.storeValuesOfGTestFlags(); int argc = 2; const char * argv[] = {"NameOfTheProgram", "--gmock_catch_leaked_mocks=0"}; ::testing::InitGoogleMock(&argc, (char**) argv); ::testing::UnitTest* unitTests = ::testing::UnitTest::GetInstance(); int currentUnitTestCount = 0; ::testing::TestCase* currentTestCase = (::testing::TestCase*) unitTests->GetTestCase(currentUnitTestCount); while (currentTestCase) { addAllTestsFromTestCaseToTestRegistry(currentTestCase); currentUnitTestCount++; currentTestCase = (::testing::TestCase*) unitTests->GetTestCase(currentUnitTestCount); } } #endif
null
118
cpp
cpputest
IEEE754ExceptionsPlugin.h
include/CppUTestExt/IEEE754ExceptionsPlugin.h
null
/* * Copyright (c) 2015, Michael Feathers, James Grenning, Bas Vodde * and Arnd Strube. 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 <organization> 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 <copyright holder> 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_IEEE754ExceptionsPlugin_h #define D_IEEE754ExceptionsPlugin_h #include "CppUTest/TestPlugin.h" class IEEE754ExceptionsPlugin: public TestPlugin { public: IEEE754ExceptionsPlugin(const SimpleString& name = "IEEE754ExceptionsPlugin"); virtual void preTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; virtual void postTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; static void disableInexact(void); static void enableInexact(void); static bool checkIeee754OverflowExceptionFlag(); static bool checkIeee754UnderflowExceptionFlag(); static bool checkIeee754InexactExceptionFlag(); static bool checkIeee754DivByZeroExceptionFlag(); private: void ieee754Check(UtestShell& test, TestResult& result, int flag, const char* text); static bool inexactDisabled_; }; #endif
null
119
cpp
cpputest
MockCheckedExpectedCall.h
include/CppUTestExt/MockCheckedExpectedCall.h
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 <organization> 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 <copyright holder> 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_MockCheckedExpectedCall_h #define D_MockCheckedExpectedCall_h #include "CppUTestExt/MockExpectedCall.h" #include "CppUTestExt/MockNamedValue.h" class MockCheckedExpectedCall : public MockExpectedCall { public: MockCheckedExpectedCall(); MockCheckedExpectedCall(unsigned int numCalls); virtual ~MockCheckedExpectedCall() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual MockExpectedCall& withName(const SimpleString& name) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withCallOrder(unsigned int callOrder) CPPUTEST_OVERRIDE { return withCallOrder(callOrder, callOrder); } virtual MockExpectedCall& withCallOrder(unsigned int initialCallOrder, unsigned int finalCallOrder) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withBoolParameter(const SimpleString& name, bool value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withIntParameter(const SimpleString& name, int value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withLongIntParameter(const SimpleString& name, long int value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withLongLongIntParameter(const SimpleString& name, cpputest_longlong value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value, double tolerance) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withStringParameter(const SimpleString& name, const char* value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withPointerParameter(const SimpleString& name, void* value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withConstPointerParameter(const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withOutputParameterReturning(const SimpleString& name, const void* value, size_t size) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString& typeName, const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& withUnmodifiedOutputParameter(const SimpleString& name) CPPUTEST_OVERRIDE; virtual MockExpectedCall& ignoreOtherParameters() CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(bool value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(int value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(unsigned int value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(long int value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(unsigned long int value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(cpputest_longlong value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(cpputest_ulonglong value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(double value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(const char* value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(void* value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(const void* value) CPPUTEST_OVERRIDE; virtual MockExpectedCall& andReturnValue(void (*value)()) CPPUTEST_OVERRIDE; virtual MockNamedValue returnValue(); virtual MockExpectedCall& onObject(void* objectPtr) CPPUTEST_OVERRIDE; virtual MockNamedValue getInputParameter(const SimpleString& name); virtual MockNamedValue getOutputParameter(const SimpleString& name); virtual SimpleString getInputParameterType(const SimpleString& name); virtual SimpleString getInputParameterValueString(const SimpleString& name); virtual bool hasInputParameterWithName(const SimpleString& name); virtual bool hasInputParameter(const MockNamedValue& parameter); virtual bool hasOutputParameterWithName(const SimpleString& name); virtual bool hasOutputParameter(const MockNamedValue& parameter); virtual bool relatesTo(const SimpleString& functionName); virtual bool relatesToObject(const void* objectPtr) const; virtual bool isFulfilled(); virtual bool canMatchActualCalls(); virtual bool isMatchingActualCallAndFinalized(); virtual bool isMatchingActualCall(); virtual bool areParametersMatchingActualCall(); virtual bool isOutOfOrder() const; virtual void callWasMade(unsigned int callOrder); virtual void inputParameterWasPassed(const SimpleString& name); virtual void outputParameterWasPassed(const SimpleString& name); virtual void finalizeActualCallMatch(); virtual void wasPassedToObject(); virtual void resetActualCallMatchingState(); virtual SimpleString callToString(); virtual SimpleString missingParametersToString(); enum { NO_EXPECTED_CALL_ORDER = 0 }; virtual unsigned int getActualCallsFulfilled() const; protected: void setName(const SimpleString& name); SimpleString getName() const; private: SimpleString functionName_; class MockExpectedFunctionParameter : public MockNamedValue { public: MockExpectedFunctionParameter(const SimpleString& name); void setMatchesActualCall(bool b); bool isMatchingActualCall() const; private: bool matchesActualCall_; }; MockExpectedFunctionParameter* item(MockNamedValueListNode* node); bool ignoreOtherParameters_; bool isActualCallMatchFinalized_; unsigned int initialExpectedCallOrder_; unsigned int finalExpectedCallOrder_; bool outOfOrder_; MockNamedValueList* inputParameters_; MockNamedValueList* outputParameters_; MockNamedValue returnValue_; void* objectPtr_; bool isSpecificObjectExpected_; bool wasPassedToObject_; unsigned int actualCalls_; unsigned int expectedCalls_; }; class MockIgnoredExpectedCall: public MockExpectedCall { public: virtual MockExpectedCall& withName(const SimpleString&) CPPUTEST_OVERRIDE { return *this;} virtual MockExpectedCall& withCallOrder(unsigned int) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withCallOrder(unsigned int, unsigned int) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withBoolParameter(const SimpleString&, bool) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withIntParameter(const SimpleString&, int) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString&, unsigned int) CPPUTEST_OVERRIDE{ return *this; } virtual MockExpectedCall& withLongIntParameter(const SimpleString&, long int) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString&, unsigned long int) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withLongLongIntParameter(const SimpleString&, cpputest_longlong) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withUnsignedLongLongIntParameter(const SimpleString&, cpputest_ulonglong) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withDoubleParameter(const SimpleString&, double) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withDoubleParameter(const SimpleString&, double, double) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withStringParameter(const SimpleString&, const char*) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withPointerParameter(const SimpleString& , void*) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withConstPointerParameter(const SimpleString& , const void*) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& , void(*)()) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withMemoryBufferParameter(const SimpleString&, const unsigned char*, size_t) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withParameterOfType(const SimpleString&, const SimpleString&, const void*) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withOutputParameterReturning(const SimpleString&, const void*, size_t) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString&, const SimpleString&, const void*) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& withUnmodifiedOutputParameter(const SimpleString&) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& ignoreOtherParameters() CPPUTEST_OVERRIDE { return *this;} virtual MockExpectedCall& andReturnValue(bool) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& andReturnValue(int) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& andReturnValue(unsigned int) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& andReturnValue(long int) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& andReturnValue(unsigned long int) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& andReturnValue(cpputest_longlong) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& andReturnValue(cpputest_ulonglong) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& andReturnValue(double) CPPUTEST_OVERRIDE { return *this;} virtual MockExpectedCall& andReturnValue(const char*) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& andReturnValue(void*) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& andReturnValue(const void*) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& andReturnValue(void (*)()) CPPUTEST_OVERRIDE { return *this; } virtual MockExpectedCall& onObject(void*) CPPUTEST_OVERRIDE { return *this; } static MockExpectedCall& instance(); }; #endif
null
120
cpp
cpputest
MockSupport_c.h
include/CppUTestExt/MockSupport_c.h
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 <organization> 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 <copyright holder> 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_MockSupport_c_h #define D_MockSupport_c_h #ifdef __cplusplus extern "C" { #endif #include "CppUTest/CppUTestConfig.h" #include "CppUTest/StandardCLibrary.h" typedef enum { MOCKVALUETYPE_BOOL, MOCKVALUETYPE_UNSIGNED_INTEGER, MOCKVALUETYPE_INTEGER, MOCKVALUETYPE_LONG_INTEGER, MOCKVALUETYPE_UNSIGNED_LONG_INTEGER, MOCKVALUETYPE_LONG_LONG_INTEGER, MOCKVALUETYPE_UNSIGNED_LONG_LONG_INTEGER, MOCKVALUETYPE_DOUBLE, MOCKVALUETYPE_STRING, MOCKVALUETYPE_POINTER, MOCKVALUETYPE_CONST_POINTER, MOCKVALUETYPE_FUNCTIONPOINTER, MOCKVALUETYPE_MEMORYBUFFER, MOCKVALUETYPE_OBJECT } MockValueType_c; typedef struct SMockValue_c { MockValueType_c type; union { int boolValue; int intValue; unsigned int unsignedIntValue; long int longIntValue; unsigned long int unsignedLongIntValue; #if CPPUTEST_USE_LONG_LONG cpputest_longlong longLongIntValue; cpputest_ulonglong unsignedLongLongIntValue; #else char longLongPlaceholder[CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE]; #endif double doubleValue; const char* stringValue; void* pointerValue; const void* constPointerValue; void (*functionPointerValue)(void); const unsigned char* memoryBufferValue; void* objectValue; const void* constObjectValue; } value; } MockValue_c; typedef struct SMockActualCall_c MockActualCall_c; struct SMockActualCall_c { MockActualCall_c* (*withBoolParameters)(const char* name, int value); MockActualCall_c* (*withIntParameters)(const char* name, int value); MockActualCall_c* (*withUnsignedIntParameters)(const char* name, unsigned int value); MockActualCall_c* (*withLongIntParameters)(const char* name, long int value); MockActualCall_c* (*withUnsignedLongIntParameters)(const char* name, unsigned long int value); MockActualCall_c* (*withLongLongIntParameters)(const char* name, cpputest_longlong value); MockActualCall_c* (*withUnsignedLongLongIntParameters)(const char* name, cpputest_ulonglong value); MockActualCall_c* (*withDoubleParameters)(const char* name, double value); MockActualCall_c* (*withStringParameters)(const char* name, const char* value); MockActualCall_c* (*withPointerParameters)(const char* name, void* value); MockActualCall_c* (*withConstPointerParameters)(const char* name, const void* value); MockActualCall_c* (*withFunctionPointerParameters)(const char* name, void (*value)(void)); MockActualCall_c* (*withMemoryBufferParameter)(const char* name, const unsigned char* value, size_t size); MockActualCall_c* (*withParameterOfType)(const char* type, const char* name, const void* value); MockActualCall_c* (*withOutputParameter)(const char* name, void* value); MockActualCall_c* (*withOutputParameterOfType)(const char* type, const char* name, void* value); int (*hasReturnValue)(void); MockValue_c (*returnValue)(void); int (*boolReturnValue)(void); int (*returnBoolValueOrDefault)(int defaultValue); int (*intReturnValue)(void); int (*returnIntValueOrDefault)(int defaultValue); unsigned int (*unsignedIntReturnValue)(void); unsigned int (*returnUnsignedIntValueOrDefault)(unsigned int defaultValue); long int (*longIntReturnValue)(void); long int (*returnLongIntValueOrDefault)(long int defaultValue); unsigned long int (*unsignedLongIntReturnValue)(void); unsigned long int (*returnUnsignedLongIntValueOrDefault)(unsigned long int defaultValue); cpputest_longlong (*longLongIntReturnValue)(void); cpputest_longlong (*returnLongLongIntValueOrDefault)(cpputest_longlong defaultValue); cpputest_ulonglong (*unsignedLongLongIntReturnValue)(void); cpputest_ulonglong (*returnUnsignedLongLongIntValueOrDefault)(cpputest_ulonglong defaultValue); const char* (*stringReturnValue)(void); const char* (*returnStringValueOrDefault)(const char * defaultValue); double (*doubleReturnValue)(void); double (*returnDoubleValueOrDefault)(double defaultValue); void* (*pointerReturnValue)(void); void* (*returnPointerValueOrDefault)(void * defaultValue); const void* (*constPointerReturnValue)(void); const void* (*returnConstPointerValueOrDefault)(const void * defaultValue); void (*(*functionPointerReturnValue)(void))(void); void (*(*returnFunctionPointerValueOrDefault)(void(*defaultValue)(void)))(void); }; typedef struct SMockExpectedCall_c MockExpectedCall_c; struct SMockExpectedCall_c { MockExpectedCall_c* (*withBoolParameters)(const char* name, int value); MockExpectedCall_c* (*withIntParameters)(const char* name, int value); MockExpectedCall_c* (*withUnsignedIntParameters)(const char* name, unsigned int value); MockExpectedCall_c* (*withLongIntParameters)(const char* name, long int value); MockExpectedCall_c* (*withUnsignedLongIntParameters)(const char* name, unsigned long int value); MockExpectedCall_c* (*withLongLongIntParameters)(const char* name, cpputest_longlong value); MockExpectedCall_c* (*withUnsignedLongLongIntParameters)(const char* name, cpputest_ulonglong value); MockExpectedCall_c* (*withDoubleParameters)(const char* name, double value); MockExpectedCall_c* (*withDoubleParametersAndTolerance)(const char* name, double value, double tolerance); MockExpectedCall_c* (*withStringParameters)(const char* name, const char* value); MockExpectedCall_c* (*withPointerParameters)(const char* name, void* value); MockExpectedCall_c* (*withConstPointerParameters)(const char* name, const void* value); MockExpectedCall_c* (*withFunctionPointerParameters)(const char* name, void (*value)(void)); MockExpectedCall_c* (*withMemoryBufferParameter)(const char* name, const unsigned char* value, size_t size); MockExpectedCall_c* (*withParameterOfType)(const char* type, const char* name, const void* value); MockExpectedCall_c* (*withOutputParameterReturning)(const char* name, const void* value, size_t size); MockExpectedCall_c* (*withOutputParameterOfTypeReturning)(const char* type, const char* name, const void* value); MockExpectedCall_c* (*withUnmodifiedOutputParameter)(const char* name); MockExpectedCall_c* (*ignoreOtherParameters)(void); MockExpectedCall_c* (*andReturnBoolValue)(int value); MockExpectedCall_c* (*andReturnUnsignedIntValue)(unsigned int value); MockExpectedCall_c* (*andReturnIntValue)(int value); MockExpectedCall_c* (*andReturnLongIntValue)(long int value); MockExpectedCall_c* (*andReturnUnsignedLongIntValue)(unsigned long int value); MockExpectedCall_c* (*andReturnLongLongIntValue)(cpputest_longlong value); MockExpectedCall_c* (*andReturnUnsignedLongLongIntValue)(cpputest_ulonglong value); MockExpectedCall_c* (*andReturnDoubleValue)(double value); MockExpectedCall_c* (*andReturnStringValue)(const char* value); MockExpectedCall_c* (*andReturnPointerValue)(void* value); MockExpectedCall_c* (*andReturnConstPointerValue)(const void* value); MockExpectedCall_c* (*andReturnFunctionPointerValue)(void (*value)(void)); }; typedef int (*MockTypeEqualFunction_c)(const void* object1, const void* object2); typedef const char* (*MockTypeValueToStringFunction_c)(const void* object1); typedef void (*MockTypeCopyFunction_c)(void* dst, const void* src); typedef struct SMockSupport_c MockSupport_c; struct SMockSupport_c { void (*strictOrder)(void); MockExpectedCall_c* (*expectOneCall)(const char* name); void (*expectNoCall)(const char* name); MockExpectedCall_c* (*expectNCalls)(unsigned int number, const char* name); MockActualCall_c* (*actualCall)(const char* name); int (*hasReturnValue)(void); MockValue_c (*returnValue)(void); int (*boolReturnValue)(void); int (*returnBoolValueOrDefault)(int defaultValue); int (*intReturnValue)(void); int (*returnIntValueOrDefault)(int defaultValue); unsigned int (*unsignedIntReturnValue)(void); unsigned int (*returnUnsignedIntValueOrDefault)(unsigned int defaultValue); long int (*longIntReturnValue)(void); long int (*returnLongIntValueOrDefault)(long int defaultValue); unsigned long int (*unsignedLongIntReturnValue)(void); unsigned long int (*returnUnsignedLongIntValueOrDefault)(unsigned long int defaultValue); cpputest_longlong (*longLongIntReturnValue)(void); cpputest_longlong (*returnLongLongIntValueOrDefault)(cpputest_longlong defaultValue); cpputest_ulonglong (*unsignedLongLongIntReturnValue)(void); cpputest_ulonglong (*returnUnsignedLongLongIntValueOrDefault)(cpputest_ulonglong defaultValue); const char* (*stringReturnValue)(void); const char* (*returnStringValueOrDefault)(const char * defaultValue); double (*doubleReturnValue)(void); double (*returnDoubleValueOrDefault)(double defaultValue); void* (*pointerReturnValue)(void); void* (*returnPointerValueOrDefault)(void * defaultValue); const void* (*constPointerReturnValue)(void); const void* (*returnConstPointerValueOrDefault)(const void * defaultValue); void (*(*functionPointerReturnValue)(void))(void); void (*(*returnFunctionPointerValueOrDefault) (void(*defaultValue)(void)))(void); void (*setBoolData) (const char* name, int value); void (*setIntData) (const char* name, int value); void (*setUnsignedIntData) (const char* name, unsigned int value); void (*setStringData) (const char* name, const char* value); void (*setDoubleData) (const char* name, double value); void (*setPointerData) (const char* name, void* value); void (*setConstPointerData) (const char* name, const void* value); void (*setFunctionPointerData) (const char* name, void (*value)(void)); void (*setDataObject) (const char* name, const char* type, void* value); void (*setDataConstObject) (const char* name, const char* type, const void* value); MockValue_c (*getData)(const char* name); void (*disable)(void); void (*enable)(void); void (*ignoreOtherCalls)(void); void (*checkExpectations)(void); int (*expectedCallsLeft)(void); void (*clear)(void); void (*crashOnFailure)(unsigned shouldCrash); void (*installComparator) (const char* typeName, MockTypeEqualFunction_c isEqual, MockTypeValueToStringFunction_c valueToString); void (*installCopier) (const char* typeName, MockTypeCopyFunction_c copier); void (*removeAllComparatorsAndCopiers)(void); }; MockSupport_c* mock_c(void); MockSupport_c* mock_scope_c(const char* scope); #ifdef __cplusplus } #endif #endif
null
121
cpp
cpputest
MemoryReportFormatter.h
include/CppUTestExt/MemoryReportFormatter.h
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 <organization> 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 <copyright holder> 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_MemoryReportFormatter_h #define D_MemoryReportFormatter_h class TestOutput; class UtestShell; class MemoryReportFormatter { public: virtual ~MemoryReportFormatter(){} virtual void report_testgroup_start(TestResult* result, UtestShell& test)=0; virtual void report_testgroup_end(TestResult* result, UtestShell& test)=0; virtual void report_test_start(TestResult* result, UtestShell& test)=0; virtual void report_test_end(TestResult* result, UtestShell& test)=0; virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, size_t line)=0; virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, size_t line)=0; }; class NormalMemoryReportFormatter : public MemoryReportFormatter { public: NormalMemoryReportFormatter(); virtual ~NormalMemoryReportFormatter() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void report_testgroup_start(TestResult* /*result*/, UtestShell& /*test*/) CPPUTEST_OVERRIDE; virtual void report_testgroup_end(TestResult* /*result*/, UtestShell& /*test*/) CPPUTEST_OVERRIDE {} // LCOV_EXCL_LINE virtual void report_test_start(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE; virtual void report_test_end(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE; virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, size_t line) CPPUTEST_OVERRIDE; }; #endif
null
122
cpp
cpputest
GTest.h
include/CppUTestExt/GTest.h
null
/* * Copyright (c) 2011, 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 <organization> 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 <copyright holder> 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 GTEST_H_ #define GTEST_H_ #undef new #undef strdup #undef strndup #undef RUN_ALL_TESTS #include "gtest/gtest.h" #ifdef CPPUTEST_USE_NEW_MACROS #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif #ifdef CPPUTEST_USE_MALLOC_MACROS #include "CppUTest/MemoryLeakDetectorMallocMacros.h" #endif #include "CppUTestExt/GTestSupport.h" #ifndef RUN_ALL_TESTS #define GTEST_VERSION_GTEST_1_7 #else #ifdef ADD_FAILURE_AT #define GTEST_VERSION_GTEST_1_6 #else #define GTEST_VERSION_GTEST_1_5 #endif #endif #undef RUN_ALL_TESTS #endif
null
123
cpp
cpputest
GTestSupport.h
include/CppUTestExt/GTestSupport.h
null
/* * Copyright (c) 2011, 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 <organization> 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 <copyright holder> 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 GTESTSUPPORT_H_ #define GTESTSUPPORT_H_ extern void CppuTestGTestIgnoreLeaksInTest(); #endif
null
124
cpp
cpputest
GMock.h
include/CppUTestExt/GMock.h
null
/* * Copyright (c) 2011, 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 <organization> 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 <copyright holder> 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 GMOCK_H_ #define GMOCK_H_ #undef new #undef strdup #undef strndup #undef RUN_ALL_TESTS #define GTEST_DONT_DEFINE_TEST 1 #define GTEST_DONT_DEFINE_FAIL 1 #include "gmock/gmock.h" #undef RUN_ALL_TESTS using testing::Return; using testing::NiceMock; #ifdef CPPUTEST_USE_NEW_MACROS #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif #ifdef CPPUTEST_USE_MALLOC_MACROS #include "CppUTest/MemoryLeakDetectorMallocMacros.h" #endif #endif
null
125
cpp
cpputest
MockActualCall.h
include/CppUTestExt/MockActualCall.h
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 <organization> 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 <copyright holder> 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_MockActualCall_h #define D_MockActualCall_h #include "CppUTest/CppUTestConfig.h" #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockNamedValue.h" #include "CppUTestExt/MockExpectedCallsList.h" class MockFailureReporter; class MockFailure; class MockActualCall { public: MockActualCall(); virtual ~MockActualCall(); virtual MockActualCall& withName(const SimpleString& name)=0; virtual MockActualCall& withCallOrder(unsigned int callOrder)=0; MockActualCall& withParameter(const SimpleString& name, bool value) { return withBoolParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, int value) { return withIntParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, unsigned int value) { return withUnsignedIntParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, long int value) { return withLongIntParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, unsigned long int value) { return withUnsignedLongIntParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, cpputest_longlong value) { return withLongLongIntParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, cpputest_ulonglong value) { return withUnsignedLongLongIntParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, double value) { return withDoubleParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, const char* value) { return withStringParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, void* value) { return withPointerParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, void (*value)()) { return withFunctionPointerParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, const void* value) { return withConstPointerParameter(name, value); } MockActualCall& withParameter(const SimpleString& name, const unsigned char* value, size_t size) { return withMemoryBufferParameter(name, value, size); } virtual MockActualCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value)=0; virtual MockActualCall& withOutputParameter(const SimpleString& name, void* output)=0; virtual MockActualCall& withOutputParameterOfType(const SimpleString& typeName, const SimpleString& name, void* output)=0; virtual MockActualCall& withBoolParameter(const SimpleString& name, bool value)=0; virtual MockActualCall& withIntParameter(const SimpleString& name, int value)=0; virtual MockActualCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value)=0; virtual MockActualCall& withLongIntParameter(const SimpleString& name, long int value)=0; virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value)=0; virtual MockActualCall& withLongLongIntParameter(const SimpleString& name, cpputest_longlong value)=0; virtual MockActualCall& withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value)=0; virtual MockActualCall& withDoubleParameter(const SimpleString& name, double value)=0; virtual MockActualCall& withStringParameter(const SimpleString& name, const char* value)=0; virtual MockActualCall& withPointerParameter(const SimpleString& name, void* value)=0; virtual MockActualCall& withFunctionPointerParameter(const SimpleString& name, void (*value)())=0; virtual MockActualCall& withConstPointerParameter(const SimpleString& name, const void* value)=0; virtual MockActualCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size)=0; virtual bool hasReturnValue()=0; virtual MockNamedValue returnValue()=0; virtual bool returnBoolValueOrDefault(bool default_value)=0; virtual bool returnBoolValue()=0; virtual int returnIntValueOrDefault(int default_value)=0; virtual int returnIntValue()=0; virtual unsigned long int returnUnsignedLongIntValue()=0; virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int default_value)=0; virtual long int returnLongIntValue()=0; virtual long int returnLongIntValueOrDefault(long int default_value)=0; virtual cpputest_ulonglong returnUnsignedLongLongIntValue()=0; virtual cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong default_value)=0; virtual cpputest_longlong returnLongLongIntValue()=0; virtual cpputest_longlong returnLongLongIntValueOrDefault(cpputest_longlong default_value)=0; virtual unsigned int returnUnsignedIntValue()=0; virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int default_value)=0; virtual const char * returnStringValueOrDefault(const char * default_value)=0; virtual const char * returnStringValue()=0; virtual double returnDoubleValue()=0; virtual double returnDoubleValueOrDefault(double default_value)=0; virtual void * returnPointerValue()=0; virtual void * returnPointerValueOrDefault(void * default_value)=0; virtual const void * returnConstPointerValue()=0; virtual const void * returnConstPointerValueOrDefault(const void * default_value)=0; virtual void (*returnFunctionPointerValue())()=0; virtual void (*returnFunctionPointerValueOrDefault(void (*default_value)()))()=0; virtual MockActualCall& onObject(const void* objectPtr)=0; }; #endif
null
126
cpp
cpputest
MemoryReportAllocator.h
include/CppUTestExt/MemoryReportAllocator.h
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 <organization> 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 <copyright holder> 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_MemoryReportAllocator_h #define D_MemoryReportAllocator_h #include "CppUTest/TestMemoryAllocator.h" class MemoryReportFormatter; class MemoryReportAllocator : public TestMemoryAllocator { protected: TestResult* result_; TestMemoryAllocator* realAllocator_; MemoryReportFormatter* formatter_; public: MemoryReportAllocator(); virtual ~MemoryReportAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void setFormatter(MemoryReportFormatter* formatter); virtual void setTestResult(TestResult* result); virtual void setRealAllocator(TestMemoryAllocator* allocator); virtual TestMemoryAllocator* getRealAllocator(); virtual char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual const char* name() const CPPUTEST_OVERRIDE; virtual const char* alloc_name() const CPPUTEST_OVERRIDE; virtual const char* free_name() const CPPUTEST_OVERRIDE; virtual TestMemoryAllocator* actualAllocator() CPPUTEST_OVERRIDE; }; #endif
null
127
cpp
cpputest
MockNamedValue.h
include/CppUTestExt/MockNamedValue.h
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 <organization> 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 <copyright holder> 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_MockNamedValue_h #define D_MockNamedValue_h #include "CppUTest/CppUTestConfig.h" /* * MockNamedValueComparator is an interface that needs to be used when creating Comparators. * This is needed when comparing values of non-native type. */ class MockNamedValueComparator { public: MockNamedValueComparator() {} virtual ~MockNamedValueComparator() {} virtual bool isEqual(const void* object1, const void* object2)=0; virtual SimpleString valueToString(const void* object)=0; }; /* * MockNamedValueCopier is an interface that needs to be used when creating Copiers. * This is needed when copying values of non-native type. */ class MockNamedValueCopier { public: MockNamedValueCopier() {} virtual ~MockNamedValueCopier() {} virtual void copy(void* out, const void* in)=0; }; class MockFunctionComparator : public MockNamedValueComparator { public: typedef bool (*isEqualFunction)(const void*, const void*); typedef SimpleString (*valueToStringFunction)(const void*); MockFunctionComparator(isEqualFunction equal, valueToStringFunction valToString) : equal_(equal), valueToString_(valToString) {} virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { return equal_(object1, object2); } virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { return valueToString_(object); } private: isEqualFunction equal_; valueToStringFunction valueToString_; }; class MockFunctionCopier : public MockNamedValueCopier { public: typedef void (*copyFunction)(void*, const void*); MockFunctionCopier(copyFunction copier) : copier_(copier) {} virtual void copy(void* dst, const void* src) CPPUTEST_OVERRIDE { copier_(dst, src); } private: copyFunction copier_; }; /* * MockNamedValue is the generic value class used. It encapsulates basic types and can use them "as if one" * Also it enables other types by putting object pointers. They can be compared with comparators. * * Basically this class ties together a Name, a Value, a Type, and a Comparator */ class MockNamedValueComparatorsAndCopiersRepository; class MockNamedValue { public: MockNamedValue(const SimpleString& name); DEFAULT_COPY_CONSTRUCTOR(MockNamedValue) virtual ~MockNamedValue(); virtual void setValue(bool value); virtual void setValue(int value); virtual void setValue(unsigned int value); virtual void setValue(long int value); virtual void setValue(unsigned long int value); virtual void setValue(cpputest_longlong value); virtual void setValue(cpputest_ulonglong value); virtual void setValue(double value); virtual void setValue(double value, double tolerance); virtual void setValue(void* value); virtual void setValue(const void* value); virtual void setValue(void (*value)()); virtual void setValue(const char* value); virtual void setMemoryBuffer(const unsigned char* value, size_t size); virtual void setConstObjectPointer(const SimpleString& type, const void* objectPtr); virtual void setObjectPointer(const SimpleString& type, void* objectPtr); virtual void setSize(size_t size); virtual void setName(const char* name); virtual bool equals(const MockNamedValue& p) const; virtual bool compatibleForCopying(const MockNamedValue& p) const; virtual SimpleString toString() const; virtual SimpleString getName() const; virtual SimpleString getType() const; virtual bool getBoolValue() const; virtual int getIntValue() const; virtual unsigned int getUnsignedIntValue() const; virtual long int getLongIntValue() const; virtual unsigned long int getUnsignedLongIntValue() const; virtual cpputest_longlong getLongLongIntValue() const; virtual cpputest_ulonglong getUnsignedLongLongIntValue() const; virtual double getDoubleValue() const; virtual double getDoubleTolerance() const; virtual const char* getStringValue() const; virtual void* getPointerValue() const; virtual const void* getConstPointerValue() const; virtual void (*getFunctionPointerValue() const)(); virtual const unsigned char* getMemoryBuffer() const; virtual const void* getConstObjectPointer() const; virtual void* getObjectPointer() const; virtual size_t getSize() const; virtual MockNamedValueComparator* getComparator() const; virtual MockNamedValueCopier* getCopier() const; static void setDefaultComparatorsAndCopiersRepository(MockNamedValueComparatorsAndCopiersRepository* repository); static MockNamedValueComparatorsAndCopiersRepository* getDefaultComparatorsAndCopiersRepository(); static const double defaultDoubleTolerance; private: SimpleString name_; SimpleString type_; union { bool boolValue_; int intValue_; unsigned int unsignedIntValue_; long int longIntValue_; unsigned long int unsignedLongIntValue_; #if CPPUTEST_USE_LONG_LONG cpputest_longlong longLongIntValue_; cpputest_ulonglong unsignedLongLongIntValue_; #else char longLongPlaceholder_[CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE]; #endif struct { double value; double tolerance; } doubleValue_; const char* stringValue_; void* pointerValue_; const void* constPointerValue_; void (*functionPointerValue_)(); const unsigned char* memoryBufferValue_; const void* constObjectPointerValue_; void* objectPointerValue_; const void* outputPointerValue_; } value_; size_t size_; MockNamedValueComparator* comparator_; MockNamedValueCopier* copier_; static MockNamedValueComparatorsAndCopiersRepository* defaultRepository_; }; class MockNamedValueListNode { public: MockNamedValueListNode(MockNamedValue* newValue); SimpleString getName() const; SimpleString getType() const; MockNamedValueListNode* next(); MockNamedValue* item(); void destroy(); void setNext(MockNamedValueListNode* node); private: MockNamedValue* data_; MockNamedValueListNode* next_; }; class MockNamedValueList { public: MockNamedValueList(); MockNamedValueListNode* begin(); void add(MockNamedValue* newValue); void clear(); MockNamedValue* getValueByName(const SimpleString& name); private: MockNamedValueListNode* head_; }; /* * MockParameterComparatorRepository is a class which stores comparators and copiers which can be used for comparing non-native types * */ struct MockNamedValueComparatorsAndCopiersRepositoryNode; class MockNamedValueComparatorsAndCopiersRepository { MockNamedValueComparatorsAndCopiersRepositoryNode* head_; public: MockNamedValueComparatorsAndCopiersRepository(); virtual ~MockNamedValueComparatorsAndCopiersRepository(); virtual void installComparator(const SimpleString& name, MockNamedValueComparator& comparator); virtual void installCopier(const SimpleString& name, MockNamedValueCopier& copier); virtual void installComparatorsAndCopiers(const MockNamedValueComparatorsAndCopiersRepository& repository); virtual MockNamedValueComparator* getComparatorForType(const SimpleString& name); virtual MockNamedValueCopier* getCopierForType(const SimpleString& name); void clear(); }; #endif
null
128
cpp
cpputest
OrderedTest.h
include/CppUTestExt/OrderedTest.h
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 <organization> 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 <copyright holder> 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() CPPUTEST_DESTRUCTOR_OVERRIDE; 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, size_t 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() CPPUTEST_OVERRIDE; }; \ class TEST_##testGroup##_##testName##_TestShell : public OrderedTestShell { \ virtual Utest* createTest() CPPUTEST_OVERRIDE { return new TEST_##testGroup##_##testName##_Test; } \ } TEST_##testGroup##_##testName##_Instance; \ static OrderedTestInstaller TEST_##testGroup##_##testName##_Installer(TEST_##testGroup##_##testName##_Instance, #testGroup, #testName, __FILE__,__LINE__, testLevel); \ void TEST_##testGroup##_##testName##_Test::testBody() #define TEST_ORDERED_C_WRAPPER(group_name, test_name, testLevel) \ extern "C" void test_##group_name##_##test_name##_wrapper_c(void); \ TEST_ORDERED(group_name, test_name, testLevel) { \ test_##group_name##_##test_name##_wrapper_c(); \ } #endif
null
129
cpp
cpputest
CodeMemoryReportFormatter.h
include/CppUTestExt/CodeMemoryReportFormatter.h
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 <organization> 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 <copyright holder> 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_CodeMemoryReportFormatter_h #define D_CodeMemoryReportFormatter_h #include "CppUTestExt/MemoryReportFormatter.h" struct CodeReportingAllocationNode; class CodeMemoryReportFormatter : public MemoryReportFormatter { private: CodeReportingAllocationNode* codeReportingList_; TestMemoryAllocator* internalAllocator_; public: CodeMemoryReportFormatter(TestMemoryAllocator* internalAllocator); virtual ~CodeMemoryReportFormatter() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void report_testgroup_start(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE; virtual void report_testgroup_end(TestResult* /*result*/, UtestShell& /*test*/) CPPUTEST_OVERRIDE {} // LCOV_EXCL_LINE virtual void report_test_start(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE; virtual void report_test_end(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE; virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, size_t line) CPPUTEST_OVERRIDE; virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, size_t line) CPPUTEST_OVERRIDE; private: void addNodeToList(const char* variableName, void* memory, CodeReportingAllocationNode* next); CodeReportingAllocationNode* findNode(void* memory); bool variableExists(const SimpleString& variableName); void clearReporting(); bool isNewAllocator(TestMemoryAllocator* allocator); SimpleString createVariableNameFromFileLineInfo(const char *file, size_t line); SimpleString getAllocationString(TestMemoryAllocator* allocator, const SimpleString& variableName, size_t size); SimpleString getDeallocationString(TestMemoryAllocator* allocator, const SimpleString& variableName, const char* file, size_t line); }; #endif
null
130
cpp
cpputest
MockCheckedActualCall.h
include/CppUTestExt/MockCheckedActualCall.h
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 <organization> 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 <copyright holder> 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_MockCheckedActualCall_h #define D_MockCheckedActualCall_h #include "CppUTestExt/MockActualCall.h" #include "CppUTestExt/MockExpectedCallsList.h" class MockCheckedActualCall : public MockActualCall { public: MockCheckedActualCall(unsigned int callOrder, MockFailureReporter* reporter, const MockExpectedCallsList& expectations); virtual ~MockCheckedActualCall() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual MockActualCall& withName(const SimpleString& name) CPPUTEST_OVERRIDE; virtual MockActualCall& withCallOrder(unsigned int) CPPUTEST_OVERRIDE; virtual MockActualCall& withBoolParameter(const SimpleString& name, bool value) CPPUTEST_OVERRIDE; virtual MockActualCall& withIntParameter(const SimpleString& name, int value) CPPUTEST_OVERRIDE; virtual MockActualCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) CPPUTEST_OVERRIDE; virtual MockActualCall& withLongIntParameter(const SimpleString& name, long int value) CPPUTEST_OVERRIDE; virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) CPPUTEST_OVERRIDE; virtual MockActualCall& withLongLongIntParameter(const SimpleString& name, cpputest_longlong value) CPPUTEST_OVERRIDE; virtual MockActualCall& withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value) CPPUTEST_OVERRIDE; virtual MockActualCall& withDoubleParameter(const SimpleString& name, double value) CPPUTEST_OVERRIDE; virtual MockActualCall& withStringParameter(const SimpleString& name, const char* value) CPPUTEST_OVERRIDE; virtual MockActualCall& withPointerParameter(const SimpleString& name, void* value) CPPUTEST_OVERRIDE; virtual MockActualCall& withConstPointerParameter(const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; virtual MockActualCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) CPPUTEST_OVERRIDE; virtual MockActualCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) CPPUTEST_OVERRIDE; virtual MockActualCall& withParameterOfType(const SimpleString& type, const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; virtual MockActualCall& withOutputParameter(const SimpleString& name, void* output) CPPUTEST_OVERRIDE; virtual MockActualCall& withOutputParameterOfType(const SimpleString& type, const SimpleString& name, void* output) CPPUTEST_OVERRIDE; virtual bool hasReturnValue() CPPUTEST_OVERRIDE; virtual MockNamedValue returnValue() CPPUTEST_OVERRIDE; virtual bool returnBoolValueOrDefault(bool default_value) CPPUTEST_OVERRIDE; virtual bool returnBoolValue() CPPUTEST_OVERRIDE; virtual int returnIntValueOrDefault(int default_value) CPPUTEST_OVERRIDE; virtual int returnIntValue() CPPUTEST_OVERRIDE; virtual unsigned long int returnUnsignedLongIntValue() CPPUTEST_OVERRIDE; virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int) CPPUTEST_OVERRIDE; virtual long int returnLongIntValue() CPPUTEST_OVERRIDE; virtual long int returnLongIntValueOrDefault(long int default_value) CPPUTEST_OVERRIDE; virtual cpputest_ulonglong returnUnsignedLongLongIntValue() CPPUTEST_OVERRIDE; virtual cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong default_value) CPPUTEST_OVERRIDE; virtual cpputest_longlong returnLongLongIntValue() CPPUTEST_OVERRIDE; virtual cpputest_longlong returnLongLongIntValueOrDefault(cpputest_longlong default_value) CPPUTEST_OVERRIDE; virtual unsigned int returnUnsignedIntValue() CPPUTEST_OVERRIDE; virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int default_value) CPPUTEST_OVERRIDE; virtual const char * returnStringValueOrDefault(const char * default_value) CPPUTEST_OVERRIDE; virtual const char * returnStringValue() CPPUTEST_OVERRIDE; virtual double returnDoubleValue() CPPUTEST_OVERRIDE; virtual double returnDoubleValueOrDefault(double default_value) CPPUTEST_OVERRIDE; virtual const void * returnConstPointerValue() CPPUTEST_OVERRIDE; virtual const void * returnConstPointerValueOrDefault(const void * default_value) CPPUTEST_OVERRIDE; virtual void * returnPointerValue() CPPUTEST_OVERRIDE; virtual void * returnPointerValueOrDefault(void *) CPPUTEST_OVERRIDE; typedef void (*FunctionPointerReturnValue)(); virtual FunctionPointerReturnValue returnFunctionPointerValue() CPPUTEST_OVERRIDE; virtual FunctionPointerReturnValue returnFunctionPointerValueOrDefault(void (*)()) CPPUTEST_OVERRIDE; virtual MockActualCall& onObject(const void* objectPtr) CPPUTEST_OVERRIDE; virtual bool isFulfilled() const; virtual bool hasFailed() const; virtual void checkExpectations(); virtual void setMockFailureReporter(MockFailureReporter* reporter); protected: void setName(const SimpleString& name); SimpleString getName() const; virtual UtestShell* getTest() const; virtual void callHasSucceeded(); virtual void copyOutputParameters(MockCheckedExpectedCall* call); virtual void completeCallWhenMatchIsFound(); virtual void failTest(const MockFailure& failure); virtual void checkInputParameter(const MockNamedValue& actualParameter); virtual void checkOutputParameter(const MockNamedValue& outputParameter); virtual void discardCurrentlyMatchingExpectations(); enum ActualCallState { CALL_IN_PROGRESS, CALL_FAILED, CALL_SUCCEED }; virtual void setState(ActualCallState state); private: SimpleString functionName_; unsigned int callOrder_; MockFailureReporter* reporter_; ActualCallState state_; bool expectationsChecked_; MockCheckedExpectedCall* matchingExpectation_; MockExpectedCallsList potentiallyMatchingExpectations_; const MockExpectedCallsList& allExpectations_; class MockOutputParametersListNode { public: SimpleString name_; SimpleString type_; void* ptr_; MockOutputParametersListNode* next_; MockOutputParametersListNode(const SimpleString& name, const SimpleString& type, void* ptr) : name_(name), type_(type), ptr_(ptr), next_(NULLPTR) {} }; MockOutputParametersListNode* outputParameterExpectations_; virtual void addOutputParameter(const SimpleString& name, const SimpleString& type, void* ptr); void cleanUpOutputParameterList(); }; class MockActualCallTrace : public MockActualCall { public: MockActualCallTrace(); virtual ~MockActualCallTrace() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual MockActualCall& withName(const SimpleString& name) CPPUTEST_OVERRIDE; virtual MockActualCall& withCallOrder(unsigned int) CPPUTEST_OVERRIDE; virtual MockActualCall& withBoolParameter(const SimpleString& name, bool value) CPPUTEST_OVERRIDE; virtual MockActualCall& withIntParameter(const SimpleString& name, int value) CPPUTEST_OVERRIDE; virtual MockActualCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) CPPUTEST_OVERRIDE; virtual MockActualCall& withLongIntParameter(const SimpleString& name, long int value) CPPUTEST_OVERRIDE; virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) CPPUTEST_OVERRIDE; virtual MockActualCall& withLongLongIntParameter(const SimpleString& name, cpputest_longlong value) CPPUTEST_OVERRIDE; virtual MockActualCall& withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value) CPPUTEST_OVERRIDE; virtual MockActualCall& withDoubleParameter(const SimpleString& name, double value) CPPUTEST_OVERRIDE; virtual MockActualCall& withStringParameter(const SimpleString& name, const char* value) CPPUTEST_OVERRIDE; virtual MockActualCall& withPointerParameter(const SimpleString& name, void* value) CPPUTEST_OVERRIDE; virtual MockActualCall& withConstPointerParameter(const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; virtual MockActualCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) CPPUTEST_OVERRIDE; virtual MockActualCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) CPPUTEST_OVERRIDE; virtual MockActualCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value) CPPUTEST_OVERRIDE; virtual MockActualCall& withOutputParameter(const SimpleString& name, void* output) CPPUTEST_OVERRIDE; virtual MockActualCall& withOutputParameterOfType(const SimpleString& typeName, const SimpleString& name, void* output) CPPUTEST_OVERRIDE; virtual bool hasReturnValue() CPPUTEST_OVERRIDE; virtual MockNamedValue returnValue() CPPUTEST_OVERRIDE; virtual bool returnBoolValueOrDefault(bool default_value) CPPUTEST_OVERRIDE; virtual bool returnBoolValue() CPPUTEST_OVERRIDE; virtual int returnIntValueOrDefault(int default_value) CPPUTEST_OVERRIDE; virtual int returnIntValue() CPPUTEST_OVERRIDE; virtual unsigned long int returnUnsignedLongIntValue() CPPUTEST_OVERRIDE; virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int) CPPUTEST_OVERRIDE; virtual long int returnLongIntValue() CPPUTEST_OVERRIDE; virtual long int returnLongIntValueOrDefault(long int default_value) CPPUTEST_OVERRIDE; virtual cpputest_ulonglong returnUnsignedLongLongIntValue() CPPUTEST_OVERRIDE; virtual cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong default_value) CPPUTEST_OVERRIDE; virtual cpputest_longlong returnLongLongIntValue() CPPUTEST_OVERRIDE; virtual cpputest_longlong returnLongLongIntValueOrDefault(cpputest_longlong default_value) CPPUTEST_OVERRIDE; virtual unsigned int returnUnsignedIntValue() CPPUTEST_OVERRIDE; virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int default_value) CPPUTEST_OVERRIDE; virtual const char * returnStringValueOrDefault(const char * default_value) CPPUTEST_OVERRIDE; virtual const char * returnStringValue() CPPUTEST_OVERRIDE; virtual double returnDoubleValue() CPPUTEST_OVERRIDE; virtual double returnDoubleValueOrDefault(double default_value) CPPUTEST_OVERRIDE; virtual void * returnPointerValue() CPPUTEST_OVERRIDE; virtual void * returnPointerValueOrDefault(void *) CPPUTEST_OVERRIDE; virtual const void * returnConstPointerValue() CPPUTEST_OVERRIDE; virtual const void * returnConstPointerValueOrDefault(const void * default_value) CPPUTEST_OVERRIDE; virtual MockCheckedActualCall::FunctionPointerReturnValue returnFunctionPointerValue() CPPUTEST_OVERRIDE; virtual MockCheckedActualCall::FunctionPointerReturnValue returnFunctionPointerValueOrDefault(void (*)()) CPPUTEST_OVERRIDE; virtual MockActualCall& onObject(const void* objectPtr) CPPUTEST_OVERRIDE; const char* getTraceOutput(); void clear(); static MockActualCallTrace& instance(); static void clearInstance(); private: SimpleString traceBuffer_; static MockActualCallTrace* instance_; void addParameterName(const SimpleString& name); }; class MockIgnoredActualCall: public MockActualCall { public: virtual MockActualCall& withName(const SimpleString&) CPPUTEST_OVERRIDE { return *this;} virtual MockActualCall& withCallOrder(unsigned int) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withBoolParameter(const SimpleString&, bool) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withIntParameter(const SimpleString&, int) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withUnsignedIntParameter(const SimpleString&, unsigned int) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withLongIntParameter(const SimpleString&, long int) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString&, unsigned long int) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withLongLongIntParameter(const SimpleString&, cpputest_longlong) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withUnsignedLongLongIntParameter(const SimpleString&, cpputest_ulonglong) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withDoubleParameter(const SimpleString&, double) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withStringParameter(const SimpleString&, const char*) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withPointerParameter(const SimpleString& , void*) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withConstPointerParameter(const SimpleString& , const void*) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withFunctionPointerParameter(const SimpleString& , void (*)()) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withMemoryBufferParameter(const SimpleString&, const unsigned char*, size_t) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withParameterOfType(const SimpleString&, const SimpleString&, const void*) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withOutputParameter(const SimpleString&, void*) CPPUTEST_OVERRIDE { return *this; } virtual MockActualCall& withOutputParameterOfType(const SimpleString&, const SimpleString&, void*) CPPUTEST_OVERRIDE { return *this; } virtual bool hasReturnValue() CPPUTEST_OVERRIDE { return false; } virtual MockNamedValue returnValue() CPPUTEST_OVERRIDE { return MockNamedValue(""); } virtual bool returnBoolValueOrDefault(bool value) CPPUTEST_OVERRIDE { return value; } virtual bool returnBoolValue() CPPUTEST_OVERRIDE { return false; } virtual int returnIntValue() CPPUTEST_OVERRIDE { return 0; } virtual int returnIntValueOrDefault(int value) CPPUTEST_OVERRIDE { return value; } virtual unsigned long int returnUnsignedLongIntValue() CPPUTEST_OVERRIDE { return 0; } virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int value) CPPUTEST_OVERRIDE { return value; } virtual long int returnLongIntValue() CPPUTEST_OVERRIDE { return 0; } virtual long int returnLongIntValueOrDefault(long int value) CPPUTEST_OVERRIDE { return value; } virtual cpputest_ulonglong returnUnsignedLongLongIntValue() CPPUTEST_OVERRIDE { #if CPPUTEST_USE_LONG_LONG return 0; #else cpputest_ulonglong ret = {}; return ret; #endif } virtual cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong value) CPPUTEST_OVERRIDE { return value; } virtual cpputest_longlong returnLongLongIntValue() CPPUTEST_OVERRIDE { #if CPPUTEST_USE_LONG_LONG return 0; #else cpputest_longlong ret = {}; return ret; #endif } virtual cpputest_longlong returnLongLongIntValueOrDefault(cpputest_longlong value) CPPUTEST_OVERRIDE { return value; } virtual unsigned int returnUnsignedIntValue() CPPUTEST_OVERRIDE { return 0; } virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int value) CPPUTEST_OVERRIDE { return value; } virtual double returnDoubleValue() CPPUTEST_OVERRIDE { return 0.0; } virtual double returnDoubleValueOrDefault(double value) CPPUTEST_OVERRIDE { return value; } virtual const char * returnStringValue() CPPUTEST_OVERRIDE { return ""; } virtual const char * returnStringValueOrDefault(const char * value) CPPUTEST_OVERRIDE { return value; } virtual void * returnPointerValue() CPPUTEST_OVERRIDE { return NULLPTR; } virtual void * returnPointerValueOrDefault(void * value) CPPUTEST_OVERRIDE { return value; } virtual const void * returnConstPointerValue() CPPUTEST_OVERRIDE { return NULLPTR; } virtual const void * returnConstPointerValueOrDefault(const void * value) CPPUTEST_OVERRIDE { return value; } virtual MockCheckedActualCall::FunctionPointerReturnValue returnFunctionPointerValue() CPPUTEST_OVERRIDE { return NULLPTR; } virtual MockCheckedActualCall::FunctionPointerReturnValue returnFunctionPointerValueOrDefault(void (*value)()) CPPUTEST_OVERRIDE { return value; } virtual MockActualCall& onObject(const void* ) CPPUTEST_OVERRIDE { return *this; } static MockIgnoredActualCall& instance(); }; #endif
null
131
cpp
cpputest
MockExpectedCall.h
include/CppUTestExt/MockExpectedCall.h
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 <organization> 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 <copyright holder> 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_MockExpectedCall_h #define D_MockExpectedCall_h #include "CppUTest/CppUTestConfig.h" class MockNamedValue; extern SimpleString StringFrom(const MockNamedValue& parameter); class MockExpectedCall { public: MockExpectedCall(); virtual ~MockExpectedCall(); virtual MockExpectedCall& withName(const SimpleString& name)=0; virtual MockExpectedCall& withCallOrder(unsigned int)=0; virtual MockExpectedCall& withCallOrder(unsigned int, unsigned int)=0; MockExpectedCall& withParameter(const SimpleString& name, bool value) { return withBoolParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, int value) { return withIntParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, unsigned int value) { return withUnsignedIntParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, long int value) { return withLongIntParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, unsigned long int value) { return withUnsignedLongIntParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, cpputest_longlong value) { return withLongLongIntParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, cpputest_ulonglong value) { return withUnsignedLongLongIntParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, double value) { return withDoubleParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, double value, double tolerance) { return withDoubleParameter(name, value, tolerance); } MockExpectedCall& withParameter(const SimpleString& name, const char* value) { return withStringParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, void* value) { return withPointerParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, const void* value) { return withConstPointerParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, void (*value)()) { return withFunctionPointerParameter(name, value); } MockExpectedCall& withParameter(const SimpleString& name, const unsigned char* value, size_t size) { return withMemoryBufferParameter(name, value, size); } virtual MockExpectedCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value)=0; virtual MockExpectedCall& withOutputParameterReturning(const SimpleString& name, const void* value, size_t size)=0; virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString& typeName, const SimpleString& name, const void* value)=0; virtual MockExpectedCall& withUnmodifiedOutputParameter(const SimpleString& name)=0; virtual MockExpectedCall& ignoreOtherParameters()=0; virtual MockExpectedCall& withBoolParameter(const SimpleString& name, bool value)=0; virtual MockExpectedCall& withIntParameter(const SimpleString& name, int value)=0; virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value)=0; virtual MockExpectedCall& withLongIntParameter(const SimpleString& name, long int value)=0; virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value)=0; virtual MockExpectedCall& withLongLongIntParameter(const SimpleString& name, cpputest_longlong value)=0; virtual MockExpectedCall& withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value)=0; virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value)=0; virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value, double tolerance)=0; virtual MockExpectedCall& withStringParameter(const SimpleString& name, const char* value)=0; virtual MockExpectedCall& withPointerParameter(const SimpleString& name, void* value)=0; virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& name, void (*value)())=0; virtual MockExpectedCall& withConstPointerParameter(const SimpleString& name, const void* value)=0; virtual MockExpectedCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size)=0; virtual MockExpectedCall& andReturnValue(bool value)=0; virtual MockExpectedCall& andReturnValue(int value)=0; virtual MockExpectedCall& andReturnValue(unsigned int value)=0; virtual MockExpectedCall& andReturnValue(long int value)=0; virtual MockExpectedCall& andReturnValue(unsigned long int value)=0; virtual MockExpectedCall& andReturnValue(cpputest_longlong value)=0; virtual MockExpectedCall& andReturnValue(cpputest_ulonglong value)=0; virtual MockExpectedCall& andReturnValue(double value)=0; virtual MockExpectedCall& andReturnValue(const char* value)=0; virtual MockExpectedCall& andReturnValue(void* value)=0; virtual MockExpectedCall& andReturnValue(const void* value)=0; virtual MockExpectedCall& andReturnValue(void (*value)())=0; virtual MockExpectedCall& onObject(void* objectPtr)=0; }; #endif
null
132
cpp
cpputest
MockFailure.h
include/CppUTestExt/MockFailure.h
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 <organization> 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 <copyright holder> 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_MockFailure_h #define D_MockFailure_h #include "CppUTest/TestFailure.h" class MockExpectedCallsList; class MockCheckedActualCall; class MockNamedValue; class MockFailure; class MockFailureReporter { protected: bool crashOnFailure_; public: MockFailureReporter() : crashOnFailure_(false){} virtual ~MockFailureReporter() {} virtual void failTest(const MockFailure& failure); virtual UtestShell* getTestToFail(); virtual void crashOnFailure(bool shouldCrash) { crashOnFailure_ = shouldCrash; } }; class MockFailure : public TestFailure { public: MockFailure(UtestShell* test); virtual ~MockFailure() CPPUTEST_DESTRUCTOR_OVERRIDE {} protected: void addExpectationsAndCallHistory(const MockExpectedCallsList& expectations); void addExpectationsAndCallHistoryRelatedTo(const SimpleString& function, const MockExpectedCallsList& expectations); }; class MockExpectedCallsDidntHappenFailure : public MockFailure { public: MockExpectedCallsDidntHappenFailure(UtestShell* test, const MockExpectedCallsList& expectations); }; class MockUnexpectedCallHappenedFailure : public MockFailure { public: MockUnexpectedCallHappenedFailure(UtestShell* test, const SimpleString& name, const MockExpectedCallsList& expectations); }; class MockCallOrderFailure : public MockFailure { public: MockCallOrderFailure(UtestShell* test, const MockExpectedCallsList& expectations); }; class MockUnexpectedInputParameterFailure : public MockFailure { public: MockUnexpectedInputParameterFailure(UtestShell* test, const SimpleString& functionName, const MockNamedValue& parameter, const MockExpectedCallsList& expectations); }; class MockUnexpectedOutputParameterFailure : public MockFailure { public: MockUnexpectedOutputParameterFailure(UtestShell* test, const SimpleString& functionName, const MockNamedValue& parameter, const MockExpectedCallsList& expectations); }; class MockExpectedParameterDidntHappenFailure : public MockFailure { public: MockExpectedParameterDidntHappenFailure(UtestShell* test, const SimpleString& functionName, const MockExpectedCallsList& allExpectations, const MockExpectedCallsList& matchingExpectations); }; class MockNoWayToCompareCustomTypeFailure : public MockFailure { public: MockNoWayToCompareCustomTypeFailure(UtestShell* test, const SimpleString& typeName); }; class MockNoWayToCopyCustomTypeFailure : public MockFailure { public: MockNoWayToCopyCustomTypeFailure(UtestShell* test, const SimpleString& typeName); }; class MockUnexpectedObjectFailure : public MockFailure { public: MockUnexpectedObjectFailure(UtestShell* test, const SimpleString& functionName, const void* expected, const MockExpectedCallsList& expectations); }; class MockExpectedObjectDidntHappenFailure : public MockFailure { public: MockExpectedObjectDidntHappenFailure(UtestShell* test, const SimpleString& functionName, const MockExpectedCallsList& expectations); }; #endif
null
133
cpp
cpputest
MemoryReporterPlugin.h
include/CppUTestExt/MemoryReporterPlugin.h
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 <organization> 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 <copyright holder> 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_MemoryReporterPlugin_h #define D_MemoryReporterPlugin_h #include "CppUTest/TestPlugin.h" #include "CppUTestExt/MemoryReportAllocator.h" class MemoryReportFormatter; class MemoryReporterPlugin : public TestPlugin { MemoryReportFormatter* formatter_; MemoryReportAllocator mallocAllocator; MemoryReportAllocator newAllocator; MemoryReportAllocator newArrayAllocator; SimpleString currentTestGroup_; public: MemoryReporterPlugin(); virtual ~MemoryReporterPlugin() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void preTestAction(UtestShell & test, TestResult & result) CPPUTEST_OVERRIDE; virtual void postTestAction(UtestShell & test, TestResult & result) CPPUTEST_OVERRIDE; virtual bool parseArguments(int, const char *const *, int) CPPUTEST_OVERRIDE; MemoryReportAllocator* getMallocAllocator(); MemoryReportAllocator* getNewAllocator(); MemoryReportAllocator* getNewArrayAllocator(); protected: virtual MemoryReportFormatter* createMemoryFormatter(const SimpleString& type); private: void destroyMemoryFormatter(MemoryReportFormatter* formatter); void setGlobalMemoryReportAllocators(); void removeGlobalMemoryReportAllocators(); void initializeAllocator(MemoryReportAllocator* allocator, TestResult & result); }; #endif
null
134
cpp
cpputest
MockSupport.h
include/CppUTestExt/MockSupport.h
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 <organization> 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 <copyright holder> 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_MockSupport_h #define D_MockSupport_h #include "CppUTestExt/MockFailure.h" #include "CppUTestExt/MockCheckedActualCall.h" #include "CppUTestExt/MockCheckedExpectedCall.h" #include "CppUTestExt/MockExpectedCallsList.h" class UtestShell; class MockSupport; /* This allows access to "the global" mocking support for easier testing */ MockSupport& mock(const SimpleString& mockName = "", MockFailureReporter* failureReporterForThisCall = NULLPTR); class MockSupport { public: MockSupport(const SimpleString& mockName = ""); virtual ~MockSupport(); virtual void strictOrder(); virtual MockExpectedCall& expectOneCall(const SimpleString& functionName); virtual void expectNoCall(const SimpleString& functionName); virtual MockExpectedCall& expectNCalls(unsigned int amount, const SimpleString& functionName); virtual MockActualCall& actualCall(const SimpleString& functionName); virtual bool hasReturnValue(); virtual MockNamedValue returnValue(); virtual bool boolReturnValue(); virtual bool returnBoolValueOrDefault(bool defaultValue); virtual int intReturnValue(); virtual int returnIntValueOrDefault(int defaultValue); virtual unsigned int unsignedIntReturnValue(); virtual long int longIntReturnValue(); virtual long int returnLongIntValueOrDefault(long int defaultValue); virtual unsigned long int unsignedLongIntReturnValue(); virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int defaultValue); virtual cpputest_longlong longLongIntReturnValue(); virtual cpputest_longlong returnLongLongIntValueOrDefault(cpputest_longlong defaultValue); virtual cpputest_ulonglong unsignedLongLongIntReturnValue(); virtual cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong defaultValue); virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int defaultValue); virtual const char* stringReturnValue(); virtual const char* returnStringValueOrDefault(const char * defaultValue); virtual double returnDoubleValueOrDefault(double defaultValue); virtual double doubleReturnValue(); virtual void* pointerReturnValue(); virtual void* returnPointerValueOrDefault(void * defaultValue); virtual const void* returnConstPointerValueOrDefault(const void * defaultValue); virtual const void* constPointerReturnValue(); virtual void (*returnFunctionPointerValueOrDefault(void (*defaultValue)()))(); virtual void (*functionPointerReturnValue())(); bool hasData(const SimpleString& name); void setData(const SimpleString& name, bool value); void setData(const SimpleString& name, int value); void setData(const SimpleString& name, unsigned int value); void setData(const SimpleString& name, const char* value); void setData(const SimpleString& name, double value); void setData(const SimpleString& name, void* value); void setData(const SimpleString& name, const void* value); void setData(const SimpleString& name, void (*value)()); void setDataObject(const SimpleString& name, const SimpleString& type, void* value); void setDataConstObject(const SimpleString& name, const SimpleString& type, const void* value); MockNamedValue getData(const SimpleString& name); MockSupport* getMockSupportScope(const SimpleString& name); const char* getTraceOutput(); /* * The following functions are recursively through the lower MockSupports scopes * This means, if you do mock().disable() it will disable *all* mocking scopes, including mock("myScope"). */ virtual void disable(); virtual void enable(); virtual void tracing(bool enabled); virtual void ignoreOtherCalls(); virtual void checkExpectations(); virtual bool expectedCallsLeft(); virtual void clear(); virtual void crashOnFailure(bool shouldFail = true); /* * Each mock() call will set the activeReporter to standard, unless a special reporter is passed for this call. */ virtual void setMockFailureStandardReporter(MockFailureReporter* reporter); virtual void setActiveReporter(MockFailureReporter* activeReporter); virtual void setDefaultComparatorsAndCopiersRepository(); virtual void installComparator(const SimpleString& typeName, MockNamedValueComparator& comparator); virtual void installCopier(const SimpleString& typeName, MockNamedValueCopier& copier); virtual void installComparatorsAndCopiers(const MockNamedValueComparatorsAndCopiersRepository& repository); virtual void removeAllComparatorsAndCopiers(); protected: MockSupport* clone(const SimpleString& mockName); virtual MockCheckedActualCall *createActualCall(); virtual void failTest(MockFailure& failure); void countCheck(); private: unsigned int actualCallOrder_; unsigned int expectedCallOrder_; bool strictOrdering_; MockFailureReporter *activeReporter_; MockFailureReporter *standardReporter_; MockFailureReporter defaultReporter_; MockExpectedCallsList expectations_; bool ignoreOtherCalls_; bool enabled_; MockCheckedActualCall *lastActualFunctionCall_; MockNamedValueComparatorsAndCopiersRepository comparatorsAndCopiersRepository_; MockNamedValueList data_; const SimpleString mockName_; bool tracing_; void checkExpectationsOfLastActualCall(); bool wasLastActualCallFulfilled(); void failTestWithExpectedCallsNotFulfilled(); void failTestWithOutOfOrderCalls(); MockNamedValue* retrieveDataFromStore(const SimpleString& name); MockSupport* getMockSupport(MockNamedValueListNode* node); bool callIsIgnored(const SimpleString& functionName); bool hasCallsOutOfOrder(); SimpleString appendScopeToName(const SimpleString& functionName); }; #endif
null
135
cpp
cpputest
MockExpectedCallsList.h
include/CppUTestExt/MockExpectedCallsList.h
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 <organization> 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 <copyright holder> 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_MockExpectedCallsList_h #define D_MockExpectedCallsList_h class MockCheckedExpectedCall; class MockNamedValue; class MockExpectedCallsList { public: MockExpectedCallsList(); virtual ~MockExpectedCallsList(); virtual void deleteAllExpectationsAndClearList(); virtual unsigned int size() const; virtual unsigned int amountOfActualCallsFulfilledFor(const SimpleString& name) const; virtual unsigned int amountOfUnfulfilledExpectations() const; virtual bool hasUnfulfilledExpectations() const; virtual bool hasFinalizedMatchingExpectations() const; virtual bool hasUnmatchingExpectationsBecauseOfMissingParameters() const; virtual bool hasExpectationWithName(const SimpleString& name) const; virtual bool hasCallsOutOfOrder() const; virtual bool isEmpty() const; virtual void addExpectedCall(MockCheckedExpectedCall* call); virtual void addExpectations(const MockExpectedCallsList& list); virtual void addExpectationsRelatedTo(const SimpleString& name, const MockExpectedCallsList& list); virtual void onlyKeepOutOfOrderExpectations(); virtual void addPotentiallyMatchingExpectations(const MockExpectedCallsList& list); virtual void onlyKeepExpectationsRelatedTo(const SimpleString& name); virtual void onlyKeepExpectationsWithInputParameter(const MockNamedValue& parameter); virtual void onlyKeepExpectationsWithInputParameterName(const SimpleString& name); virtual void onlyKeepExpectationsWithOutputParameter(const MockNamedValue& parameter); virtual void onlyKeepExpectationsWithOutputParameterName(const SimpleString& name); virtual void onlyKeepExpectationsOnObject(const void* objectPtr); virtual void onlyKeepUnmatchingExpectations(); virtual MockCheckedExpectedCall* removeFirstFinalizedMatchingExpectation(); virtual MockCheckedExpectedCall* removeFirstMatchingExpectation(); virtual MockCheckedExpectedCall* getFirstMatchingExpectation(); virtual void resetActualCallMatchingState(); virtual void wasPassedToObject(); virtual void parameterWasPassed(const SimpleString& parameterName); virtual void outputParameterWasPassed(const SimpleString& parameterName); virtual SimpleString unfulfilledCallsToString(const SimpleString& linePrefix = "") const; virtual SimpleString fulfilledCallsToString(const SimpleString& linePrefix = "") const; virtual SimpleString callsWithMissingParametersToString(const SimpleString& linePrefix, const SimpleString& missingParametersPrefix) const; protected: virtual void pruneEmptyNodeFromList(); class MockExpectedCallsListNode { public: MockCheckedExpectedCall* expectedCall_; MockExpectedCallsListNode* next_; MockExpectedCallsListNode(MockCheckedExpectedCall* expectedCall) : expectedCall_(expectedCall), next_(NULLPTR) {} }; private: MockExpectedCallsListNode* head_; MockExpectedCallsList(const MockExpectedCallsList&); }; #endif
null
136
cpp
cpputest
MockSupportPlugin.h
include/CppUTestExt/MockSupportPlugin.h
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 <organization> 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 <copyright holder> 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_MockSupportPlugin_h #define D_MockSupportPlugin_h #include "CppUTest/TestPlugin.h" #include "CppUTestExt/MockNamedValue.h" class MockSupportPlugin : public TestPlugin { public: MockSupportPlugin(const SimpleString& name = "MockSupportPLugin"); virtual ~MockSupportPlugin() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void preTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE; virtual void postTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE; virtual void installComparator(const SimpleString& name, MockNamedValueComparator& comparator); virtual void installCopier(const SimpleString& name, MockNamedValueCopier& copier); void clear(); private: MockNamedValueComparatorsAndCopiersRepository repository_; }; #endif
null
137
cpp
cpputest
stdint.h
include/Platforms/c2000/stdint.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde * and Arnd R. Strube * 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 <organization> 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 <copyright holder> 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 stdint_wrapper_h #define stdint_wrapper_h #include <stdint.h> typedef unsigned char uint8_t; /* This will still compile to 16 bit */ #endif /* stdint_wrapper_h */
null
138
cpp
cpputest
ClassNameCTest.cpp
scripts/UnityTemplates/ClassNameCTest.cpp
null
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"); }
null
139
cpp
cpputest
FunctionNameCTest.cpp
scripts/UnityTemplates/FunctionNameCTest.cpp
null
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"); }
null
140
cpp
cpputest
InterfaceCTest.cpp
scripts/UnityTemplates/InterfaceCTest.cpp
null
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"); }
null
141
cpp
cpputest
ClassNameCIoDriverTest.cpp
scripts/UnityTemplates/ClassNameCIoDriverTest.cpp
null
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"); }
null
142
cpp
cpputest
ClassNameCMultipleInstanceTest.cpp
scripts/UnityTemplates/ClassNameCMultipleInstanceTest.cpp
null
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"); }
null
143
cpp
cpputest
MockClassName.h
scripts/CppUnitTemplates/MockClassName.h
null
#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
null
144
cpp
cpputest
ClassNameCTest.cpp
scripts/CppUnitTemplates/ClassNameCTest.cpp
null
#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"); }
null
145
cpp
cpputest
ClassNameTest.cpp
scripts/CppUnitTemplates/ClassNameTest.cpp
null
#include <cppunit/config/SourcePrefix.h> #include <cppunit/extensions/HelperMacros.h> #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);
null
146
cpp
cpputest
InterfaceCTest.cpp
scripts/CppUnitTemplates/InterfaceCTest.cpp
null
#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"); }
null
147
cpp
cpputest
ClassName.cpp
scripts/CppUnitTemplates/ClassName.cpp
null
#include "ClassName.h" ClassName::ClassName() { } ClassName::~ClassName() { }
null
148
cpp
cpputest
ClassNameC.h
scripts/CppUnitTemplates/ClassNameC.h
null
#ifndef D_ClassName_H #define D_ClassName_H /////////////////////////////////////////////////////////////////////////////// // // ClassName is responsible for ... // /////////////////////////////////////////////////////////////////////////////// void ClassName_Create(void); void ClassName_Destroy(void); #endif // D_ClassName_H
null
149
cpp
cpputest
MockClassNameC.h
scripts/CppUnitTemplates/MockClassNameC.h
null
#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
null
150
cpp
cpputest
ClassName.h
scripts/CppUnitTemplates/ClassName.h
null
#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
null
151
cpp
cpputest
ClassNameCMultipleInstance.h
scripts/CppUnitTemplates/ClassNameCMultipleInstance.h
null
#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
null
152
cpp
cpputest
ClassNameCMultipleInstanceTest.cpp
scripts/CppUnitTemplates/ClassNameCMultipleInstanceTest.cpp
null
#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"); }
null
153
cpp
cpputest
ClassNameCPolymorphic.h
scripts/CppUnitTemplates/ClassNameCPolymorphic.h
null
#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
null
154
cpp
cpputest
InterfaceTest.cpp
scripts/CppUnitTemplates/InterfaceTest.cpp
null
#include <cppunit/config/SourcePrefix.h> #include <cppunit/extensions/HelperMacros.h> #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);
null
155
cpp
cpputest
AllTests.cpp
scripts/CppUnitTemplates/ProjectTemplate/tests/AllTests.cpp
null
#include "CppUTest/CommandLineTestRunner.h" int main(int ac, char** av) { return CommandLineTestRunner::RunAllTests(ac, av); }
null
156
cpp
cpputest
ProjectBuildTimeTest.cpp
scripts/CppUnitTemplates/ProjectTemplate/tests/util/ProjectBuildTimeTest.cpp
null
#include "CppUTest/TestHarness.h" #include "ProjectBuildTime.h" TEST_GROUP(ProjectBuildTime) { ProjectBuildTime* projectBuildTime; void setup() { projectBuildTime = new ProjectBuildTime(); } void teardown() { delete projectBuildTime; } }; TEST(ProjectBuildTime, Create) { CHECK(0 != projectBuildTime->GetDateTime()); }
null
157
cpp
cpputest
ProjectBuildTime.h
scripts/CppUnitTemplates/ProjectTemplate/include/util/ProjectBuildTime.h
null
#ifndef D_ProjectBuildTime_H #define D_ProjectBuildTime_H /////////////////////////////////////////////////////////////////////////////// // // ProjectBuildTime is responsible for recording and reporting when // this project library was built // /////////////////////////////////////////////////////////////////////////////// class ProjectBuildTime { public: explicit ProjectBuildTime(); virtual ~ProjectBuildTime(); const char* GetDateTime(); private: const char* dateTime; ProjectBuildTime(const ProjectBuildTime&); ProjectBuildTime& operator=(const ProjectBuildTime&); }; #endif // D_ProjectBuildTime_H
null
158
cpp
cpputest
ProjectBuildTime.cpp
scripts/CppUnitTemplates/ProjectTemplate/src/util/ProjectBuildTime.cpp
null
#include "ProjectBuildTime.h" ProjectBuildTime::ProjectBuildTime() : dateTime(__DATE__ " " __TIME__) { } ProjectBuildTime::~ProjectBuildTime() { } const char* ProjectBuildTime::GetDateTime() { return dateTime; }
null
159
cpp
cpputest
ClassNameCIoDriver.h
scripts/templates/ClassNameCIoDriver.h
null
#ifndef D_ClassName_H #define D_ClassName_H /********************************************************** * * ClassName is responsible for ... * **********************************************************/ #include <stdint.h> void ClassName_Create(void); void ClassName_Destroy(void); #endif /* D_FakeClassName_H */
null
160
cpp
cpputest
MockClassName.h
scripts/templates/MockClassName.h
null
#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
null
161
cpp
cpputest
ClassNameCTest.cpp
scripts/templates/ClassNameCTest.cpp
null
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"); }
null
162
cpp
cpputest
ClassNameTest.cpp
scripts/templates/ClassNameTest.cpp
null
#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"); }
null
163
cpp
cpputest
FunctionNameCTest.cpp
scripts/templates/FunctionNameCTest.cpp
null
extern "C" { #include "ClassName.h" } #include "CppUTest/TestHarness.h" TEST_GROUP(ClassName) { void setup() { } void teardown() { } }; TEST(ClassName, Create) { FAIL("Start here"); }
null
164
cpp
cpputest
InterfaceCTest.cpp
scripts/templates/InterfaceCTest.cpp
null
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"); }
null
165
cpp
cpputest
ClassName.cpp
scripts/templates/ClassName.cpp
null
#include "ClassName.h" ClassName::ClassName() { } ClassName::~ClassName() { }
null
166
cpp
cpputest
ClassNameC.h
scripts/templates/ClassNameC.h
null
#ifndef D_ClassName_H #define D_ClassName_H /********************************************************** * * ClassName is responsible for ... * **********************************************************/ void ClassName_Create(void); void ClassName_Destroy(void); #endif /* D_FakeClassName_H */
null
167
cpp
cpputest
MockClassNameC.h
scripts/templates/MockClassNameC.h
null
#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 */
null
168
cpp
cpputest
ClassNameCIoDriverTest.cpp
scripts/templates/ClassNameCIoDriverTest.cpp
null
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"); }
null
169
cpp
cpputest
ClassName.h
scripts/templates/ClassName.h
null
#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
null
170
cpp
cpputest
ClassNameCMultipleInstance.h
scripts/templates/ClassNameCMultipleInstance.h
null
#ifndef D_ClassName_H #define D_ClassName_H /********************************************************************** * * ClassName is responsible for ... * **********************************************************************/ typedef struct ClassNameStruct * ClassName; ClassName ClassName_Create(void); void ClassName_Destroy(ClassName); #endif /* D_FakeClassName_H */
null
171
cpp
cpputest
FunctionNameC.h
scripts/templates/FunctionNameC.h
null
#ifndef D_ClassName_H #define D_ClassName_H /********************************************************** * * ClassName is responsible for ... * **********************************************************/ void ClassName(); #endif /* D_FakeClassName_H */
null
172
cpp
cpputest
ClassNameCMultipleInstanceTest.cpp
scripts/templates/ClassNameCMultipleInstanceTest.cpp
null
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"); }
null
173
cpp
cpputest
ClassNameCPolymorphic.h
scripts/templates/ClassNameCPolymorphic.h
null
#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 */
null
174
cpp
cpputest
InterfaceTest.cpp
scripts/templates/InterfaceTest.cpp
null
#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"); }
null
175
cpp
cpputest
AllTests.cpp
scripts/templates/ProjectTemplate/tests/AllTests.cpp
null
#include "CppUTest/CommandLineTestRunner.h" int main(int ac, char** av) { return CommandLineTestRunner::RunAllTests(ac, av); }
null
176
cpp
cpputest
ProjectBuildTimeTest.cpp
scripts/templates/ProjectTemplate/tests/util/ProjectBuildTimeTest.cpp
null
#include "CppUTest/TestHarness.h" #include "ProjectBuildTime.h" TEST_GROUP(ProjectBuildTime) { ProjectBuildTime* projectBuildTime; void setup() { projectBuildTime = new ProjectBuildTime(); } void teardown() { delete projectBuildTime; } }; TEST(ProjectBuildTime, Create) { CHECK(0 != projectBuildTime->GetDateTime()); }
null
177
cpp
cpputest
ProjectBuildTime.h
scripts/templates/ProjectTemplate/include/util/ProjectBuildTime.h
null
#ifndef D_ProjectBuildTime_H #define D_ProjectBuildTime_H /////////////////////////////////////////////////////////////////////////////// // // ProjectBuildTime is responsible for recording and reporting when // this project library was built // /////////////////////////////////////////////////////////////////////////////// class ProjectBuildTime { public: explicit ProjectBuildTime(); virtual ~ProjectBuildTime(); const char* GetDateTime(); private: const char* dateTime; ProjectBuildTime(const ProjectBuildTime&); ProjectBuildTime& operator=(const ProjectBuildTime&); }; #endif // D_ProjectBuildTime_H
null
178
cpp
cpputest
ProjectBuildTime.cpp
scripts/templates/ProjectTemplate/src/util/ProjectBuildTime.cpp
null
#include "ProjectBuildTime.h" ProjectBuildTime::ProjectBuildTime() : dateTime(__DATE__ " " __TIME__) { } ProjectBuildTime::~ProjectBuildTime() { } const char* ProjectBuildTime::GetDateTime() { return dateTime; }
null
179
cpp
cpputest
main.cpp
platforms_examples/armcc/AT91SAM7A3/tests/main.cpp
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 <organization> 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 <copyright holder> 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, char** av) { return RUN_ALL_TESTS(ac, av); }
null
180
cpp
cpputest
test1.cpp
platforms_examples/armcc/LPC1833/tests/test1.cpp
null
#include "CppUTest/TestHarness.h" TEST_GROUP(start) { }; TEST(start, first) { FAIL("Start here!"); }
null
181
cpp
cpputest
main.cpp
platforms_examples/armcc/LPC1833/tests/main.cpp
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 <organization> 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 <copyright holder> 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); }
null
182
cpp
cpputest
main.cpp
platforms_examples/armcc/LPC1768/tests/main.cpp
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 <organization> 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 <copyright holder> 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 <iostream> #include <cstdint> extern "C" void _clock_init(void); extern std::uint32_t SystemCoreClock; extern const std::uint32_t SystemCoreClock12; int main(int ac, char** av) { SystemCoreClock = SystemCoreClock12; /* if 12 MHz quartz is used; need to LPC_TIM3 measure */ _clock_init(); /* secondary call for new SystemCoreClock freq; previous call worked with unknown value */ std::cout << "Hello, World!\n"; int result = RUN_ALL_TESTS(ac, av); return result; }
null
183
cpp
cpputest
CommandLineTestRunner.cpp
src/CppUTest/CommandLineTestRunner.cpp
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 <organization> 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 <copyright holder> 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/TeamCityTestOutput.h" #include "CppUTest/TestRegistry.h" int CommandLineTestRunner::RunAllTests(int ac, char** av) { return RunAllTests(ac, (const char *const *) av); } int CommandLineTestRunner::RunAllTests(int ac, const char *const *av) { int result = 0; ConsoleTestOutput backupOutput; MemoryLeakWarningPlugin memLeakWarn(DEF_PLUGIN_MEM_LEAK); memLeakWarn.destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(true); TestRegistry::getCurrentRegistry()->installPlugin(&memLeakWarn); { CommandLineTestRunner runner(ac, av, TestRegistry::getCurrentRegistry()); result = runner.runAllTestsMain(); } if (result == 0) { backupOutput << memLeakWarn.FinalReport(0); } TestRegistry::getCurrentRegistry()->removePluginByName(DEF_PLUGIN_MEM_LEAK); return result; } CommandLineTestRunner::CommandLineTestRunner(int ac, const char *const *av, TestRegistry* registry) : output_(NULLPTR), arguments_(NULLPTR), registry_(registry) { arguments_ = new CommandLineArguments(ac, av); } CommandLineTestRunner::~CommandLineTestRunner() { delete arguments_; delete output_; } int CommandLineTestRunner::runAllTestsMain() { int testResult = 1; 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_->setGroupFilters(arguments_->getGroupFilters()); registry_->setNameFilters(arguments_->getNameFilters()); if (arguments_->isVerbose()) output_->verbose(TestOutput::level_verbose); if (arguments_->isVeryVerbose()) output_->verbose(TestOutput::level_veryVerbose); if (arguments_->isColor()) output_->color(); if (arguments_->runTestsInSeperateProcess()) registry_->setRunTestsInSeperateProcess(); if (arguments_->isRunIgnored()) registry_->setRunIgnored(); if (arguments_->isCrashingOnFail()) UtestShell::setCrashOnFail(); UtestShell::setRethrowExceptions( arguments_->isRethrowingExceptions() ); } int CommandLineTestRunner::runAllTests() { initializeTestRun(); size_t loopCount = 0; size_t failedTestCount = 0; size_t failedExecutionCount = 0; size_t repeatCount = arguments_->getRepeatCount(); if (arguments_->isListingTestGroupNames()) { TestResult tr(*output_); registry_->listTestGroupNames(tr); return 0; } if (arguments_->isListingTestGroupAndCaseNames()) { TestResult tr(*output_); registry_->listTestGroupAndCaseNames(tr); return 0; } if (arguments_->isListingTestLocations()) { TestResult tr(*output_); registry_->listTestLocations(tr); return 0; } if (arguments_->isReversing()) registry_->reverseTests(); if (arguments_->isShuffling()) { output_->print("Test order shuffling enabled with seed: "); output_->print(arguments_->getShuffleSeed()); output_->print("\n"); } while (loopCount++ < repeatCount) { if (arguments_->isShuffling()) registry_->shuffleTests(arguments_->getShuffleSeed()); output_->printTestRun(loopCount, repeatCount); TestResult tr(*output_); registry_->runAllTests(tr); failedTestCount += tr.getFailureCount(); if (tr.isFailure()) { failedExecutionCount++; } } return (int) (failedTestCount != 0 ? failedTestCount : failedExecutionCount); } TestOutput* CommandLineTestRunner::createTeamCityOutput() { return new TeamCityTestOutput; } TestOutput* CommandLineTestRunner::createJUnitOutput(const SimpleString& packageName) { JUnitTestOutput* junitOutput = new JUnitTestOutput; if (junitOutput != NULLPTR) { junitOutput->setPackageName(packageName); } return junitOutput; } TestOutput* CommandLineTestRunner::createConsoleOutput() { return new ConsoleTestOutput; } TestOutput* CommandLineTestRunner::createCompositeOutput(TestOutput* outputOne, TestOutput* outputTwo) { CompositeTestOutput* composite = new CompositeTestOutput; composite->setOutputOne(outputOne); composite->setOutputTwo(outputTwo); return composite; } bool CommandLineTestRunner::parseArguments(TestPlugin* plugin) { if (!arguments_->parse(plugin)) { output_ = createConsoleOutput(); output_->print((arguments_->needHelp()) ? arguments_->help() : arguments_->usage()); return false; } if (arguments_->isJUnitOutput()) { output_= createJUnitOutput(arguments_->getPackageName()); if (arguments_->isVerbose() || arguments_->isVeryVerbose()) output_ = createCompositeOutput(output_, createConsoleOutput()); } else if (arguments_->isTeamCityOutput()) { output_ = createTeamCityOutput(); } else output_ = createConsoleOutput(); return true; }
null
184
cpp
cpputest
TestPlugin.cpp
src/CppUTest/TestPlugin.cpp
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 <organization> 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 <copyright holder> 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<const char *const *> (av), index); } bool TestPlugin::parseAllArguments(int ac, const char *const *av, int index) { if (parseArguments(ac, av, index)) return true; if (next_) return next_->parseAllArguments(ac, av, index); 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 = NULLPTR; 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; } 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(NULLPTR) { } NullTestPlugin* NullTestPlugin::instance() { static NullTestPlugin _instance; return &_instance; } void NullTestPlugin::runAllPreTestAction(UtestShell&, TestResult&) { } void NullTestPlugin::runAllPostTestAction(UtestShell&, TestResult&) { }
null
185
cpp
cpputest
SimpleMutex.cpp
src/CppUTest/SimpleMutex.cpp
null
/* * Copyright (c) 2014, Michael Feathers, James Grenning, Bas Vodde and Chen YewMing * 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 <organization> 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 <copyright holder> 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/SimpleMutex.h" SimpleMutex::SimpleMutex(void) { psMtx = PlatformSpecificMutexCreate(); } SimpleMutex::~SimpleMutex(void) { PlatformSpecificMutexDestroy(psMtx); } void SimpleMutex::Lock(void) { PlatformSpecificMutexLock(psMtx); } void SimpleMutex::Unlock(void) { PlatformSpecificMutexUnlock(psMtx); } ScopedMutexLock::ScopedMutexLock(SimpleMutex *mtx) : mutex(mtx) { mutex->Lock(); } ScopedMutexLock::~ScopedMutexLock() { mutex->Unlock(); }
null
186
cpp
cpputest
TestFailure.cpp
src/CppUTest/TestFailure.cpp
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 <organization> 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 <copyright holder> 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/SimpleString.h" #include "CppUTest/PlatformSpecificFunctions.h" #if CPPUTEST_USE_STD_CPP_LIB #include <typeinfo> #if defined(__GNUC__) #include <cxxabi.h> #include <memory> #endif #endif TestFailure::TestFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& theMessage) : testName_(test->getFormattedName()), testNameOnly_(test->getName()), fileName_(fileName), lineNumber_(lineNumber), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_(theMessage) { } TestFailure::TestFailure(UtestShell* test, const SimpleString& theMessage) : testName_(test->getFormattedName()), testNameOnly_(test->getName()), fileName_(test->getFile()), lineNumber_(test->getLineNumber()), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_(theMessage) { } TestFailure::TestFailure(UtestShell* test, const char* fileName, size_t lineNum) : testName_(test->getFormattedName()), testNameOnly_(test->getName()), fileName_(fileName), lineNumber_(lineNum), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_("no message") { } TestFailure::TestFailure(const TestFailure& f) : testName_(f.testName_), testNameOnly_(f.testNameOnly_), 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_; } SimpleString TestFailure::getTestNameOnly() const { return testNameOnly_; } size_t TestFailure::getFailureLineNumber() const { return lineNumber_; } size_t 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 offset, size_t reportedPosition) { 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) reportedPosition); result += "\n"; result += StringFromFormat("\t%s%s>\n", differentString.asCharString(), actualString.subString(offset, extraCharactersWindow).asCharString()); result += StringFromFormat("\t%s^", SimpleString(" ", (differentString.size() + halfOfExtraCharactersWindow)).asCharString()); return result; } SimpleString TestFailure::createUserText(const SimpleString& text) { SimpleString userMessage = ""; if (!text.isEmpty()) { //This is a kludge to turn off "Message: " for this case. //I don't think "Message: " adds anything, as you get to see the //message. I propose we remove "Message: " lead in if (!text.startsWith("LONGS_EQUAL")) userMessage += "Message: "; userMessage += text; userMessage += "\n\t"; } return userMessage; } EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += createButWasString(StringFromOrNull(expected), StringFromOrNull(actual)); } EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += createButWasString(expected, actual); } DoublesEqualFailure::DoublesEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, double expected, double actual, double threshold, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += createButWasString(StringFrom(expected, 7), StringFrom(actual, 7)); message_ += " threshold used was <"; message_ += StringFrom(threshold, 7); message_ += ">"; if (PlatformSpecificIsNan(expected) || PlatformSpecificIsNan(actual) || PlatformSpecificIsNan(threshold)) message_ += "\n\tCannot make comparisons with Nan"; } CheckEqualFailure::CheckEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString printableExpected = PrintableStringFromOrNull(expected.asCharString()); SimpleString printableActual = PrintableStringFromOrNull(actual.asCharString()); message_ += createButWasString(printableExpected, printableActual); size_t failStart; for (failStart = 0; actual.at(failStart) == expected.at(failStart); failStart++) ; size_t failStartPrintable; for (failStartPrintable = 0; printableActual.at(failStartPrintable) == printableExpected.at(failStartPrintable); failStartPrintable++) ; message_ += createDifferenceAtPosString(printableActual, failStartPrintable, failStart); } ComparisonFailure::ComparisonFailure(UtestShell *test, const char *fileName, size_t lineNumber, const SimpleString& checkString, const SimpleString &comparisonString, const SimpleString &text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += checkString; message_ += "("; message_ += comparisonString; message_ += ") failed"; } ContainsFailure::ContainsFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += StringFromFormat("actual <%s>\n\tdid not contain <%s>", actual.asCharString(), expected.asCharString()); } CheckFailure::CheckFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& checkString, const SimpleString& conditionString, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += checkString; message_ += "("; message_ += conditionString; message_ += ") failed"; } FailFailure::FailFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& message) : TestFailure(test, fileName, lineNumber) { message_ = message; } LongsEqualFailure::LongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, long expected, long actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); SimpleString eDecimal = StringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString actualReported = aDecimal + " " + BracketsFormattedHexStringFrom(actual); SimpleString expectedReported = eDecimal + " " + BracketsFormattedHexStringFrom(expected); message_ += createButWasString(expectedReported, actualReported); } UnsignedLongsEqualFailure::UnsignedLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, unsigned long expected, unsigned long actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); SimpleString eDecimal = StringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString actualReported = aDecimal + " " + BracketsFormattedHexStringFrom(actual); SimpleString expectedReported = eDecimal + " " + BracketsFormattedHexStringFrom(expected); message_ += createButWasString(expectedReported, actualReported); } LongLongsEqualFailure::LongLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, cpputest_longlong expected, cpputest_longlong actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); SimpleString eDecimal = StringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString actualReported = aDecimal + " " + BracketsFormattedHexStringFrom(actual); SimpleString expectedReported = eDecimal + " " + BracketsFormattedHexStringFrom(expected); message_ += createButWasString(expectedReported, actualReported); } UnsignedLongLongsEqualFailure::UnsignedLongLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, cpputest_ulonglong expected, cpputest_ulonglong actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); SimpleString eDecimal = StringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString actualReported = aDecimal + " " + BracketsFormattedHexStringFrom(actual); SimpleString expectedReported = eDecimal + " " + BracketsFormattedHexStringFrom(expected); message_ += createButWasString(expectedReported, actualReported); } SignedBytesEqualFailure::SignedBytesEqualFailure (UtestShell* test, const char* fileName, size_t lineNumber, signed char expected, signed char actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom((int)actual); SimpleString eDecimal = StringFrom((int)expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString actualReported = aDecimal + " " + BracketsFormattedHexStringFrom(actual); SimpleString expectedReported = eDecimal + " " + BracketsFormattedHexStringFrom(expected); message_ += createButWasString(expectedReported, actualReported); } StringEqualFailure::StringEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString printableExpected = PrintableStringFromOrNull(expected); SimpleString printableActual = PrintableStringFromOrNull(actual); message_ += createButWasString(printableExpected, printableActual); if((expected) && (actual)) { size_t failStart; for (failStart = 0; actual[failStart] == expected[failStart]; failStart++) ; size_t failStartPrintable; for (failStartPrintable = 0; printableActual.at(failStartPrintable) == printableExpected.at(failStartPrintable); failStartPrintable++) ; message_ += createDifferenceAtPosString(printableActual, failStartPrintable, failStart); } } StringEqualNoCaseFailure::StringEqualNoCaseFailure(UtestShell* test, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString printableExpected = PrintableStringFromOrNull(expected); SimpleString printableActual = PrintableStringFromOrNull(actual); message_ += createButWasString(printableExpected, printableActual); if((expected) && (actual)) { size_t failStart; for (failStart = 0; SimpleString::ToLower(actual[failStart]) == SimpleString::ToLower(expected[failStart]); failStart++) ; size_t failStartPrintable; for (failStartPrintable = 0; SimpleString::ToLower(printableActual.at(failStartPrintable)) == SimpleString::ToLower(printableExpected.at(failStartPrintable)); failStartPrintable++) ; message_ += createDifferenceAtPosString(printableActual, failStartPrintable, failStart); } } BinaryEqualFailure::BinaryEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const unsigned char* expected, const unsigned char* actual, size_t size, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString actualHex = StringFromBinaryOrNull(actual, size); message_ += createButWasString(StringFromBinaryOrNull(expected, size), actualHex); if ((expected) && (actual)) { size_t failStart; for (failStart = 0; actual[failStart] == expected[failStart]; failStart++) ; message_ += createDifferenceAtPosString(actualHex, (failStart * 3 + 1), failStart); } } BitsEqualFailure::BitsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += createButWasString(StringFromMaskedBits(expected, mask, byteCount), StringFromMaskedBits(actual, mask, byteCount)); } FeatureUnsupportedFailure::FeatureUnsupportedFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& featureName, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += StringFromFormat("The feature \"%s\" is not supported in this environment or with the feature set selected when building the library.", featureName.asCharString()); } #if CPPUTEST_HAVE_EXCEPTIONS UnexpectedExceptionFailure::UnexpectedExceptionFailure(UtestShell* test) : TestFailure(test, "Unexpected exception of unknown type was thrown.") { } #if CPPUTEST_USE_STD_CPP_LIB #if CPPUTEST_HAVE_RTTI static SimpleString getExceptionTypeName(const std::exception &e) { const char *name = typeid(e).name(); #if defined(__GNUC__) && (__cplusplus >= 201103L) int status = -1; std::unique_ptr<char, void(*)(void*)> demangledName( abi::__cxa_demangle(name, NULLPTR, NULLPTR, &status), std::free ); return (status==0) ? demangledName.get() : name; #else return name; #endif } #endif // CPPUTEST_HAVE_RTTI UnexpectedExceptionFailure::UnexpectedExceptionFailure(UtestShell* test, const std::exception &e) : TestFailure( test, #if CPPUTEST_HAVE_RTTI StringFromFormat( "Unexpected exception of type '%s' was thrown: %s", getExceptionTypeName(e).asCharString(), e.what() ) #else "Unexpected exception of unknown type was thrown." #endif ) { (void) e; } #endif // CPPUTEST_USE_STD_CPP_LIB #endif // CPPUTEST_HAVE_EXCEPTIONS
null
187
cpp
cpputest
MemoryLeakWarningPlugin.cpp
src/CppUTest/MemoryLeakWarningPlugin.cpp
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 <organization> 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 <copyright holder> 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" #include "CppUTest/SimpleMutex.h" /********** Enabling and disabling for C also *********/ #if CPPUTEST_USE_MEM_LEAK_DETECTION class MemLeakScopedMutex { public: MemLeakScopedMutex() : lock(MemoryLeakWarningPlugin::getGlobalDetector()->getMutex()) { } private: ScopedMutexLock lock; }; static void* threadsafe_mem_leak_malloc(size_t size, const char* file, size_t line) { MemLeakScopedMutex lock; return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentMallocAllocator(), size, file, line, true); } static void threadsafe_mem_leak_free(void* buffer, const char* file, size_t line) { MemLeakScopedMutex lock; MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) buffer); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentMallocAllocator(), (char*) buffer, file, line, true); } static void* threadsafe_mem_leak_realloc(void* memory, size_t size, const char* file, size_t line) { MemLeakScopedMutex lock; return MemoryLeakWarningPlugin::getGlobalDetector()->reallocMemory(getCurrentMallocAllocator(), (char*) memory, size, file, line, true); } static void* mem_leak_malloc(size_t size, const char* file, size_t line) { return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentMallocAllocator(), size, file, line, true); } static void mem_leak_free(void* buffer, const char* file, size_t line) { MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) buffer); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentMallocAllocator(), (char*) buffer, file, line, true); } static void* mem_leak_realloc(void* memory, size_t size, const char* file, size_t line) { return MemoryLeakWarningPlugin::getGlobalDetector()->reallocMemory(getCurrentMallocAllocator(), (char*) memory, size, file, line, true); } #endif static void* normal_malloc(size_t size, const char*, size_t) { return PlatformSpecificMalloc(size); } static void* normal_realloc(void* memory, size_t size, const char*, size_t) { return PlatformSpecificRealloc(memory, size); } static void normal_free(void* buffer, const char*, size_t) { PlatformSpecificFree(buffer); } #if CPPUTEST_USE_MEM_LEAK_DETECTION static void *(*malloc_fptr)(size_t size, const char* file, size_t line) = mem_leak_malloc; static void (*free_fptr)(void* mem, const char* file, size_t line) = mem_leak_free; static void*(*realloc_fptr)(void* memory, size_t size, const char* file, size_t line) = mem_leak_realloc; static void *(*saved_malloc_fptr)(size_t size, const char* file, size_t line) = mem_leak_malloc; static void (*saved_free_fptr)(void* mem, const char* file, size_t line) = mem_leak_free; static void*(*saved_realloc_fptr)(void* memory, size_t size, const char* file, size_t line) = mem_leak_realloc; #else static void *(*malloc_fptr)(size_t size, const char* file, size_t line) = normal_malloc; static void (*free_fptr)(void* mem, const char* file, size_t line) = normal_free; static void*(*realloc_fptr)(void* memory, size_t size, const char* file, size_t line) = normal_realloc; #endif void* cpputest_malloc_location_with_leak_detection(size_t size, const char* file, size_t line) { return malloc_fptr(size, file, line); } void* cpputest_realloc_location_with_leak_detection(void* memory, size_t size, const char* file, size_t line) { return realloc_fptr(memory, size, file, line); } void cpputest_free_location_with_leak_detection(void* buffer, const char* file, size_t line) { free_fptr(buffer, file, line); } /********** C++ *************/ #if CPPUTEST_USE_MEM_LEAK_DETECTION #undef new #if CPPUTEST_HAVE_EXCEPTIONS #define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) if ((memory) == NULLPTR) throw CPPUTEST_BAD_ALLOC() #else #define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) #endif static void* threadsafe_mem_leak_operator_new (size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { MemLeakScopedMutex lock; void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* threadsafe_mem_leak_operator_new_nothrow (size_t size) UT_NOTHROW { MemLeakScopedMutex lock; return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size); } static void* threadsafe_mem_leak_operator_new_debug (size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { MemLeakScopedMutex lock; void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size, file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* threadsafe_mem_leak_operator_new_array (size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { MemLeakScopedMutex lock; void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* threadsafe_mem_leak_operator_new_array_nothrow (size_t size) UT_NOTHROW { MemLeakScopedMutex lock; return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size); } static void* threadsafe_mem_leak_operator_new_array_debug (size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { MemLeakScopedMutex lock; void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void threadsafe_mem_leak_operator_delete (void* mem) UT_NOTHROW { MemLeakScopedMutex lock; MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewAllocator(), (char*) mem); } static void threadsafe_mem_leak_operator_delete_array (void* mem) UT_NOTHROW { MemLeakScopedMutex lock; MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewArrayAllocator(), (char*) mem); } static void* mem_leak_operator_new (size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); 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, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size, file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* mem_leak_operator_new_array (size_t size) UT_THROW(CPPUTEST_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, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, 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(CPPUTEST_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*/, size_t /*line*/) UT_THROW(CPPUTEST_BAD_ALLOC) { void* memory = PlatformSpecificMalloc(size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* normal_operator_new_array (size_t size) UT_THROW(CPPUTEST_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*/, size_t /*line*/) UT_THROW(CPPUTEST_BAD_ALLOC) { void* memory = PlatformSpecificMalloc(size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void normal_operator_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(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new; static void *(*operator_new_nothrow_fptr)(size_t size) UT_NOTHROW = mem_leak_operator_new_nothrow; static void *(*operator_new_debug_fptr)(size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_debug; static void *(*operator_new_array_fptr)(size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_array; static void *(*operator_new_array_nothrow_fptr)(size_t size) UT_NOTHROW = mem_leak_operator_new_array_nothrow; static void *(*operator_new_array_debug_fptr)(size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_array_debug; static void (*operator_delete_fptr)(void* mem) UT_NOTHROW = mem_leak_operator_delete; static void (*operator_delete_array_fptr)(void* mem) UT_NOTHROW = mem_leak_operator_delete_array; static void *(*saved_operator_new_fptr)(size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new; static void *(*saved_operator_new_nothrow_fptr)(size_t size) UT_NOTHROW = mem_leak_operator_new_nothrow; static void *(*saved_operator_new_debug_fptr)(size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_debug; static void *(*saved_operator_new_array_fptr)(size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_array; static void *(*saved_operator_new_array_nothrow_fptr)(size_t size) UT_NOTHROW = mem_leak_operator_new_array_nothrow; static void *(*saved_operator_new_array_debug_fptr)(size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) = mem_leak_operator_new_array_debug; static void (*saved_operator_delete_fptr)(void* mem) UT_NOTHROW = mem_leak_operator_delete; static void (*saved_operator_delete_array_fptr)(void* mem) UT_NOTHROW = mem_leak_operator_delete_array; static int save_counter = 0; void* operator new(size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { return operator_new_fptr(size); } void* operator new(size_t size, const char* file, int line) UT_THROW(CPPUTEST_BAD_ALLOC) { return operator_new_debug_fptr(size, file, (size_t)line); } void* operator new(size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { return operator_new_debug_fptr(size, file, line); } 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 delete(void* mem, const char*, size_t) UT_NOTHROW { operator_delete_fptr(mem); } #if __cplusplus >= 201402L void operator delete (void* mem, size_t) UT_NOTHROW { operator_delete_fptr(mem); } #endif void* operator new[](size_t size) UT_THROW(CPPUTEST_BAD_ALLOC) { return operator_new_array_fptr(size); } void* operator new [](size_t size, const char* file, int line) UT_THROW(CPPUTEST_BAD_ALLOC) { return operator_new_array_debug_fptr(size, file, (size_t)line); } void* operator new [](size_t size, const char* file, size_t line) UT_THROW(CPPUTEST_BAD_ALLOC) { return operator_new_array_debug_fptr(size, file, line); } 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); } void operator delete[](void* mem, const char*, size_t) UT_NOTHROW { operator_delete_array_fptr(mem); } #if __cplusplus >= 201402L void operator delete[] (void* mem, size_t) UT_NOTHROW { operator_delete_array_fptr(mem); } #endif #if CPPUTEST_USE_STD_CPP_LIB void* operator new(size_t size, const std::nothrow_t&) UT_NOTHROW { return operator_new_nothrow_fptr(size); } void operator delete(void* mem, const std::nothrow_t&) UT_NOTHROW { operator_delete_fptr(mem); } void* operator new[](size_t size, const std::nothrow_t&) UT_NOTHROW { return operator_new_array_nothrow_fptr(size); } void operator delete[](void* mem, const std::nothrow_t&) UT_NOTHROW { operator_delete_array_fptr(mem); } #else /* Have a similar method. This avoid unused operator_new_nothrow_fptr warning */ 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::turnOnDefaultNotThreadSafeNewDeleteOverloads() { #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 MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads() { #if CPPUTEST_USE_MEM_LEAK_DETECTION operator_new_fptr = threadsafe_mem_leak_operator_new; operator_new_nothrow_fptr = threadsafe_mem_leak_operator_new_nothrow; operator_new_debug_fptr = threadsafe_mem_leak_operator_new_debug; operator_new_array_fptr = threadsafe_mem_leak_operator_new_array; operator_new_array_nothrow_fptr = threadsafe_mem_leak_operator_new_array_nothrow; operator_new_array_debug_fptr = threadsafe_mem_leak_operator_new_array_debug; operator_delete_fptr = threadsafe_mem_leak_operator_delete; operator_delete_array_fptr = threadsafe_mem_leak_operator_delete_array; malloc_fptr = threadsafe_mem_leak_malloc; realloc_fptr = threadsafe_mem_leak_realloc; free_fptr = threadsafe_mem_leak_free; #endif } bool MemoryLeakWarningPlugin::areNewDeleteOverloaded() { #if CPPUTEST_USE_MEM_LEAK_DETECTION return operator_new_fptr == mem_leak_operator_new || operator_new_fptr == threadsafe_mem_leak_operator_new; #else return false; #endif } void MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads() { #if CPPUTEST_USE_MEM_LEAK_DETECTION if (++save_counter > 1) return; saved_operator_new_fptr = operator_new_fptr; saved_operator_new_nothrow_fptr = operator_new_nothrow_fptr; saved_operator_new_debug_fptr = operator_new_debug_fptr; saved_operator_new_array_fptr = operator_new_array_fptr; saved_operator_new_array_nothrow_fptr = operator_new_array_nothrow_fptr; saved_operator_new_array_debug_fptr = operator_new_array_debug_fptr; saved_operator_delete_fptr = operator_delete_fptr; saved_operator_delete_array_fptr = operator_delete_array_fptr; saved_malloc_fptr = malloc_fptr; saved_realloc_fptr = realloc_fptr; saved_free_fptr = free_fptr; turnOffNewDeleteOverloads(); #endif } void MemoryLeakWarningPlugin::restoreNewDeleteOverloads() { #if CPPUTEST_USE_MEM_LEAK_DETECTION if (--save_counter > 0) return; operator_new_fptr = saved_operator_new_fptr; operator_new_nothrow_fptr = saved_operator_new_nothrow_fptr; operator_new_debug_fptr = saved_operator_new_debug_fptr; operator_new_array_fptr = saved_operator_new_array_fptr; operator_new_array_nothrow_fptr = saved_operator_new_array_nothrow_fptr; operator_new_array_debug_fptr = saved_operator_new_array_debug_fptr; operator_delete_fptr = saved_operator_delete_fptr; operator_delete_array_fptr = saved_operator_delete_array_fptr; malloc_fptr = saved_malloc_fptr; realloc_fptr = saved_realloc_fptr; free_fptr = saved_free_fptr; #endif } void crash_on_allocation_number(unsigned alloc_number) { static CrashOnAllocationAllocator crashAllocator; crashAllocator.setNumberToCrashOn(alloc_number); setCurrentMallocAllocator(&crashAllocator); setCurrentNewAllocator(&crashAllocator); setCurrentNewArrayAllocator(&crashAllocator); } class MemoryLeakWarningReporter: public MemoryLeakFailure { public: virtual ~MemoryLeakWarningReporter() CPPUTEST_DESTRUCTOR_OVERRIDE { } virtual void fail(char* fail_string) CPPUTEST_OVERRIDE { UtestShell* currentTest = UtestShell::getCurrent(); currentTest->failWith(FailFailure(currentTest, currentTest->getName().asCharString(), currentTest->getLineNumber(), fail_string), UtestShell::getCurrentTestTerminatorWithoutExceptions()); } // LCOV_EXCL_LINE }; static MemoryLeakFailure* globalReporter = NULLPTR; static MemoryLeakDetector* globalDetector = NULLPTR; MemoryLeakDetector* MemoryLeakWarningPlugin::getGlobalDetector() { if (globalDetector == NULLPTR) { saveAndDisableNewDeleteOverloads(); globalReporter = new MemoryLeakWarningReporter; globalDetector = new MemoryLeakDetector(globalReporter); restoreNewDeleteOverloads(); } 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 = NULLPTR; } MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::firstPlugin_ = NULLPTR; MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::getFirstPlugin() { return firstPlugin_; } MemoryLeakDetector* MemoryLeakWarningPlugin::getMemoryLeakDetector() { return memLeakDetector_; } void MemoryLeakWarningPlugin::ignoreAllLeaksInTest() { ignoreAllWarnings_ = true; } void MemoryLeakWarningPlugin::expectLeaksInTest(size_t n) { expectedLeaks_ = n; } MemoryLeakWarningPlugin::MemoryLeakWarningPlugin(const SimpleString& name, MemoryLeakDetector* localDetector) : TestPlugin(name), ignoreAllWarnings_(false), destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_(false), expectedLeaks_(0) { if (firstPlugin_ == NULLPTR) 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(); size_t leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_checking); if (!ignoreAllWarnings_ && expectedLeaks_ != leaks && failureCount_ == result.getFailureCount()) { if(MemoryLeakWarningPlugin::areNewDeleteOverloaded()) { TestFailure f(&test, memLeakDetector_->report(mem_leak_period_checking)); result.addFailure(f); } else if(expectedLeaks_ > 0) { result.print(StringFromFormat("Warning: Expected %d leak(s), but leak detection was disabled", (int) expectedLeaks_).asCharString()); } } memLeakDetector_->markCheckingPeriodLeaksAsNonCheckingPeriod(); ignoreAllWarnings_ = false; expectedLeaks_ = 0; } const char* MemoryLeakWarningPlugin::FinalReport(size_t toBeDeletedLeaks) { size_t leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_enabled); if (leaks != toBeDeletedLeaks) return memLeakDetector_->report(mem_leak_period_enabled); return ""; }
null
188
cpp
cpputest
SimpleString.cpp
src/CppUTest/SimpleString.cpp
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 <organization> 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 <copyright holder> 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" GlobalSimpleStringAllocatorStash::GlobalSimpleStringAllocatorStash() : originalAllocator_(NULLPTR) { } void GlobalSimpleStringAllocatorStash::save() { originalAllocator_ = SimpleString::getStringAllocator(); } void GlobalSimpleStringAllocatorStash::restore() { SimpleString::setStringAllocator(originalAllocator_); } GlobalSimpleStringMemoryAccountant::GlobalSimpleStringMemoryAccountant() : allocator_(NULLPTR) { accountant_ = new MemoryAccountant(); } GlobalSimpleStringMemoryAccountant::~GlobalSimpleStringMemoryAccountant() { restoreAllocator(); delete accountant_; delete allocator_; } void GlobalSimpleStringMemoryAccountant::restoreAllocator() { if (allocator_ && (SimpleString::getStringAllocator() == allocator_)) SimpleString::setStringAllocator(allocator_->originalAllocator()); } void GlobalSimpleStringMemoryAccountant::useCacheSizes(size_t cacheSizes[], size_t length) { accountant_->useCacheSizes(cacheSizes, length); } void GlobalSimpleStringMemoryAccountant::start() { if (allocator_ != NULLPTR) return; allocator_ = new AccountingTestMemoryAllocator(*accountant_, SimpleString::getStringAllocator()); SimpleString::setStringAllocator(allocator_); } void GlobalSimpleStringMemoryAccountant::stop() { if (allocator_ == NULLPTR) FAIL("Global SimpleString allocator stopped without starting"); if (SimpleString::getStringAllocator() != allocator_) FAIL("GlobalStrimpleStringMemoryAccountant: allocator has changed between start and stop!"); restoreAllocator(); } SimpleString GlobalSimpleStringMemoryAccountant::report() { return accountant_->report(); } AccountingTestMemoryAllocator* GlobalSimpleStringMemoryAccountant::getAllocator() { return allocator_; } TestMemoryAllocator* SimpleString::stringAllocator_ = NULLPTR; TestMemoryAllocator* SimpleString::getStringAllocator() { if (stringAllocator_ == NULLPTR) 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, const char* file, size_t line) { return getStringAllocator()->alloc_memory(_size, file, line); } void SimpleString::deallocStringBuffer(char* str, size_t size, const char* file, size_t line) { getStringAllocator()->free_memory(str, size, file, line); } char* SimpleString::getEmptyString() const { char* empty = allocStringBuffer(1, __FILE__, __LINE__); empty[0] = '\0'; return empty; } // does not support + or - prefixes unsigned SimpleString::AtoU(const char* str) { while (isSpace(*str)) str++; unsigned result = 0; for(; isDigit(*str) && *str >= '0'; str++) { result *= 10; result += static_cast<unsigned>(*str - '0'); } return result; } int SimpleString::AtoI(const char* str) { while (isSpace(*str)) str++; char first_char = *str; if (first_char == '-' || first_char == '+') str++; int result = 0; for(; isDigit(*str); str++) { result *= 10; result += *str - '0'; } return (first_char == '-') ? -result : result; } int SimpleString::StrCmp(const char* s1, const char* s2) { while(*s1 && *s1 == *s2) { ++s1; ++s2; } return *(const unsigned char *) s1 - *(const unsigned char *) s2; } size_t SimpleString::StrLen(const char* str) { size_t n = (size_t)-1; do n++; while (*str++); return n; } int SimpleString::StrNCmp(const char* s1, const char* s2, size_t n) { while (n && *s1 && *s1 == *s2) { --n; ++s1; ++s2; } return n ? *(const unsigned char *) s1 - *(const unsigned char *) s2 : 0; } char* SimpleString::StrNCpy(char* s1, const char* s2, size_t n) { char* result = s1; if((NULLPTR == s1) || (0 == n)) return result; *s1 = *s2; while ((--n != 0) && *s1){ *++s1 = *++s2; } return result; } const char* SimpleString::StrStr(const char* s1, const char* s2) { if(!*s2) return s1; for (; *s1; s1++) if (StrNCmp(s1, s2, StrLen(s2)) == 0) return s1; return NULLPTR; } char SimpleString::ToLower(char ch) { return isUpper(ch) ? (char)((int)ch + ('a' - 'A')) : ch; } int SimpleString::MemCmp(const void* s1, const void *s2, size_t n) { const unsigned char* p1 = (const unsigned char*) s1; const unsigned char* p2 = (const unsigned char*) s2; while (n--) if (*p1 != *p2) { return *p1 - *p2; } else { ++p1; ++p2; } return 0; } void SimpleString::deallocateInternalBuffer() { if (buffer_) { deallocStringBuffer(buffer_, bufferSize_, __FILE__, __LINE__); buffer_ = NULLPTR; bufferSize_ = 0; } } void SimpleString::setInternalBufferAsEmptyString() { deallocateInternalBuffer(); bufferSize_ = 1; buffer_ = getEmptyString(); } void SimpleString::copyBufferToNewInternalBuffer(const char* otherBuffer, size_t bufferSize) { deallocateInternalBuffer(); bufferSize_ = bufferSize; buffer_ = copyToNewBuffer(otherBuffer, bufferSize_); } void SimpleString::setInternalBufferToNewBuffer(size_t bufferSize) { deallocateInternalBuffer(); bufferSize_ = bufferSize; buffer_ = allocStringBuffer(bufferSize_, __FILE__, __LINE__); buffer_[0] = '\0'; } void SimpleString::setInternalBufferTo(char* buffer, size_t bufferSize) { deallocateInternalBuffer(); bufferSize_ = bufferSize; buffer_ = buffer; } void SimpleString::copyBufferToNewInternalBuffer(const SimpleString& otherBuffer) { copyBufferToNewInternalBuffer(otherBuffer.buffer_, otherBuffer.size() + 1); } void SimpleString::copyBufferToNewInternalBuffer(const char* otherBuffer) { copyBufferToNewInternalBuffer(otherBuffer, StrLen(otherBuffer) + 1); } const char* SimpleString::getBuffer() const { return buffer_; } SimpleString::SimpleString(const char *otherBuffer) : buffer_(NULLPTR), bufferSize_(0) { if (otherBuffer == NULLPTR) setInternalBufferAsEmptyString(); else copyBufferToNewInternalBuffer(otherBuffer); } SimpleString::SimpleString(const char *other, size_t repeatCount) : buffer_(NULLPTR), bufferSize_(0) { size_t otherStringLength = StrLen(other); setInternalBufferToNewBuffer(otherStringLength * repeatCount + 1); char* next = buffer_; for (size_t i = 0; i < repeatCount; i++) { StrNCpy(next, other, otherStringLength + 1); next += otherStringLength; } *next = 0; } SimpleString::SimpleString(const SimpleString& other) : buffer_(NULLPTR), bufferSize_(0) { copyBufferToNewInternalBuffer(other.getBuffer()); } SimpleString& SimpleString::operator=(const SimpleString& other) { if (this != &other) copyBufferToNewInternalBuffer(other); return *this; } bool SimpleString::contains(const SimpleString& other) const { return StrStr(getBuffer(), other.getBuffer()) != NULLPTR; } bool SimpleString::containsNoCase(const SimpleString& other) const { return lowerCase().contains(other.lowerCase()); } bool SimpleString::startsWith(const SimpleString& other) const { if (other.size() == 0) return true; else if (size() == 0) return false; else return StrStr(getBuffer(), other.getBuffer()) == getBuffer(); } bool SimpleString::endsWith(const SimpleString& other) const { size_t length = size(); size_t other_length = other.size(); if (other_length == 0) return true; if (length == 0) return false; if (length < other_length) return false; return StrCmp(getBuffer() + length - other_length, other.getBuffer()) == 0; } size_t SimpleString::count(const SimpleString& substr) const { size_t num = 0; const char* str = getBuffer(); const char* strpart = NULLPTR; if (*str){ strpart = StrStr(str, substr.getBuffer()); } while (*str && strpart) { str = strpart; str++; num++; strpart = StrStr(str, substr.getBuffer()); } return num; } 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); const char* str = getBuffer(); const char* prev; for (size_t i = 0; i < num; ++i) { prev = str; str = StrStr(str, delimiter.getBuffer()) + 1; col[i] = SimpleString(prev).subString(0, size_t (str - prev)); } 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 (getBuffer()[i] == to) buffer_[i] = with; } } void SimpleString::replace(const char* to, const char* with) { size_t c = count(to); if (c == 0) { return; } size_t len = size(); size_t tolen = StrLen(to); size_t withlen = StrLen(with); size_t newsize = len + (withlen * c) - (tolen * c) + 1; if (newsize > 1) { char* newbuf = allocStringBuffer(newsize, __FILE__, __LINE__); for (size_t i = 0, j = 0; i < len;) { if (StrNCmp(&getBuffer()[i], to, tolen) == 0) { StrNCpy(&newbuf[j], with, withlen + 1); j += withlen; i += tolen; } else { newbuf[j] = getBuffer()[i]; j++; i++; } } newbuf[newsize - 1] = '\0'; setInternalBufferTo(newbuf, newsize); } else setInternalBufferAsEmptyString(); } SimpleString SimpleString::printable() const { static const char* shortEscapeCodes[] = { "\\a", "\\b", "\\t", "\\n", "\\v", "\\f", "\\r" }; SimpleString result; result.setInternalBufferToNewBuffer(getPrintableSize() + 1); size_t str_size = size(); size_t j = 0; for (size_t i = 0; i < str_size; i++) { char c = buffer_[i]; if (isControlWithShortEscapeSequence(c)) { StrNCpy(&result.buffer_[j], shortEscapeCodes[(unsigned char)(c - '\a')], 2); j += 2; } else if (isControl(c)) { SimpleString hexEscapeCode = StringFromFormat("\\x%02X ", c); StrNCpy(&result.buffer_[j], hexEscapeCode.asCharString(), 4); j += 4; } else { result.buffer_[j] = c; j++; } } result.buffer_[j] = 0; return result; } size_t SimpleString::getPrintableSize() const { size_t str_size = size(); size_t printable_str_size = str_size; for (size_t i = 0; i < str_size; i++) { char c = buffer_[i]; if (isControlWithShortEscapeSequence(c)) { printable_str_size += 1; } else if (isControl(c)) { printable_str_size += 3; } } return printable_str_size; } SimpleString SimpleString::lowerCase() const { SimpleString str(*this); size_t str_size = str.size(); for (size_t i = 0; i < str_size; i++) str.buffer_[i] = ToLower(str.getBuffer()[i]); return str; } const char *SimpleString::asCharString() const { return getBuffer(); } size_t SimpleString::size() const { return StrLen(getBuffer()); } bool SimpleString::isEmpty() const { return size() == 0; } SimpleString::~SimpleString() { deallocateInternalBuffer(); } bool operator==(const SimpleString& left, const SimpleString& right) { return 0 == SimpleString::StrCmp(left.asCharString(), right.asCharString()); } bool SimpleString::equalsNoCase(const SimpleString& str) const { return lowerCase() == str.lowerCase(); } bool operator!=(const SimpleString& left, const SimpleString& right) { return !(left == right); } SimpleString SimpleString::operator+(const SimpleString& rhs) const { SimpleString t(getBuffer()); t += rhs.getBuffer(); return t; } SimpleString& SimpleString::operator+=(const SimpleString& rhs) { return operator+=(rhs.getBuffer()); } SimpleString& SimpleString::operator+=(const char* rhs) { size_t originalSize = this->size(); size_t additionalStringSize = StrLen(rhs) + 1; size_t sizeOfNewString = originalSize + additionalStringSize; char* tbuffer = copyToNewBuffer(this->getBuffer(), sizeOfNewString); StrNCpy(tbuffer + originalSize, rhs, additionalStringSize); setInternalBufferTo(tbuffer, sizeOfNewString); 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 = getBuffer() + beginPos; if (newString.size() > amount) newString.buffer_[amount] = '\0'; return newString; } SimpleString SimpleString::subString(size_t beginPos) const { return subString(beginPos, npos); } char SimpleString::at(size_t pos) const { return getBuffer()[pos]; } size_t SimpleString::find(char ch) const { return findFrom(0, ch); } size_t SimpleString::findFrom(size_t starting_position, char ch) const { size_t length = size(); for (size_t i = starting_position; i < length; i++) if (at(i) == ch) return i; return npos; } SimpleString SimpleString::subStringFromTill(char startChar, char lastExcludedChar) const { size_t beginPos = find(startChar); if (beginPos == npos) return ""; size_t endPos = findFrom(beginPos, lastExcludedChar); if (endPos == npos) return subString(beginPos); return subString(beginPos, endPos - beginPos); } char* SimpleString::copyToNewBuffer(const char* bufferToCopy, size_t bufferSize) { char* newBuffer = allocStringBuffer(bufferSize, __FILE__, __LINE__); StrNCpy(newBuffer, bufferToCopy, bufferSize); newBuffer[bufferSize-1] = '\0'; return newBuffer; } void SimpleString::copyToBuffer(char* bufferToCopy, size_t bufferSize) const { if (bufferToCopy == NULLPTR || bufferSize == 0) return; size_t sizeToCopy = (bufferSize-1 < size()) ? (bufferSize-1) : size(); StrNCpy(bufferToCopy, getBuffer(), sizeToCopy); bufferToCopy[sizeToCopy] = '\0'; } bool SimpleString::isDigit(char ch) { return '0' <= ch && '9' >= ch; } bool SimpleString::isSpace(char ch) { return (ch == ' ') || (0x08 < ch && 0x0E > ch); } bool SimpleString::isUpper(char ch) { return 'A' <= ch && 'Z' >= ch; } bool SimpleString::isControl(char ch) { return ch < ' ' || ch == char(0x7F); } bool SimpleString::isControlWithShortEscapeSequence(char ch) { return '\a' <= ch && '\r' >= ch; } SimpleString StringFrom(bool value) { return SimpleString(StringFromFormat("%s", value ? "true" : "false")); } SimpleString StringFrom(const char *value) { return SimpleString(value); } SimpleString StringFromOrNull(const char * expected) { return (expected) ? StringFrom(expected) : StringFrom("(null)"); } SimpleString PrintableStringFromOrNull(const char * expected) { return (expected) ? StringFrom(expected).printable() : StringFrom("(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 StringFrom(void (*value)()) { return SimpleString("0x") + HexStringFrom(value); } SimpleString HexStringFrom(long value) { return StringFromFormat("%lx", value); } SimpleString HexStringFrom(int value) { return StringFromFormat("%x", value); } SimpleString HexStringFrom(signed char value) { SimpleString result = StringFromFormat("%x", value); if(value < 0) { size_t size = result.size(); result = result.subString(size-(CPPUTEST_CHAR_BIT/4)); } return result; } SimpleString HexStringFrom(unsigned long value) { return StringFromFormat("%lx", value); } SimpleString HexStringFrom(unsigned int value) { return StringFromFormat("%x", value); } SimpleString BracketsFormattedHexStringFrom(int value) { return BracketsFormattedHexString(HexStringFrom(value)); } SimpleString BracketsFormattedHexStringFrom(unsigned int value) { return BracketsFormattedHexString(HexStringFrom(value)); } SimpleString BracketsFormattedHexStringFrom(long value) { return BracketsFormattedHexString(HexStringFrom(value)); } SimpleString BracketsFormattedHexStringFrom(unsigned long value) { return BracketsFormattedHexString(HexStringFrom(value)); } SimpleString BracketsFormattedHexStringFrom(signed char value) { return BracketsFormattedHexString(HexStringFrom(value)); } SimpleString BracketsFormattedHexString(SimpleString hexString) { return SimpleString("(0x") + hexString + ")" ; } /* * ARM compiler has only partial support for C++11. * Specifically nullptr_t is not officially supported */ #if __cplusplus > 199711L && !defined __arm__ && CPPUTEST_USE_STD_CPP_LIB SimpleString StringFrom(const std::nullptr_t value) { (void) value; return "(null)"; } #endif #if CPPUTEST_USE_LONG_LONG SimpleString StringFrom(cpputest_longlong value) { return StringFromFormat("%lld", value); } SimpleString StringFrom(cpputest_ulonglong value) { return StringFromFormat("%llu", value); } SimpleString HexStringFrom(cpputest_longlong value) { return StringFromFormat("%llx", value); } SimpleString HexStringFrom(cpputest_ulonglong value) { return StringFromFormat("%llx", value); } SimpleString HexStringFrom(const void* value) { return HexStringFrom((cpputest_ulonglong) value); } SimpleString HexStringFrom(void (*value)()) { return HexStringFrom((cpputest_ulonglong) value); } SimpleString BracketsFormattedHexStringFrom(cpputest_longlong value) { return BracketsFormattedHexString(HexStringFrom(value)); } SimpleString BracketsFormattedHexStringFrom(cpputest_ulonglong value) { return BracketsFormattedHexString(HexStringFrom(value)); } #else /* CPPUTEST_USE_LONG_LONG */ static long convertPointerToLongValue(const void* value) { /* * 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; } static long convertFunctionPointerToLongValue(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 StringFrom(cpputest_longlong) { return "<longlong_unsupported>"; } SimpleString StringFrom(cpputest_ulonglong) { return "<ulonglong_unsupported>"; } SimpleString HexStringFrom(cpputest_longlong) { return "<longlong_unsupported>"; } SimpleString HexStringFrom(cpputest_ulonglong) { return "<ulonglong_unsupported>"; } SimpleString HexStringFrom(const void* value) { return StringFromFormat("%lx", convertPointerToLongValue(value)); } SimpleString HexStringFrom(void (*value)()) { return StringFromFormat("%lx", convertFunctionPointerToLongValue(value)); } SimpleString BracketsFormattedHexStringFrom(cpputest_longlong) { return ""; } SimpleString BracketsFormattedHexStringFrom(cpputest_ulonglong) { return ""; } #endif /* CPPUTEST_USE_LONG_LONG */ SimpleString StringFrom(double value, int precision) { if (PlatformSpecificIsNan(value)) return "Nan - Not a number"; else if (PlatformSpecificIsInf(value)) return "Inf - Infinity"; else 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("%u", i); } #if CPPUTEST_USE_STD_CPP_LIB #include <string> SimpleString StringFrom(const std::string& value) { return SimpleString(value.c_str()); } #endif SimpleString StringFrom(unsigned long i) { return StringFromFormat("%lu", i); } 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, __FILE__, __LINE__); PlatformSpecificVSNprintf(newBuffer, newBufferSize, format, argsCopy); resultString = SimpleString(newBuffer); SimpleString::deallocStringBuffer(newBuffer, newBufferSize, __FILE__, __LINE__); } va_end(argsCopy); return resultString; } SimpleString StringFromBinary(const unsigned char* value, size_t size) { SimpleString result; for (size_t i = 0; i < size; i++) { result += StringFromFormat("%02X ", value[i]); } result = result.subString(0, result.size() - 1); return result; } SimpleString StringFromBinaryOrNull(const unsigned char* value, size_t size) { return (value) ? StringFromBinary(value, size) : StringFrom("(null)"); } SimpleString StringFromBinaryWithSize(const unsigned char* value, size_t size) { SimpleString result = StringFromFormat("Size = %u | HexContents = ", (unsigned) size); size_t displayedSize = ((size > 128) ? 128 : size); result += StringFromBinaryOrNull(value, displayedSize); if (size > displayedSize) { result += " ..."; } return result; } SimpleString StringFromBinaryWithSizeOrNull(const unsigned char* value, size_t size) { return (value) ? StringFromBinaryWithSize(value, size) : StringFrom("(null)"); } SimpleString StringFromMaskedBits(unsigned long value, unsigned long mask, size_t byteCount) { SimpleString result; size_t bitCount = (byteCount > sizeof(unsigned long)) ? (sizeof(unsigned long) * CPPUTEST_CHAR_BIT) : (byteCount * CPPUTEST_CHAR_BIT); const unsigned long msbMask = (((unsigned long) 1) << (bitCount - 1)); for (size_t i = 0; i < bitCount; i++) { if (mask & msbMask) { result += (value & msbMask) ? "1" : "0"; } else { result += "x"; } if (((i % 8) == 7) && (i != (bitCount - 1))) { result += " "; } value <<= 1; mask <<= 1; } return result; } SimpleString StringFromOrdinalNumber(unsigned int number) { const char* suffix = "th"; if ((number < 11) || (number > 13)) { unsigned int const onesDigit = number % 10; if (3 == onesDigit) { suffix = "rd"; } else if (2 == onesDigit) { suffix = "nd"; } else if (1 == onesDigit) { suffix = "st"; } } return StringFromFormat("%u%s", number, suffix); } SimpleStringCollection::SimpleStringCollection() { collection_ = NULLPTR; size_ = 0; } void SimpleStringCollection::allocate(size_t _size) { 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]; }
null
189
cpp
cpputest
TestResult.cpp
src/CppUTest/TestResult.cpp
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 <organization> 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 <copyright holder> 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) { } TestResult::~TestResult() { } void TestResult::currentGroupStarted(UtestShell* test) { output_.printCurrentGroupStarted(*test); currentGroupTimeStarted_ = (size_t) GetPlatformSpecificTimeInMillis(); } void TestResult::currentGroupEnded(UtestShell* /*test*/) { currentGroupTotalExecutionTime_ = (size_t) GetPlatformSpecificTimeInMillis() - currentGroupTimeStarted_; output_.printCurrentGroupEnded(*this); } void TestResult::currentTestStarted(UtestShell* test) { output_.printCurrentTestStarted(*test); currentTestTimeStarted_ = (size_t) GetPlatformSpecificTimeInMillis(); } void TestResult::print(const char* text) { output_.print(text); } void TestResult::printVeryVerbose(const char* text) { output_.printVeryVerbose(text); } void TestResult::currentTestEnded(UtestShell* /*test*/) { currentTestTotalExecutionTime_ = (size_t) GetPlatformSpecificTimeInMillis() - currentTestTimeStarted_; output_.printCurrentTestEnded(*this); } void TestResult::addFailure(const TestFailure& failure) { output_.printFailure(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_ = (size_t) GetPlatformSpecificTimeInMillis(); output_.printTestsStarted(); } void TestResult::testsEnded() { size_t timeEnded = (size_t) GetPlatformSpecificTimeInMillis(); totalExecutionTime_ = timeEnded - timeStarted_; output_.printTestsEnded(*this); } size_t TestResult::getTotalExecutionTime() const { return totalExecutionTime_; } void TestResult::setTotalExecutionTime(size_t exTime) { totalExecutionTime_ = exTime; } size_t TestResult::getCurrentTestTotalExecutionTime() const { return currentTestTotalExecutionTime_; } size_t TestResult::getCurrentGroupTotalExecutionTime() const { return currentGroupTotalExecutionTime_; }
null
190
cpp
cpputest
SimpleStringInternalCache.cpp
src/CppUTest/SimpleStringInternalCache.cpp
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 <organization> 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 <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/SimpleStringInternalCache.h" struct SimpleStringMemoryBlock { SimpleStringMemoryBlock* next_; char* memory_; }; struct SimpleStringInternalCacheNode { size_t size_; SimpleStringMemoryBlock* freeMemoryHead_; SimpleStringMemoryBlock* usedMemoryHead_; }; SimpleStringInternalCache::SimpleStringInternalCache() : allocator_(defaultMallocAllocator()), cache_(NULLPTR), nonCachedAllocations_(NULLPTR), hasWarnedAboutDeallocations(false) { cache_ = createInternalCacheNodes(); } SimpleStringInternalCache::~SimpleStringInternalCache() { allocator_ = defaultMallocAllocator(); destroyInternalCacheNode(cache_); } void SimpleStringInternalCache::setAllocator(TestMemoryAllocator* allocator) { allocator_ = allocator; } SimpleStringInternalCacheNode* SimpleStringInternalCache::createInternalCacheNodes() { SimpleStringInternalCacheNode* node = (SimpleStringInternalCacheNode*) (void*) allocator_->alloc_memory(sizeof(SimpleStringInternalCacheNode) * amountOfInternalCacheNodes, __FILE__, __LINE__); for (int i = 0; i < amountOfInternalCacheNodes; i++) { node[i].freeMemoryHead_ = NULLPTR; node[i].usedMemoryHead_ = NULLPTR; } node[0].size_ = 32; node[1].size_ = 64; node[2].size_ = 96; node[3].size_ = 128; node[4].size_ = 256; return node; } bool SimpleStringInternalCache::isCached(size_t size) { return size <= 256; } size_t SimpleStringInternalCache::getIndexForCache(size_t size) { for (size_t i = 0; i < amountOfInternalCacheNodes; i++) if (size <= cache_[i].size_) return i; return 0; // LCOV_EXCL_LINE } SimpleStringInternalCacheNode* SimpleStringInternalCache::getCacheNodeFromSize(size_t size) { size_t index = getIndexForCache(size); return &cache_[index]; } void SimpleStringInternalCache::destroyInternalCacheNode(SimpleStringInternalCacheNode * node) { allocator_->free_memory((char*) node, sizeof(SimpleStringInternalCacheNode) * amountOfInternalCacheNodes, __FILE__, __LINE__); } SimpleStringMemoryBlock* SimpleStringInternalCache::createSimpleStringMemoryBlock(size_t size, SimpleStringMemoryBlock* next) { SimpleStringMemoryBlock* block = (SimpleStringMemoryBlock*) (void*) allocator_->alloc_memory(sizeof(SimpleStringMemoryBlock) , __FILE__, __LINE__); block->memory_ = allocator_->alloc_memory(size , __FILE__, __LINE__); block->next_ = next; return block; } void SimpleStringInternalCache::destroySimpleStringMemoryBlock(SimpleStringMemoryBlock * block, size_t size) { allocator_->free_memory(block->memory_, size, __FILE__, __LINE__); allocator_->free_memory((char*) block, sizeof(SimpleStringMemoryBlock), __FILE__, __LINE__); } void SimpleStringInternalCache::destroySimpleStringMemoryBlockList(SimpleStringMemoryBlock * block, size_t size) { SimpleStringMemoryBlock* current = block; while (current) { SimpleStringMemoryBlock* next = current->next_; destroySimpleStringMemoryBlock(current, size); current = next; } } SimpleStringMemoryBlock* SimpleStringInternalCache::addToSimpleStringMemoryBlockList(SimpleStringMemoryBlock* newBlock, SimpleStringMemoryBlock* previousHead) { newBlock->next_ = previousHead; return newBlock; } bool SimpleStringInternalCache::hasFreeBlocksOfSize(size_t size) { return getCacheNodeFromSize(size)->freeMemoryHead_ != NULLPTR; } SimpleStringMemoryBlock* SimpleStringInternalCache::reserveCachedBlockFrom(SimpleStringInternalCacheNode* node) { SimpleStringMemoryBlock* block = node->freeMemoryHead_; node->freeMemoryHead_ = block->next_; node->usedMemoryHead_ = addToSimpleStringMemoryBlockList(block, node->usedMemoryHead_); return block; } SimpleStringMemoryBlock* SimpleStringInternalCache::allocateNewCacheBlockFrom(SimpleStringInternalCacheNode* node) { SimpleStringMemoryBlock* block = createSimpleStringMemoryBlock(node->size_, node->usedMemoryHead_); node->usedMemoryHead_ = addToSimpleStringMemoryBlockList(block, node->usedMemoryHead_); return block; } void SimpleStringInternalCache::printDeallocatingUnknownMemory(char* memory) { if (!hasWarnedAboutDeallocations) { hasWarnedAboutDeallocations = true; UtestShell::getCurrent()->print(StringFromFormat("\nWARNING: Attempting to deallocate a String buffer that was allocated while not caching. Ignoring it!\n" "This is likely due statics and will cause problems.\n" "Only warning once to avoid recursive warnings.\n" "String we are deallocating: \"%s\"\n", memory).asCharString(), __FILE__, __LINE__); } } void SimpleStringInternalCache::releaseCachedBlockFrom(char* memory, SimpleStringInternalCacheNode* node) { if (node->usedMemoryHead_ && node->usedMemoryHead_->memory_ == memory) { SimpleStringMemoryBlock* block = node->usedMemoryHead_; node->usedMemoryHead_ = node->usedMemoryHead_->next_; node->freeMemoryHead_ = addToSimpleStringMemoryBlockList(block, node->freeMemoryHead_); return; } for (SimpleStringMemoryBlock* block = node->usedMemoryHead_; block; block = block->next_) { if (block->next_ && block->next_->memory_ == memory) { SimpleStringMemoryBlock* blockToFree = block->next_; block->next_ = block->next_->next_; node->freeMemoryHead_ = addToSimpleStringMemoryBlockList(blockToFree, node->freeMemoryHead_); return; } } printDeallocatingUnknownMemory(memory); } void SimpleStringInternalCache::releaseNonCachedMemory(char* memory, size_t size) { if (nonCachedAllocations_ && nonCachedAllocations_->memory_ == memory) { SimpleStringMemoryBlock* block = nonCachedAllocations_; nonCachedAllocations_ = block->next_; destroySimpleStringMemoryBlock(block, size); return; } for (SimpleStringMemoryBlock* block = nonCachedAllocations_; block; block = block->next_) { if (block->next_ && block->next_->memory_ == memory) { SimpleStringMemoryBlock* blockToFree = block->next_; block->next_ = block->next_->next_; destroySimpleStringMemoryBlock(blockToFree, size); return; } } printDeallocatingUnknownMemory(memory); } char* SimpleStringInternalCache::alloc(size_t size) { if (isCached(size)) { if (hasFreeBlocksOfSize(size)) return reserveCachedBlockFrom(getCacheNodeFromSize(size))->memory_; else return allocateNewCacheBlockFrom(getCacheNodeFromSize(size))->memory_; } nonCachedAllocations_ = createSimpleStringMemoryBlock(size, nonCachedAllocations_); return nonCachedAllocations_->memory_; } void SimpleStringInternalCache::dealloc(char* memory, size_t size) { if (isCached(size)) { size_t index = getIndexForCache(size); SimpleStringInternalCacheNode* cacheNode = &cache_[index]; releaseCachedBlockFrom(memory, cacheNode); return; } releaseNonCachedMemory(memory, size); } void SimpleStringInternalCache::clearCache() { for (size_t i = 0; i < amountOfInternalCacheNodes; i++) { destroySimpleStringMemoryBlockList(cache_[i].freeMemoryHead_, cache_[i].size_); cache_[i].freeMemoryHead_ = NULLPTR; } } void SimpleStringInternalCache::clearAllIncludingCurrentlyUsedMemory() { for (size_t i = 0; i < amountOfInternalCacheNodes; i++) { destroySimpleStringMemoryBlockList(cache_[i].freeMemoryHead_, cache_[i].size_); destroySimpleStringMemoryBlockList(cache_[i].usedMemoryHead_, cache_[i].size_); cache_[i].freeMemoryHead_ = NULLPTR; cache_[i].usedMemoryHead_ = NULLPTR; } destroySimpleStringMemoryBlockList(nonCachedAllocations_, 0); nonCachedAllocations_ = NULLPTR; } GlobalSimpleStringCache::GlobalSimpleStringCache() { allocator_ = new SimpleStringCacheAllocator(cache_, SimpleString::getStringAllocator()); SimpleString::setStringAllocator(allocator_); } GlobalSimpleStringCache::~GlobalSimpleStringCache() { SimpleString::setStringAllocator(allocator_->originalAllocator()); cache_.clearAllIncludingCurrentlyUsedMemory(); delete allocator_; } TestMemoryAllocator* GlobalSimpleStringCache::getAllocator() { return allocator_; } SimpleStringCacheAllocator::SimpleStringCacheAllocator(SimpleStringInternalCache& cache, TestMemoryAllocator* origAllocator) : cache_(cache), originalAllocator_(origAllocator) { cache_.setAllocator(origAllocator); } SimpleStringCacheAllocator::~SimpleStringCacheAllocator() { cache_.setAllocator(NULLPTR); } char* SimpleStringCacheAllocator::alloc_memory(size_t size, const char*, size_t) { return cache_.alloc(size); } void SimpleStringCacheAllocator::free_memory(char* memory, size_t size, const char*, size_t) { cache_.dealloc(memory, size); } const char* SimpleStringCacheAllocator::name() const { return "SimpleStringCacheAllocator"; } const char* SimpleStringCacheAllocator::alloc_name() const { return originalAllocator_->alloc_name(); } const char* SimpleStringCacheAllocator::free_name() const { return originalAllocator_->free_name(); } TestMemoryAllocator* SimpleStringCacheAllocator::actualAllocator() { return originalAllocator_->actualAllocator(); } TestMemoryAllocator* SimpleStringCacheAllocator::originalAllocator() { return originalAllocator_; }
null
191
cpp
cpputest
TestRegistry.cpp
src/CppUTest/TestRegistry.cpp
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 <organization> 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 <copyright holder> 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/PlatformSpecificFunctions.h" TestRegistry::TestRegistry() : tests_(NULLPTR), nameFilters_(NULLPTR), groupFilters_(NULLPTR), firstPlugin_(NullTestPlugin::instance()), runInSeperateProcess_(false), currentRepetition_(0), runIgnored_(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 != NULLPTR; test = test->getNext()) { if (runInSeperateProcess_) test->setRunInSeperateProcess(); if (runIgnored_) test->setRunIgnored(); if (groupStart) { result.currentGroupStarted(test); groupStart = false; } 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(); currentRepetition_++; } void TestRegistry::listTestGroupNames(TestResult& result) { SimpleString groupList; for (UtestShell *test = tests_; test != NULLPTR; test = test->getNext()) { SimpleString gname; gname += "#"; gname += test->getGroup(); gname += "#"; if (!groupList.contains(gname)) { groupList += gname; groupList += " "; } } groupList.replace("#", ""); if (groupList.endsWith(" ")) groupList = groupList.subString(0, groupList.size() - 1); result.print(groupList.asCharString()); } void TestRegistry::listTestGroupAndCaseNames(TestResult& result) { SimpleString groupAndNameList; for (UtestShell *test = tests_; test != NULLPTR; test = test->getNext()) { if (testShouldRun(test, result)) { SimpleString groupAndName; groupAndName += "#"; groupAndName += test->getGroup(); groupAndName += "."; groupAndName += test->getName(); groupAndName += "#"; if (!groupAndNameList.contains(groupAndName)) { groupAndNameList += groupAndName; groupAndNameList += " "; } } } groupAndNameList.replace("#", ""); if (groupAndNameList.endsWith(" ")) groupAndNameList = groupAndNameList.subString(0, groupAndNameList.size() - 1); result.print(groupAndNameList.asCharString()); } void TestRegistry::listTestLocations(TestResult& result) { SimpleString testLocations; for (UtestShell *test = tests_; test != NULLPTR; test = test->getNext()) { SimpleString testLocation; testLocation += test->getGroup(); testLocation += "."; testLocation += test->getName(); testLocation += "."; testLocation += test->getFile(); testLocation += "."; testLocation += StringFromFormat("%d\n",(int) test->getLineNumber()); testLocations += testLocation; } result.print(testLocations.asCharString()); } bool TestRegistry::endOfGroup(UtestShell* test) { return (!test || !test->getNext() || test->getGroup() != test->getNext()->getGroup()); } size_t TestRegistry::countTests() { return tests_ ? tests_->countTests() : 0; } TestRegistry* TestRegistry::currentRegistry_ = NULLPTR; TestRegistry* TestRegistry::getCurrentRegistry() { static TestRegistry registry; return (currentRegistry_ == NULLPTR) ? &registry : currentRegistry_; } void TestRegistry::setCurrentRegistry(TestRegistry* registry) { currentRegistry_ = registry; } void TestRegistry::unDoLastAddTest() { tests_ = tests_ ? tests_->getNext() : NULLPTR; } void TestRegistry::setNameFilters(const TestFilter* filters) { nameFilters_ = filters; } void TestRegistry::setGroupFilters(const TestFilter* filters) { groupFilters_ = filters; } void TestRegistry::setRunIgnored() { runIgnored_ = true; } void TestRegistry::setRunTestsInSeperateProcess() { runInSeperateProcess_ = true; } int TestRegistry::getCurrentRepetition() { return currentRepetition_; } bool TestRegistry::testShouldRun(UtestShell* test, TestResult& result) { if (test->shouldRun(groupFilters_, nameFilters_)) 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_; } void TestRegistry::shuffleTests(size_t seed) { UtestShellPointerArray array(getFirstTest()); array.shuffle(seed); tests_ = array.getFirstTest(); } void TestRegistry::reverseTests() { UtestShellPointerArray array(getFirstTest()); array.reverse(); tests_ = array.getFirstTest(); } UtestShell* TestRegistry::getTestWithNext(UtestShell* test) { UtestShell* current = tests_; while (current && current->getNext() != test) current = current->getNext(); return current; } UtestShell* TestRegistry::findTestWithName(const SimpleString& name) { UtestShell* current = tests_; while (current) { if (current->getName() == name) return current; current = current->getNext(); } return NULLPTR; } UtestShell* TestRegistry::findTestWithGroup(const SimpleString& group) { UtestShell* current = tests_; while (current) { if (current->getGroup() == group) return current; current = current->getNext(); } return NULLPTR; }
null
192
cpp
cpputest
TestOutput.cpp
src/CppUTest/TestOutput.cpp
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 <organization> 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 <copyright holder> 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_(level_quiet), color_(false), progressIndication_(".") { } TestOutput::~TestOutput() { } void TestOutput::verbose(VerbosityLevel level) { verbose_ = level; } void TestOutput::color() { color_ = true; } void TestOutput::print(const char* str) { printBuffer(str); } void TestOutput::print(long n) { print(StringFrom(n).asCharString()); } void TestOutput::print(size_t n) { print(StringFrom(n).asCharString()); } void TestOutput::printDouble(double d) { print(StringFrom(d).asCharString()); } 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_ > level_quiet) print(test.getFormattedName().asCharString()); if (test.willRun()) { setProgressIndicator("."); } else { setProgressIndicator("!"); } } void TestOutput::printCurrentTestEnded(const TestResult& res) { if (verbose_ > level_quiet) { 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::printTestsEnded(const TestResult& result) { print("\n"); const bool isFailure = result.isFailure(); const size_t failureCount = result.getFailureCount(); if (isFailure) { if (color_) { print("\033[31;1m"); } print("Errors ("); if (failureCount > 0) { print(failureCount); print(" failures, "); } else { print("ran nothing, "); } } else { if (color_) { print("\033[32;1m"); } print("OK ("); } 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)"); if (color_) { print("\033[m"); } if (isFailure && failureCount == 0) { print("\nNote: test run failed because no tests were run or ignored. Assuming something went wrong. " "This often happens because of linking errors or typos in test filter."); } print("\n\n"); dotCount_ = 0; } void TestOutput::printTestRun(size_t number, size_t total) { if (total > 1) { print("Test run "); print(number); print(" of "); print(total); print("\n"); } } void TestOutput::printFailure(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, size_t lineNumber) { if (TestOutput::getWorkingEnvironment() == TestOutput::visualStudio) printVisualStudioErrorInFileOnLine(file, lineNumber); else printEclipseErrorInFileOnLine(file, lineNumber); } void TestOutput::printEclipseErrorInFileOnLine(SimpleString file, size_t lineNumber) { print("\n"); print(file.asCharString()); print(":"); print(lineNumber); print(":"); print(" error:"); } void TestOutput::printVisualStudioErrorInFileOnLine(SimpleString file, size_t lineNumber) { print("\n"); print(file.asCharString()); print("("); print(lineNumber); print("):"); print(" error:"); } void TestOutput::printVeryVerbose(const char* str) { if(verbose_ == level_veryVerbose) printBuffer(str); } void ConsoleTestOutput::printBuffer(const char* s) { PlatformSpecificFPuts(s, PlatformSpecificStdOut); flush(); } void ConsoleTestOutput::flush() { PlatformSpecificFlush(); } StringBufferTestOutput::~StringBufferTestOutput() { } CompositeTestOutput::CompositeTestOutput() : outputOne_(NULLPTR), outputTwo_(NULLPTR) { } CompositeTestOutput::~CompositeTestOutput() { delete outputOne_; delete outputTwo_; } void CompositeTestOutput::setOutputOne(TestOutput* output) { delete outputOne_; outputOne_ = output; } void CompositeTestOutput::setOutputTwo(TestOutput* output) { delete outputTwo_; outputTwo_ = output; } void CompositeTestOutput::printTestsStarted() { if (outputOne_) outputOne_->printTestsStarted(); if (outputTwo_) outputTwo_->printTestsStarted(); } void CompositeTestOutput::printTestsEnded(const TestResult& result) { if (outputOne_) outputOne_->printTestsEnded(result); if (outputTwo_) outputTwo_->printTestsEnded(result); } void CompositeTestOutput::printCurrentTestStarted(const UtestShell& test) { if (outputOne_) outputOne_->printCurrentTestStarted(test); if (outputTwo_) outputTwo_->printCurrentTestStarted(test); } void CompositeTestOutput::printCurrentTestEnded(const TestResult& res) { if (outputOne_) outputOne_->printCurrentTestEnded(res); if (outputTwo_) outputTwo_->printCurrentTestEnded(res); } void CompositeTestOutput::printCurrentGroupStarted(const UtestShell& test) { if (outputOne_) outputOne_->printCurrentGroupStarted(test); if (outputTwo_) outputTwo_->printCurrentGroupStarted(test); } void CompositeTestOutput::printCurrentGroupEnded(const TestResult& res) { if (outputOne_) outputOne_->printCurrentGroupEnded(res); if (outputTwo_) outputTwo_->printCurrentGroupEnded(res); } void CompositeTestOutput::verbose(VerbosityLevel level) { if (outputOne_) outputOne_->verbose(level); if (outputTwo_) outputTwo_->verbose(level); } void CompositeTestOutput::color() { if (outputOne_) outputOne_->color(); if (outputTwo_) outputTwo_->color(); } void CompositeTestOutput::printBuffer(const char* buffer) { if (outputOne_) outputOne_->printBuffer(buffer); if (outputTwo_) outputTwo_->printBuffer(buffer); } void CompositeTestOutput::print(const char* buffer) { if (outputOne_) outputOne_->print(buffer); if (outputTwo_) outputTwo_->print(buffer); } void CompositeTestOutput::print(long number) { if (outputOne_) outputOne_->print(number); if (outputTwo_) outputTwo_->print(number); } void CompositeTestOutput::print(size_t number) { if (outputOne_) outputOne_->print(number); if (outputTwo_) outputTwo_->print(number); } void CompositeTestOutput::printDouble(double number) { if (outputOne_) outputOne_->printDouble(number); if (outputTwo_) outputTwo_->printDouble(number); } void CompositeTestOutput::printFailure(const TestFailure& failure) { if (outputOne_) outputOne_->printFailure(failure); if (outputTwo_) outputTwo_->printFailure(failure); } void CompositeTestOutput::setProgressIndicator(const char* indicator) { if (outputOne_) outputOne_->setProgressIndicator(indicator); if (outputTwo_) outputTwo_->setProgressIndicator(indicator); } void CompositeTestOutput::printVeryVerbose(const char* str) { if (outputOne_) outputOne_->printVeryVerbose(str); if (outputTwo_) outputTwo_->printVeryVerbose(str); } void CompositeTestOutput::flush() { if (outputOne_) outputOne_->flush(); if (outputTwo_) outputTwo_->flush(); }
null
193
cpp
cpputest
TestMemoryAllocator.cpp
src/CppUTest/TestMemoryAllocator.cpp
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 <organization> 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 <copyright holder> 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 == NULLPTR) FAIL("malloc returned null pointer"); return mem; } static TestMemoryAllocator* currentNewAllocator = NULLPTR; static TestMemoryAllocator* currentNewArrayAllocator = NULLPTR; static TestMemoryAllocator* currentMallocAllocator = NULLPTR; void setCurrentNewAllocator(TestMemoryAllocator* allocator) { currentNewAllocator = allocator; } TestMemoryAllocator* getCurrentNewAllocator() { if (currentNewAllocator == NULLPTR) 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 == NULLPTR) 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 == NULLPTR) setCurrentMallocAllocatorToDefault(); return currentMallocAllocator; } void setCurrentMallocAllocatorToDefault() { currentMallocAllocator = defaultMallocAllocator(); } TestMemoryAllocator* defaultMallocAllocator() { static TestMemoryAllocator allocator("Standard Malloc Allocator", "malloc", "free"); return &allocator; } ///////////////////////////////////////////// GlobalMemoryAllocatorStash::GlobalMemoryAllocatorStash() : originalMallocAllocator(NULLPTR), originalNewAllocator(NULLPTR), originalNewArrayAllocator(NULLPTR) { } void GlobalMemoryAllocatorStash::save() { originalMallocAllocator = getCurrentMallocAllocator(); originalNewAllocator = getCurrentNewAllocator(); originalNewArrayAllocator = getCurrentNewArrayAllocator(); } void GlobalMemoryAllocatorStash::restore() { if (originalMallocAllocator) setCurrentMallocAllocator(originalMallocAllocator); if (originalNewAllocator) setCurrentNewAllocator(originalNewAllocator); if (originalNewArrayAllocator) setCurrentNewArrayAllocator(originalNewArrayAllocator); } TestMemoryAllocator::TestMemoryAllocator(const char* name_str, const char* alloc_name_str, const char* free_name_str) : name_(name_str), alloc_name_(alloc_name_str), free_name_(free_name_str), hasBeenDestroyed_(false) { } TestMemoryAllocator::~TestMemoryAllocator() { hasBeenDestroyed_ = true; } bool TestMemoryAllocator::hasBeenDestroyed() { return hasBeenDestroyed_; } bool TestMemoryAllocator::isOfEqualType(TestMemoryAllocator* allocator) { return SimpleString::StrCmp(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, 0, "MemoryLeakNode", 1); } char* TestMemoryAllocator::alloc_memory(size_t size, const char*, size_t) { return checkedMalloc(size); } void TestMemoryAllocator::free_memory(char* memory, size_t, const char*, size_t) { PlatformSpecificFree(memory); } const char* TestMemoryAllocator::name() const { return name_; } const char* TestMemoryAllocator::alloc_name() const { return alloc_name_; } const char* TestMemoryAllocator::free_name() const { return free_name_; } TestMemoryAllocator* TestMemoryAllocator::actualAllocator() { return this; } MemoryLeakAllocator::MemoryLeakAllocator(TestMemoryAllocator* originalAllocator) : originalAllocator_(originalAllocator) { } MemoryLeakAllocator::~MemoryLeakAllocator() { } char* MemoryLeakAllocator::alloc_memory(size_t size, const char* file, size_t line) { return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(originalAllocator_, size, file, line); } void MemoryLeakAllocator::free_memory(char* memory, size_t, const char* file, size_t line) { MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(originalAllocator_, memory, file, line); } const char* MemoryLeakAllocator::name() const { return "MemoryLeakAllocator"; } const char* MemoryLeakAllocator::alloc_name() const { return originalAllocator_->alloc_name(); } const char* MemoryLeakAllocator::free_name() const { return originalAllocator_->free_name(); } TestMemoryAllocator* MemoryLeakAllocator::actualAllocator() { return originalAllocator_->actualAllocator(); } CrashOnAllocationAllocator::CrashOnAllocationAllocator() : allocationToCrashOn_(0) { } CrashOnAllocationAllocator::~CrashOnAllocationAllocator() { } void CrashOnAllocationAllocator::setNumberToCrashOn(unsigned allocationToCrashOn) { allocationToCrashOn_ = allocationToCrashOn; } char* CrashOnAllocationAllocator::alloc_memory(size_t size, const char* file, size_t line) { if (MemoryLeakWarningPlugin::getGlobalDetector()->getCurrentAllocationNumber() == allocationToCrashOn_) UT_CRASH(); return TestMemoryAllocator::alloc_memory(size, file, line); } NullUnknownAllocator::~NullUnknownAllocator() { } char* NullUnknownAllocator::alloc_memory(size_t /*size*/, const char*, size_t) { return NULLPTR; } void NullUnknownAllocator::free_memory(char* /*memory*/, size_t, const char*, size_t) { } NullUnknownAllocator::NullUnknownAllocator() : TestMemoryAllocator("Null Allocator", "unknown", "unknown") { } TestMemoryAllocator* NullUnknownAllocator::defaultAllocator() { static NullUnknownAllocator allocator; return &allocator; } class LocationToFailAllocNode { public: int allocNumberToFail_; int actualAllocNumber_; const char* file_; size_t line_; LocationToFailAllocNode* next_; void failAtAllocNumber(int number, LocationToFailAllocNode* next) { init(next); allocNumberToFail_ = number; } void failNthAllocAt(int allocationNumber, const char* file, size_t line, LocationToFailAllocNode* next) { init(next); allocNumberToFail_ = allocationNumber; file_ = file; line_ = line; } bool shouldFail(int allocationNumber, const char* file, size_t line) { if (file_ && SimpleString::StrCmp(file, file_) == 0 && line == line_) { actualAllocNumber_++; return actualAllocNumber_ == allocNumberToFail_; } if (allocationNumber == allocNumberToFail_) return true; return false; } private: void init(LocationToFailAllocNode* next = NULLPTR) { allocNumberToFail_ = 0; actualAllocNumber_ = 0; file_ = NULLPTR; line_ = 0; next_ = next; } }; FailableMemoryAllocator::~FailableMemoryAllocator() { } FailableMemoryAllocator::FailableMemoryAllocator(const char* name_str, const char* alloc_name_str, const char* free_name_str) : TestMemoryAllocator(name_str, alloc_name_str, free_name_str), head_(NULLPTR), currentAllocNumber_(0) { } void FailableMemoryAllocator::failAllocNumber(int number) { LocationToFailAllocNode* newNode = (LocationToFailAllocNode*) (void*) allocMemoryLeakNode(sizeof(LocationToFailAllocNode)); newNode->failAtAllocNumber(number, head_); head_ = newNode; } void FailableMemoryAllocator::failNthAllocAt(int allocationNumber, const char* file, size_t line) { LocationToFailAllocNode* newNode = (LocationToFailAllocNode*) (void*) allocMemoryLeakNode(sizeof(LocationToFailAllocNode)); newNode->failNthAllocAt(allocationNumber, file, line, head_); head_ = newNode; } char* FailableMemoryAllocator::alloc_memory(size_t size, const char* file, size_t line) { currentAllocNumber_++; LocationToFailAllocNode* current = head_; LocationToFailAllocNode* previous = NULLPTR; while (current) { if (current->shouldFail(currentAllocNumber_, file, line)) { if (previous) previous->next_ = current->next_; else head_ = current->next_; free_memory((char*) current, size, __FILE__, __LINE__); return NULLPTR; } previous = current; current = current->next_; } return TestMemoryAllocator::alloc_memory(size, file, line); } char* FailableMemoryAllocator::allocMemoryLeakNode(size_t size) { return (char*)PlatformSpecificMalloc(size); } void FailableMemoryAllocator::checkAllFailedAllocsWereDone() { if (head_) { UtestShell* currentTest = UtestShell::getCurrent(); SimpleString failText; if (head_->file_) failText = StringFromFormat("Expected failing alloc at %s:%d was never done", head_->file_, (int) head_->line_); else failText = StringFromFormat("Expected allocation number %d was never done", (int) head_->allocNumberToFail_); currentTest->failWith(FailFailure(currentTest, currentTest->getName().asCharString(), currentTest->getLineNumber(), failText)); } } void FailableMemoryAllocator::clearFailedAllocs() { LocationToFailAllocNode* current = head_; while (current) { head_ = current->next_; free_memory((char*) current, 0, __FILE__, __LINE__); current = head_; } currentAllocNumber_ = 0; } struct MemoryAccountantAllocationNode { size_t size_; size_t allocations_; size_t deallocations_; size_t maxAllocations_; size_t currentAllocations_; MemoryAccountantAllocationNode* next_; }; MemoryAccountantAllocationNode* MemoryAccountant::createNewAccountantAllocationNode(size_t size, MemoryAccountantAllocationNode* next) const { MemoryAccountantAllocationNode* node = (MemoryAccountantAllocationNode*) (void*) allocator_->alloc_memory(sizeof(MemoryAccountantAllocationNode), __FILE__, __LINE__); node->size_ = size; node->allocations_ = 0; node->deallocations_ = 0; node->maxAllocations_ = 0; node->currentAllocations_ = 0; node->next_ = next; return node; } void MemoryAccountant::destroyAccountantAllocationNode(MemoryAccountantAllocationNode* node) const { allocator_->free_memory((char*) node, sizeof(*node), __FILE__, __LINE__); } MemoryAccountant::MemoryAccountant() : head_(NULLPTR), allocator_(defaultMallocAllocator()), useCacheSizes_(false) { } MemoryAccountant::~MemoryAccountant() { clear(); } void MemoryAccountant::createCacheSizeNodes(size_t sizes[], size_t length) { for (size_t i = 0; i < length; i++) findOrCreateNodeOfSize(sizes[i]); if (head_ == NULLPTR) head_ = createNewAccountantAllocationNode(0, NULLPTR); else { for (MemoryAccountantAllocationNode* lastNode = head_; lastNode; lastNode = lastNode->next_) { if (lastNode->next_ == NULLPTR) { lastNode->next_ = createNewAccountantAllocationNode(0, NULLPTR); break; } } } } void MemoryAccountant::useCacheSizes(size_t sizes[], size_t length) { if (head_) FAIL("MemoryAccountant: Cannot set cache sizes as allocations already occured!"); createCacheSizeNodes(sizes, length); useCacheSizes_ = true; } void MemoryAccountant::setAllocator(TestMemoryAllocator* allocator) { allocator_ = allocator; } void MemoryAccountant::clear() { MemoryAccountantAllocationNode* node = head_; MemoryAccountantAllocationNode* to_be_deleted = NULLPTR; while (node) { to_be_deleted = node; node = node->next_; destroyAccountantAllocationNode(to_be_deleted); } head_ = NULLPTR; } MemoryAccountantAllocationNode* MemoryAccountant::findNodeOfSize(size_t size) const { if (useCacheSizes_) { for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) { if (((size > node->size_) && (node->next_ == NULLPTR)) || ((size <= node->size_) && !((node->next_->size_ != 0) && (node->next_->size_ <= size)))) return node; } } else for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) if (node->size_ == size) return node; return NULLPTR; } MemoryAccountantAllocationNode* MemoryAccountant::findOrCreateNodeOfSize(size_t size) { if (useCacheSizes_) return findNodeOfSize(size); if (head_ && head_->size_ > size) head_ = createNewAccountantAllocationNode(size, head_); for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) { if (node->size_ == size) return node; if (node->next_ == NULLPTR || node->next_->size_ > size) node->next_ = createNewAccountantAllocationNode(size, node->next_); } head_ = createNewAccountantAllocationNode(size, head_); return head_; } void MemoryAccountant::alloc(size_t size) { MemoryAccountantAllocationNode* node = findOrCreateNodeOfSize(size); node->allocations_++; node->currentAllocations_++; node->maxAllocations_ = (node->currentAllocations_ > node->maxAllocations_) ? node->currentAllocations_ : node->maxAllocations_; } void MemoryAccountant::dealloc(size_t size) { MemoryAccountantAllocationNode* node = findOrCreateNodeOfSize(size); node->deallocations_++; if (node->currentAllocations_) node->currentAllocations_--; } size_t MemoryAccountant::totalAllocationsOfSize(size_t size) const { MemoryAccountantAllocationNode* node = findNodeOfSize(size); if (node) return node->allocations_; return 0; } size_t MemoryAccountant::totalDeallocationsOfSize(size_t size) const { MemoryAccountantAllocationNode* node = findNodeOfSize(size); if (node) return node->deallocations_; return 0; } size_t MemoryAccountant::maximumAllocationAtATimeOfSize(size_t size) const { MemoryAccountantAllocationNode* node = findNodeOfSize(size); if (node) return node->maxAllocations_; return 0; } size_t MemoryAccountant::totalAllocations() const { size_t theTotalAllocations = 0; for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) theTotalAllocations += node->allocations_; return theTotalAllocations; } size_t MemoryAccountant::totalDeallocations() const { size_t theTotalDeallocations = 0; for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) theTotalDeallocations += node->deallocations_; return theTotalDeallocations; } SimpleString MemoryAccountant::reportNoAllocations() const { return SimpleString("CppUTest Memory Accountant has not noticed any allocations or deallocations. Sorry\n"); } SimpleString MemoryAccountant::reportTitle() const { if (useCacheSizes_) return "CppUTest Memory Accountant report (with cache sizes):\n"; return "CppUTest Memory Accountant report:\n"; } SimpleString MemoryAccountant::reportHeader() const { if (useCacheSizes_) return "Cache size # allocations # deallocations max # allocations at one time\n"; return "Allocation size # allocations # deallocations max # allocations at one time\n"; } #define MEMORY_ACCOUNTANT_ROW_FORMAT "%s %5d %5d %5d\n" SimpleString MemoryAccountant::reportFooter() const { return SimpleString(" Thank you for your business\n"); } SimpleString MemoryAccountant::stringSize(size_t size) const { return (size == 0) ? StringFrom("other") : StringFromFormat("%5d", (int) size); } SimpleString MemoryAccountant::report() const { if (head_ == NULLPTR) return reportNoAllocations(); SimpleString accountantReport = reportTitle() + reportHeader(); for (MemoryAccountantAllocationNode* node = head_; node; node = node->next_) accountantReport += StringFromFormat(MEMORY_ACCOUNTANT_ROW_FORMAT, stringSize(node->size_).asCharString(), (int) node->allocations_, (int) node->deallocations_, (int) node->maxAllocations_); return accountantReport + reportFooter(); } AccountingTestMemoryAllocator::AccountingTestMemoryAllocator(MemoryAccountant& accountant, TestMemoryAllocator* origAllocator) : accountant_(accountant), originalAllocator_(origAllocator), head_(NULLPTR) { } AccountingTestMemoryAllocator::~AccountingTestMemoryAllocator() { } struct AccountingTestMemoryAllocatorMemoryNode { char* memory_; size_t size_; AccountingTestMemoryAllocatorMemoryNode* next_; }; void AccountingTestMemoryAllocator::addMemoryToMemoryTrackingToKeepTrackOfSize(char* memory, size_t size) { AccountingTestMemoryAllocatorMemoryNode* node = (AccountingTestMemoryAllocatorMemoryNode*) (void*) originalAllocator_->alloc_memory(sizeof(AccountingTestMemoryAllocatorMemoryNode), __FILE__, __LINE__); node->memory_ = memory; node->size_ = size; node->next_ = head_; head_ = node; } size_t AccountingTestMemoryAllocator::removeNextNodeAndReturnSize(AccountingTestMemoryAllocatorMemoryNode* node) { AccountingTestMemoryAllocatorMemoryNode* foundNode = node->next_; node->next_ = node->next_->next_; size_t size = foundNode->size_; originalAllocator_->free_memory((char*) foundNode, size, __FILE__, __LINE__); return size; } size_t AccountingTestMemoryAllocator::removeHeadAndReturnSize() { AccountingTestMemoryAllocatorMemoryNode* foundNode = head_; head_ = head_->next_; size_t size = foundNode->size_; originalAllocator_->free_memory((char*) foundNode, size, __FILE__, __LINE__); return size; } size_t AccountingTestMemoryAllocator::removeMemoryFromTrackingAndReturnAllocatedSize(char* memory) { if (head_ && head_->memory_ == memory) return removeHeadAndReturnSize(); for (AccountingTestMemoryAllocatorMemoryNode* node = head_; node; node = node->next_) { if (node->next_ && node->next_->memory_ == memory) return removeNextNodeAndReturnSize(node); } return 0; } char* AccountingTestMemoryAllocator::alloc_memory(size_t size, const char* file, size_t line) { accountant_.alloc(size); char* memory = originalAllocator_->alloc_memory(size, file, line); addMemoryToMemoryTrackingToKeepTrackOfSize(memory, size); return memory; } void AccountingTestMemoryAllocator::free_memory(char* memory, size_t, const char* file, size_t line) { size_t size = removeMemoryFromTrackingAndReturnAllocatedSize(memory); accountant_.dealloc(size); originalAllocator_->free_memory(memory, size, file, line); } TestMemoryAllocator* AccountingTestMemoryAllocator::actualAllocator() { return originalAllocator_->actualAllocator(); } TestMemoryAllocator* AccountingTestMemoryAllocator::originalAllocator() { return originalAllocator_; } const char* AccountingTestMemoryAllocator::alloc_name() const { return originalAllocator_->alloc_name(); } const char* AccountingTestMemoryAllocator::free_name() const { return originalAllocator_->free_name(); } GlobalMemoryAccountant::GlobalMemoryAccountant() : mallocAllocator_(NULLPTR), newAllocator_(NULLPTR), newArrayAllocator_(NULLPTR) { } GlobalMemoryAccountant::~GlobalMemoryAccountant() { restoreMemoryAllocators(); delete mallocAllocator_; delete newAllocator_; delete newArrayAllocator_; } void GlobalMemoryAccountant::useCacheSizes(size_t sizes[], size_t length) { accountant_.useCacheSizes(sizes, length); } void GlobalMemoryAccountant::start() { if (mallocAllocator_ != NULLPTR) FAIL("Global allocator start called twice!"); mallocAllocator_ = new AccountingTestMemoryAllocator(accountant_, getCurrentMallocAllocator()); newAllocator_ = new AccountingTestMemoryAllocator(accountant_, getCurrentNewAllocator()); newArrayAllocator_ = new AccountingTestMemoryAllocator(accountant_, getCurrentNewArrayAllocator()); accountant_.setAllocator(getCurrentMallocAllocator()); setCurrentMallocAllocator(mallocAllocator_); setCurrentNewAllocator(newAllocator_); setCurrentNewArrayAllocator(newArrayAllocator_); } void GlobalMemoryAccountant::restoreMemoryAllocators() { if (getCurrentMallocAllocator() == mallocAllocator_) setCurrentMallocAllocator(mallocAllocator_->originalAllocator()); if (getCurrentNewAllocator() == newAllocator_) setCurrentNewAllocator(newAllocator_->originalAllocator()); if (getCurrentNewArrayAllocator() == newArrayAllocator_) setCurrentNewArrayAllocator(newArrayAllocator_->originalAllocator()); } void GlobalMemoryAccountant::stop() { if (mallocAllocator_ == NULLPTR) FAIL("GlobalMemoryAccount: Stop called without starting"); if (getCurrentMallocAllocator() != mallocAllocator_) FAIL("GlobalMemoryAccountant: Malloc memory allocator has been changed while accounting for memory"); if (getCurrentNewAllocator() != newAllocator_) FAIL("GlobalMemoryAccountant: New memory allocator has been changed while accounting for memory"); if (getCurrentNewArrayAllocator() != newArrayAllocator_) FAIL("GlobalMemoryAccountant: New Array memory allocator has been changed while accounting for memory"); restoreMemoryAllocators(); } SimpleString GlobalMemoryAccountant::report() { return accountant_.report(); } TestMemoryAllocator* GlobalMemoryAccountant::getMallocAllocator() { return mallocAllocator_; } TestMemoryAllocator* GlobalMemoryAccountant::getNewAllocator() { return newAllocator_; } TestMemoryAllocator* GlobalMemoryAccountant::getNewArrayAllocator() { return newArrayAllocator_; }
null
194
cpp
cpputest
CommandLineArguments.cpp
src/CppUTest/CommandLineArguments.cpp
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 <organization> 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 <copyright holder> 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 *const *av) : ac_(ac), av_(av), needHelp_(false), verbose_(false), veryVerbose_(false), color_(false), runTestsAsSeperateProcess_(false), listTestGroupNames_(false), listTestGroupAndCaseNames_(false), listTestLocations_(false), runIgnored_(false), reversing_(false), crashOnFail_(false), rethrowExceptions_(true), shuffling_(false), shufflingPreSeeded_(false), repeat_(1), shuffleSeed_(0), groupFilters_(NULLPTR), nameFilters_(NULLPTR), outputType_(OUTPUT_ECLIPSE) { } CommandLineArguments::~CommandLineArguments() { while(groupFilters_) { TestFilter* current = groupFilters_; groupFilters_ = groupFilters_->getNext(); delete current; } while(nameFilters_) { TestFilter* current = nameFilters_; nameFilters_ = nameFilters_->getNext(); delete current; } } bool CommandLineArguments::parse(TestPlugin* plugin) { bool correctParameters = true; for (int i = 1; i < ac_; i++) { SimpleString argument = av_[i]; if (argument == "-h") { needHelp_ = true; correctParameters = false; } else if (argument == "-v") verbose_ = true; else if (argument == "-vv") veryVerbose_ = true; else if (argument == "-c") color_ = true; else if (argument == "-p") runTestsAsSeperateProcess_ = true; else if (argument == "-b") reversing_ = true; else if (argument == "-lg") listTestGroupNames_ = true; else if (argument == "-ln") listTestGroupAndCaseNames_ = true; else if (argument == "-ll") listTestLocations_ = true; else if (argument == "-ri") runIgnored_ = true; else if (argument == "-f") crashOnFail_ = true; else if ((argument == "-e") || (argument == "-ci")) rethrowExceptions_ = false; else if (argument.startsWith("-r")) setRepeatCount(ac_, av_, i); else if (argument.startsWith("-g")) addGroupFilter(ac_, av_, i); else if (argument.startsWith("-t")) correctParameters = addGroupDotNameFilter(ac_, av_, i, "-t", false, false); else if (argument.startsWith("-st")) correctParameters = addGroupDotNameFilter(ac_, av_, i, "-st", true, false); else if (argument.startsWith("-xt")) correctParameters = addGroupDotNameFilter(ac_, av_, i, "-xt", false, true); else if (argument.startsWith("-xst")) correctParameters = addGroupDotNameFilter(ac_, av_, i, "-xst", true, true); else if (argument.startsWith("-sg")) addStrictGroupFilter(ac_, av_, i); else if (argument.startsWith("-xg")) addExcludeGroupFilter(ac_, av_, i); else if (argument.startsWith("-xsg")) addExcludeStrictGroupFilter(ac_, av_, i); else if (argument.startsWith("-n")) addNameFilter(ac_, av_, i); else if (argument.startsWith("-sn")) addStrictNameFilter(ac_, av_, i); else if (argument.startsWith("-xn")) addExcludeNameFilter(ac_, av_, i); else if (argument.startsWith("-xsn")) addExcludeStrictNameFilter(ac_, av_, i); else if (argument.startsWith("-s")) correctParameters = setShuffle(ac_, av_, i); else if (argument.startsWith("TEST(")) addTestToRunBasedOnVerboseOutput(ac_, av_, i, "TEST("); else if (argument.startsWith("IGNORE_TEST(")) addTestToRunBasedOnVerboseOutput(ac_, av_, i, "IGNORE_TEST("); else if (argument.startsWith("-o")) correctParameters = setOutputType(ac_, av_, i); else if (argument.startsWith("-p")) correctParameters = plugin->parseAllArguments(ac_, av_, i); else if (argument.startsWith("-k")) setPackageName(ac_, av_, i); else correctParameters = false; if (correctParameters == false) { return false; } } return true; } const char* CommandLineArguments::usage() const { return "use -h for more extensive help\n" "usage [-h] [-v] [-vv] [-c] [-p] [-lg] [-ln] [-ll] [-ri] [-r[<#>]] [-f] [-e] [-ci]\n" " [-g|sg|xg|xsg <groupName>]... [-n|sn|xn|xsn <testName>]... [-t|st|xt|xst <groupName>.<testName>]...\n" " [-b] [-s [<seed>]] [\"[IGNORE_]TEST(<groupName>, <testName>)\"]...\n" " [-o{normal|eclipse|junit|teamcity}] [-k <packageName>]\n"; } const char* CommandLineArguments::help() const { return "Thanks for using CppUTest.\n" "\n" "Options that do not run tests but query:\n" " -h - this wonderful help screen. Joy!\n" " -lg - print a list of group names, separated by spaces\n" " -ln - print a list of test names in the form of group.name, separated by spaces\n" " -ll - print a list of test names in the form of group.name.test_file_path.line\n" "\n" "Options that change the output format:\n" " -c - colorize output, print green if OK, or red if failed\n" " -v - verbose, print each test name as it runs\n" " -vv - very verbose, print internal information during test run\n" "\n" "Options that change the output location:\n" " -onormal - no output to files\n" " -oeclipse - equivalent to -onormal\n" " -oteamcity - output to xml files (as the name suggests, for TeamCity)\n" " -ojunit - output to JUnit ant plugin style xml files (for CI systems)\n" " -k <packageName> - add a package name in JUnit output (for classification in CI systems)\n" "\n" "\n" "Options that control which tests are run:\n" " -g <group> - only run tests whose group contains <group>\n" " -n <name> - only run tests whose name contains <name>\n" " -t <group>.<name> - only run tests whose group and name contain <group> and <name>\n" " -sg <group> - only run tests whose group exactly matches <group>\n" " -sn <name> - only run tests whose name exactly matches <name>\n" " -st <grp>.<name> - only run tests whose group and name exactly match <grp> and <name>\n" " -xg <group> - exclude tests whose group contains <group>\n" " -xn <name> - exclude tests whose name contains <name>\n" " -xt <grp>.<name> - exclude tests whose group and name contain <grp> and <name>\n" " -xsg <group> - exclude tests whose group exactly matches <group>\n" " -xsn <name> - exclude tests whose name exactly matches <name>\n" " -xst <grp>.<name> - exclude tests whose group and name exactly match <grp> and <name>\n" " \"[IGNORE_]TEST(<group>, <name>)\"\n" " - only run tests whose group and name exactly match <group> and <name>\n" " (this can be used to copy-paste output from the -v option on the command line)\n" "\n" "Options that control how the tests are run:\n" " -p - run tests in a separate process\n" " -b - run the tests backwards, reversing the normal way\n" " -s [<seed>] - shuffle tests randomly (randomization seed is optional, must be greater than 0)\n" " -r[<#>] - repeat the tests <#> times (or twice if <#> is not specified)\n" " -f - Cause the tests to crash on failure (to allow the test to be debugged if necessary)\n" " -e - do not rethrow unexpected exceptions on failure\n" " -ci - continuous integration mode (equivalent to -e)\n"; } bool CommandLineArguments::needHelp() const { return needHelp_; } bool CommandLineArguments::isVerbose() const { return verbose_; } bool CommandLineArguments::isVeryVerbose() const { return veryVerbose_; } bool CommandLineArguments::isColor() const { return color_; } bool CommandLineArguments::isListingTestGroupNames() const { return listTestGroupNames_; } bool CommandLineArguments::isListingTestGroupAndCaseNames() const { return listTestGroupAndCaseNames_; } bool CommandLineArguments::isListingTestLocations() const { return listTestLocations_; } bool CommandLineArguments::isRunIgnored() const { return runIgnored_; } bool CommandLineArguments::runTestsInSeperateProcess() const { return runTestsAsSeperateProcess_; } size_t CommandLineArguments::getRepeatCount() const { return repeat_; } bool CommandLineArguments::isReversing() const { return reversing_; } bool CommandLineArguments::isCrashingOnFail() const { return crashOnFail_; } bool CommandLineArguments::isRethrowingExceptions() const { return rethrowExceptions_; } bool CommandLineArguments::isShuffling() const { return shuffling_; } size_t CommandLineArguments::getShuffleSeed() const { return shuffleSeed_; } const TestFilter* CommandLineArguments::getGroupFilters() const { return groupFilters_; } const TestFilter* CommandLineArguments::getNameFilters() const { return nameFilters_; } void CommandLineArguments::setRepeatCount(int ac, const char *const *av, int& i) { repeat_ = 0; SimpleString repeatParameter(av[i]); if (repeatParameter.size() > 2) repeat_ = (size_t) (SimpleString::AtoI(av[i] + 2)); else if (i + 1 < ac) { repeat_ = (size_t) (SimpleString::AtoI(av[i + 1])); if (repeat_ != 0) i++; } if (0 == repeat_) repeat_ = 2; } bool CommandLineArguments::setShuffle(int ac, const char * const *av, int& i) { shuffling_ = true; shuffleSeed_ = (unsigned int)GetPlatformSpecificTimeInMillis(); if (shuffleSeed_ == 0) shuffleSeed_++; SimpleString shuffleParameter = av[i]; if (shuffleParameter.size() > 2) { shufflingPreSeeded_ = true; shuffleSeed_ = SimpleString::AtoU(av[i] + 2); } else if (i + 1 < ac) { unsigned int parsedParameter = SimpleString::AtoU(av[i + 1]); if (parsedParameter != 0) { shufflingPreSeeded_ = true; shuffleSeed_ = parsedParameter; i++; } } return (shuffleSeed_ != 0); } SimpleString CommandLineArguments::getParameterField(int ac, const char * const *av, int& i, const SimpleString& parameterName) { size_t parameterLength = parameterName.size(); SimpleString parameter(av[i]); if (parameter.size() > parameterLength) return av[i] + parameterLength; else if (i + 1 < ac) return av[++i]; return ""; } void CommandLineArguments::addGroupFilter(int ac, const char *const *av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-g")); groupFilters_ = groupFilter->add(groupFilters_); } bool CommandLineArguments::addGroupDotNameFilter(int ac, const char *const *av, int& i, const SimpleString& parameterName, bool strict, bool exclude) { SimpleString groupDotName = getParameterField(ac, av, i, parameterName); SimpleStringCollection collection; groupDotName.split(".", collection); if (collection.size() != 2) return false; TestFilter* groupFilter = new TestFilter(collection[0].subString(0, collection[0].size()-1)); TestFilter* nameFilter = new TestFilter(collection[1]); if (strict) { groupFilter->strictMatching(); nameFilter->strictMatching(); } if (exclude) { groupFilter->invertMatching(); nameFilter->invertMatching(); } groupFilters_ = groupFilter->add(groupFilters_); nameFilters_ = nameFilter->add(nameFilters_); return true; } void CommandLineArguments::addStrictGroupFilter(int ac, const char *const *av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-sg")); groupFilter->strictMatching(); groupFilters_ = groupFilter->add(groupFilters_); } void CommandLineArguments::addExcludeGroupFilter(int ac, const char *const *av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-xg")); groupFilter->invertMatching(); groupFilters_ = groupFilter->add(groupFilters_); } void CommandLineArguments::addExcludeStrictGroupFilter(int ac, const char *const *av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-xsg")); groupFilter->strictMatching(); groupFilter->invertMatching(); groupFilters_ = groupFilter->add(groupFilters_); } void CommandLineArguments::addNameFilter(int ac, const char *const *av, int& i) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, i, "-n")); nameFilters_ = nameFilter->add(nameFilters_); } void CommandLineArguments::addStrictNameFilter(int ac, const char *const *av, int& index) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, index, "-sn")); nameFilter->strictMatching(); nameFilters_= nameFilter->add(nameFilters_); } void CommandLineArguments::addExcludeNameFilter(int ac, const char *const *av, int& index) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, index, "-xn")); nameFilter->invertMatching(); nameFilters_= nameFilter->add(nameFilters_); } void CommandLineArguments::addExcludeStrictNameFilter(int ac, const char *const *av, int& index) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, index, "-xsn")); nameFilter->invertMatching(); nameFilter->strictMatching(); nameFilters_= nameFilter->add(nameFilters_); } void CommandLineArguments::addTestToRunBasedOnVerboseOutput(int ac, const char *const *av, int& index, const char* parameterName) { SimpleString wholename = getParameterField(ac, av, index, parameterName); SimpleString testname = wholename.subStringFromTill(',', ')'); testname = testname.subString(2); TestFilter* namefilter = new TestFilter(testname); TestFilter* groupfilter = new TestFilter(wholename.subStringFromTill(wholename.at(0), ',')); namefilter->strictMatching(); groupfilter->strictMatching(); groupFilters_ = groupfilter->add(groupFilters_); nameFilters_ = namefilter->add(nameFilters_); } void CommandLineArguments::setPackageName(int ac, const char *const *av, int& i) { SimpleString packageName = getParameterField(ac, av, i, "-k"); if (packageName.size() == 0) return; packageName_ = packageName; } bool CommandLineArguments::setOutputType(int ac, const char *const *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; } if (outputType == "teamcity") { outputType_ = OUTPUT_TEAMCITY; return true; } return false; } bool CommandLineArguments::isEclipseOutput() const { return outputType_ == OUTPUT_ECLIPSE; } bool CommandLineArguments::isJUnitOutput() const { return outputType_ == OUTPUT_JUNIT; } bool CommandLineArguments::isTeamCityOutput() const { return outputType_ == OUTPUT_TEAMCITY; } const SimpleString& CommandLineArguments::getPackageName() const { return packageName_; }
null
195
cpp
cpputest
JUnitTestOutput.cpp
src/CppUTest/JUnitTestOutput.cpp
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 <organization> 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 <copyright holder> 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_(NULLPTR), ignored_(false), lineNumber_ (0), checkCount_ (0), next_(NULLPTR) { } SimpleString name_; size_t execTime_; TestFailure* failure_; bool ignored_; SimpleString file_; size_t lineNumber_; size_t checkCount_; JUnitTestCaseResultNode* next_; }; struct JUnitTestGroupResult { JUnitTestGroupResult() : testCount_(0), failureCount_(0), totalCheckCount_(0), startTime_(0), groupExecTime_(0), head_(NULLPTR), tail_(NULLPTR) { } size_t testCount_; size_t failureCount_; size_t totalCheckCount_; size_t startTime_; size_t groupExecTime_; SimpleString group_; JUnitTestCaseResultNode* head_; JUnitTestCaseResultNode* tail_; }; struct JUnitTestOutputImpl { JUnitTestGroupResult results_; PlatformSpecificFile file_; SimpleString package_; SimpleString stdOutput_; }; 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_; delete cur->failure_; delete cur; cur = tmp; } impl_->results_.head_ = NULLPTR; impl_->results_.tail_ = NULLPTR; } void JUnitTestOutput::printTestsStarted() { } void JUnitTestOutput::printCurrentGroupStarted(const UtestShell& /*test*/) { } void JUnitTestOutput::printCurrentTestEnded(const TestResult& result) { impl_->results_.tail_->execTime_ = result.getCurrentTestTotalExecutionTime(); impl_->results_.tail_->checkCount_ = result.getCheckCount(); } 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_ = (size_t) GetPlatformSpecificTimeInMillis(); if (impl_->results_.tail_ == NULLPTR) { 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(); impl_->results_.tail_->file_ = test.getFile(); impl_->results_.tail_->lineNumber_ = test.getLineNumber(); if (!test.willRun()) { impl_->results_.tail_->ignored_ = true; } } SimpleString JUnitTestOutput::createFileName(const SimpleString& group) { SimpleString fileName = "cpputest_"; if (!impl_->package_.isEmpty()) { fileName += impl_->package_; fileName += "_"; } fileName += group; return encodeFileName(fileName) + ".xml"; } SimpleString JUnitTestOutput::encodeFileName(const SimpleString& fileName) { // special character list based on: https://en.wikipedia.org/wiki/Filename static const char* const forbiddenCharacters = "/\\?%*:|\"<>"; SimpleString result = fileName; for (const char* sym = forbiddenCharacters; *sym; ++sym) { result.replace(*sym, '_'); } return result; } void JUnitTestOutput::setPackageName(const SimpleString& package) { if (impl_ != NULLPTR) { impl_->package_ = package; } } void JUnitTestOutput::writeXmlHeader() { writeToFile("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); } void JUnitTestOutput::writeTestSuiteSummary() { SimpleString buf = StringFromFormat( "<testsuite errors=\"0\" failures=\"%d\" hostname=\"localhost\" name=\"%s\" tests=\"%d\" time=\"%d.%03d\" timestamp=\"%s\">\n", (int)impl_->results_.failureCount_, impl_->results_.group_.asCharString(), (int) impl_->results_.testCount_, (int) (impl_->results_.groupExecTime_ / 1000), (int) (impl_->results_.groupExecTime_ % 1000), GetPlatformSpecificTimeString()); writeToFile(buf.asCharString()); } void JUnitTestOutput::writeProperties() { writeToFile("<properties>\n"); writeToFile("</properties>\n"); } SimpleString JUnitTestOutput::encodeXmlText(const SimpleString& textbody) { SimpleString buf = textbody.asCharString(); buf.replace("&", "&amp;"); buf.replace("\"", "&quot;"); buf.replace("<", "&lt;"); buf.replace(">", "&gt;"); buf.replace("\r", "&#13;"); buf.replace("\n", "&#10;"); return buf; } void JUnitTestOutput::writeTestCases() { JUnitTestCaseResultNode* cur = impl_->results_.head_; while (cur) { SimpleString buf = StringFromFormat( "<testcase classname=\"%s%s%s\" name=\"%s\" assertions=\"%d\" time=\"%d.%03d\" file=\"%s\" line=\"%d\">\n", impl_->package_.asCharString(), impl_->package_.isEmpty() ? "" : ".", impl_->results_.group_.asCharString(), cur->name_.asCharString(), (int) (cur->checkCount_ - impl_->results_.totalCheckCount_), (int) (cur->execTime_ / 1000), (int)(cur->execTime_ % 1000), cur->file_.asCharString(), (int) cur->lineNumber_); writeToFile(buf.asCharString()); impl_->results_.totalCheckCount_ = cur->checkCount_; if (cur->failure_) { writeFailure(cur); } else if (cur->ignored_) { writeToFile("<skipped />\n"); } writeToFile("</testcase>\n"); cur = cur->next_; } } void JUnitTestOutput::writeFailure(JUnitTestCaseResultNode* node) { SimpleString buf = StringFromFormat( "<failure message=\"%s:%d: %s\" type=\"AssertionFailedError\">\n", node->failure_->getFileName().asCharString(), (int) node->failure_->getFailureLineNumber(), encodeXmlText(node->failure_->getMessage()).asCharString()); writeToFile(buf.asCharString()); writeToFile("</failure>\n"); } void JUnitTestOutput::writeFileEnding() { writeToFile("<system-out>"); writeToFile(encodeXmlText(impl_->stdOutput_)); writeToFile("</system-out>\n"); writeToFile("<system-err></system-err>\n"); writeToFile("</testsuite>\n"); } void JUnitTestOutput::writeTestGroupToFile() { openFileForWrite(createFileName(impl_->results_.group_)); writeXmlHeader(); writeTestSuiteSummary(); writeProperties(); writeTestCases(); writeFileEnding(); closeFile(); } // LCOV_EXCL_START void JUnitTestOutput::printBuffer(const char*) { } void JUnitTestOutput::print(const char *output) { impl_->stdOutput_ += output; } void JUnitTestOutput::print(long) { } void JUnitTestOutput::print(size_t) { } void JUnitTestOutput::flush() { } // LCOV_EXCL_STOP void JUnitTestOutput::printFailure(const TestFailure& failure) { if (impl_->results_.tail_->failure_ == NULLPTR) { impl_->results_.failureCount_++; impl_->results_.tail_->failure_ = new TestFailure(failure); } } 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_); }
null
196
cpp
cpputest
Utest.cpp
src/CppUTest/Utest.cpp
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 <organization> 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 <copyright holder> 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/PlatformSpecificFunctions.h" #include "CppUTest/TestOutput.h" #if defined(__GNUC__) && __GNUC__ >= 11 # define NEEDS_DISABLE_NULL_WARNING #endif /* GCC >= 11 */ bool doubles_equal(double d1, double d2, double threshold) { if (PlatformSpecificIsNan(d1) || PlatformSpecificIsNan(d2) || PlatformSpecificIsNan(threshold)) return false; if (PlatformSpecificIsInf(d1) && PlatformSpecificIsInf(d2)) { return true; } return PlatformSpecificFabs(d1 - d2) <= threshold; } /* Sometimes stubs use the CppUTest assertions. * Its not correct to do so, but this small helper class will prevent a segmentation fault and instead * will give an error message and also the file/line of the check that was executed outside the tests. */ class OutsideTestRunnerUTest: public UtestShell { public: static OutsideTestRunnerUTest& instance(); virtual TestResult& getTestResult() { return defaultTestResult; } virtual ~OutsideTestRunnerUTest() CPPUTEST_DESTRUCTOR_OVERRIDE { } private: OutsideTestRunnerUTest() : UtestShell("\n\t NOTE: Assertion happened without being in a test run (perhaps in main?)", "\n\t Something is very wrong. Check this assertion and fix", "unknown file", 0), defaultTestResult(defaultOutput) { } ConsoleTestOutput defaultOutput; TestResult defaultTestResult; }; OutsideTestRunnerUTest& OutsideTestRunnerUTest::instance() { static OutsideTestRunnerUTest instance_; return instance_; } /* * Below helpers are used for the PlatformSpecificSetJmp and LongJmp. They pass a method for what needs to happen after * the jump, so that the stack stays right. * */ extern "C" { static void helperDoTestSetup(void* data) { ((Utest*)data)->setup(); } static void helperDoTestBody(void* data) { ((Utest*)data)->testBody(); } static void helperDoTestTeardown(void* data) { ((Utest*)data)->teardown(); } struct HelperTestRunInfo { HelperTestRunInfo(UtestShell* shell, TestPlugin* plugin, TestResult* result) : shell_(shell), plugin_(plugin), result_(result){} UtestShell* shell_; TestPlugin* plugin_; TestResult* result_; }; static void helperDoRunOneTestInCurrentProcess(void* data) { HelperTestRunInfo* runInfo = (HelperTestRunInfo*) data; UtestShell* shell = runInfo->shell_; TestPlugin* plugin = runInfo->plugin_; TestResult* result = runInfo->result_; shell->runOneTestInCurrentProcess(plugin, *result); } static void helperDoRunOneTestSeperateProcess(void* data) { HelperTestRunInfo* runInfo = (HelperTestRunInfo*) data; UtestShell* shell = runInfo->shell_; TestPlugin* plugin = runInfo->plugin_; TestResult* result = runInfo->result_; PlatformSpecificRunTestInASeperateProcess(shell, plugin, result); } } /******************************** */ static const NormalTestTerminator normalTestTerminator = NormalTestTerminator(); static const CrashingTestTerminator crashingTestTerminator = CrashingTestTerminator(); static const TestTerminatorWithoutExceptions normalTestTerminatorWithoutExceptions; static const CrashingTestTerminatorWithoutExceptions crashingTestTerminatorWithoutExceptions; const TestTerminator *UtestShell::currentTestTerminator_ = &normalTestTerminator; const TestTerminator *UtestShell::currentTestTerminatorWithoutExceptions_ = &normalTestTerminatorWithoutExceptions; bool UtestShell::rethrowExceptions_ = false; /******************************** */ UtestShell::UtestShell() : group_("UndefinedTestGroup"), name_("UndefinedTest"), file_("UndefinedFile"), lineNumber_(0), next_(NULLPTR), isRunAsSeperateProcess_(false), hasFailed_(false) { } UtestShell::UtestShell(const char* groupName, const char* testName, const char* fileName, size_t lineNumber) : group_(groupName), name_(testName), file_(fileName), lineNumber_(lineNumber), next_(NULLPTR), isRunAsSeperateProcess_(false), hasFailed_(false) { } UtestShell::UtestShell(const char* groupName, const char* testName, const char* fileName, size_t lineNumber, UtestShell* nextTest) : group_(groupName), name_(testName), file_(fileName), lineNumber_(lineNumber), next_(nextTest), isRunAsSeperateProcess_(false), hasFailed_(false) { } UtestShell::~UtestShell() { } static void (*pleaseCrashMeRightNow) () = PlatformSpecificAbort; void UtestShell::setCrashMethod(void (*crashme)()) { pleaseCrashMeRightNow = crashme; } void UtestShell::resetCrashMethod() { pleaseCrashMeRightNow = PlatformSpecificAbort; } void UtestShell::crash() { pleaseCrashMeRightNow(); } void UtestShell::runOneTest(TestPlugin* plugin, TestResult& result) { hasFailed_ = false; result.countRun(); HelperTestRunInfo runInfo(this, plugin, &result); if (isRunInSeperateProcess()) PlatformSpecificSetJmp(helperDoRunOneTestSeperateProcess, &runInfo); else PlatformSpecificSetJmp(helperDoRunOneTestInCurrentProcess, &runInfo); } Utest* UtestShell::createTest() { return new Utest(); } void UtestShell::destroyTest(Utest* test) { delete test; } void UtestShell::runOneTestInCurrentProcess(TestPlugin* plugin, TestResult& result) { result.printVeryVerbose("\n-- before runAllPreTestAction: "); plugin->runAllPreTestAction(*this, result); result.printVeryVerbose("\n-- after runAllPreTestAction: "); //save test context, so that test class can be tested UtestShell* savedTest = UtestShell::getCurrent(); TestResult* savedResult = UtestShell::getTestResult(); UtestShell::setTestResult(&result); UtestShell::setCurrentTest(this); Utest* testToRun = NULLPTR; #if CPPUTEST_HAVE_EXCEPTIONS try { #endif result.printVeryVerbose("\n---- before createTest: "); testToRun = createTest(); result.printVeryVerbose("\n---- after createTest: "); result.printVeryVerbose("\n------ before runTest: "); testToRun->run(); result.printVeryVerbose("\n------ after runTest: "); UtestShell::setCurrentTest(savedTest); UtestShell::setTestResult(savedResult); #if CPPUTEST_HAVE_EXCEPTIONS } catch(...) { destroyTest(testToRun); throw; } #endif result.printVeryVerbose("\n---- before destroyTest: "); destroyTest(testToRun); result.printVeryVerbose("\n---- after destroyTest: "); result.printVeryVerbose("\n-- before runAllPostTestAction: "); plugin->runAllPostTestAction(*this, result); result.printVeryVerbose("\n-- after runAllPostTestAction: "); } UtestShell *UtestShell::getNext() const { return next_; } UtestShell* UtestShell::addTest(UtestShell *test) { next_ = test; return this; } size_t UtestShell::countTests() { return next_ ? next_->countTests() + 1 : 1; } SimpleString UtestShell::getMacroName() const { return "TEST"; } const SimpleString UtestShell::getName() const { return SimpleString(name_); } const SimpleString UtestShell::getGroup() const { return SimpleString(group_); } SimpleString UtestShell::getFormattedName() const { SimpleString formattedName(getMacroName()); formattedName += "("; formattedName += group_; formattedName += ", "; formattedName += name_; formattedName += ")"; return formattedName; } bool UtestShell::hasFailed() const { return hasFailed_; } void UtestShell::countCheck() { getTestResult()->countCheck(); } bool UtestShell::willRun() const { return true; } bool UtestShell::isRunInSeperateProcess() const { return isRunAsSeperateProcess_; } void UtestShell::setRunInSeperateProcess() { isRunAsSeperateProcess_ = true; } void UtestShell::setRunIgnored() { } void UtestShell::setFileName(const char* fileName) { file_ = fileName; } void UtestShell::setLineNumber(size_t lineNumber) { lineNumber_ = lineNumber; } void UtestShell::setGroupName(const char* groupName) { group_ = groupName; } void UtestShell::setTestName(const char* testName) { name_ = testName; } const SimpleString UtestShell::getFile() const { return SimpleString(file_); } size_t UtestShell::getLineNumber() const { return lineNumber_; } bool UtestShell::match(const char* target, const TestFilter* filters) const { if(filters == NULLPTR) return true; for(; filters != NULLPTR; filters = filters->getNext()) if(filters->match(target)) return true; return false; } bool UtestShell::shouldRun(const TestFilter* groupFilters, const TestFilter* nameFilters) const { return match(group_, groupFilters) && match(name_, nameFilters); } void UtestShell::failWith(const TestFailure& failure) { failWith(failure, getCurrentTestTerminator()); } // LCOV_EXCL_LINE void UtestShell::failWith(const TestFailure& failure, const TestTerminator& terminator) { addFailure(failure); terminator.exitCurrentTest(); } // LCOV_EXCL_LINE void UtestShell::addFailure(const TestFailure& failure) { hasFailed_ = true; getTestResult()->addFailure(failure); } void UtestShell::exitTest(const TestTerminator& terminator) { terminator.exitCurrentTest(); } // LCOV_EXCL_LINE void UtestShell::assertTrue(bool condition, const char *checkString, const char *conditionString, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (!condition) failWith(CheckFailure(this, fileName, lineNumber, checkString, conditionString, text), testTerminator); } void UtestShell::fail(const char *text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); failWith(FailFailure(this, fileName, lineNumber, text), testTerminator); } // LCOV_EXCL_LINE void UtestShell::assertCstrEqual(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (actual == NULLPTR && expected == NULLPTR) return; if (actual == NULLPTR || expected == NULLPTR) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); if (SimpleString::StrCmp(expected, actual) != 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); } void UtestShell::assertCstrNEqual(const char* expected, const char* actual, size_t length, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (actual == NULLPTR && expected == NULLPTR) return; if (actual == NULLPTR || expected == NULLPTR) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); if (SimpleString::StrNCmp(expected, actual, length) != 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); } void UtestShell::assertCstrNoCaseEqual(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber) { getTestResult()->countCheck(); if (actual == NULLPTR && expected == NULLPTR) return; if (actual == NULLPTR || expected == NULLPTR) failWith(StringEqualNoCaseFailure(this, fileName, lineNumber, expected, actual, text)); if (!SimpleString(expected).equalsNoCase(actual)) failWith(StringEqualNoCaseFailure(this, fileName, lineNumber, expected, actual, text)); } void UtestShell::assertCstrContains(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber) { getTestResult()->countCheck(); if (actual == NULLPTR && expected == NULLPTR) return; if (actual == NULLPTR || expected == NULLPTR) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); if (!SimpleString(actual).contains(expected)) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); } void UtestShell::assertCstrNoCaseContains(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber) { getTestResult()->countCheck(); if (actual == NULLPTR && expected == NULLPTR) return; if (actual == NULLPTR || expected == NULLPTR) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); if (!SimpleString(actual).containsNoCase(expected)) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); } void UtestShell::assertLongsEqual(long expected, long actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(LongsEqualFailure (this, fileName, lineNumber, expected, actual, text), testTerminator); } void UtestShell::assertUnsignedLongsEqual(unsigned long expected, unsigned long actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(UnsignedLongsEqualFailure (this, fileName, lineNumber, expected, actual, text), testTerminator); } void UtestShell::assertLongLongsEqual(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); #if CPPUTEST_USE_LONG_LONG if (expected != actual) failWith(LongLongsEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); #else (void)expected; (void)actual; failWith(FeatureUnsupportedFailure(this, fileName, lineNumber, "CPPUTEST_USE_LONG_LONG", text), testTerminator); #endif } void UtestShell::assertUnsignedLongLongsEqual(cpputest_ulonglong expected, cpputest_ulonglong actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); #if CPPUTEST_USE_LONG_LONG if (expected != actual) failWith(UnsignedLongLongsEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); #else (void)expected; (void)actual; failWith(FeatureUnsupportedFailure(this, fileName, lineNumber, "CPPUTEST_USE_LONG_LONG", text), testTerminator); #endif } void UtestShell::assertSignedBytesEqual(signed char expected, signed char actual, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(SignedBytesEqualFailure (this, fileName, lineNumber, expected, actual, text), testTerminator); } void UtestShell::assertPointersEqual(const void* expected, const void* actual, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(EqualsFailure(this, fileName, lineNumber, StringFrom(expected), StringFrom(actual), text), testTerminator); } void UtestShell::assertFunctionPointersEqual(void (*expected)(), void (*actual)(), const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(EqualsFailure(this, fileName, lineNumber, StringFrom(expected), StringFrom(actual), text), testTerminator); } void UtestShell::assertDoublesEqual(double expected, double actual, double threshold, const char* text, const char* fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (!doubles_equal(expected, actual, threshold)) failWith(DoublesEqualFailure(this, fileName, lineNumber, expected, actual, threshold, text), testTerminator); } void UtestShell::assertBinaryEqual(const void *expected, const void *actual, size_t length, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (length == 0) return; if (actual == NULLPTR && expected == NULLPTR) return; if (actual == NULLPTR || expected == NULLPTR) failWith(BinaryEqualFailure(this, fileName, lineNumber, (const unsigned char *) expected, (const unsigned char *) actual, length, text), testTerminator); if (SimpleString::MemCmp(expected, actual, length) != 0) failWith(BinaryEqualFailure(this, fileName, lineNumber, (const unsigned char *) expected, (const unsigned char *) actual, length, text), testTerminator); } void UtestShell::assertBitsEqual(unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const char* text, const char *fileName, size_t lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if ((expected & mask) != (actual & mask)) failWith(BitsEqualFailure(this, fileName, lineNumber, expected, actual, mask, byteCount, text), testTerminator); } void UtestShell::assertEquals(bool failed, const char* expected, const char* actual, const char* text, const char* file, size_t line, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (failed) failWith(CheckEqualFailure(this, file, line, expected, actual, text), testTerminator); } void UtestShell::assertCompare(bool comparison, const char *checkString, const char *comparisonString, const char *text, const char *fileName, size_t lineNumber, const TestTerminator &testTerminator) { getTestResult()->countCheck(); if (!comparison) failWith(ComparisonFailure(this, fileName, lineNumber, checkString, comparisonString, text), testTerminator); } void UtestShell::print(const char *text, const char* fileName, size_t lineNumber) { SimpleString stringToPrint = "\n"; stringToPrint += fileName; stringToPrint += ":"; stringToPrint += StringFrom(lineNumber); stringToPrint += " "; stringToPrint += text; getTestResult()->print(stringToPrint.asCharString()); } void UtestShell::print(const SimpleString& text, const char* fileName, size_t lineNumber) { print(text.asCharString(), fileName, lineNumber); } void UtestShell::printVeryVerbose(const char* text) { getTestResult()->printVeryVerbose(text); } TestResult* UtestShell::testResult_ = NULLPTR; UtestShell* UtestShell::currentTest_ = NULLPTR; void UtestShell::setTestResult(TestResult* result) { testResult_ = result; } void UtestShell::setCurrentTest(UtestShell* test) { currentTest_ = test; } TestResult* UtestShell::getTestResult() { if (testResult_ == NULLPTR) return &OutsideTestRunnerUTest::instance().getTestResult(); return testResult_; } UtestShell* UtestShell::getCurrent() { if (currentTest_ == NULLPTR) return &OutsideTestRunnerUTest::instance(); return currentTest_; } const TestTerminator &UtestShell::getCurrentTestTerminator() { return *currentTestTerminator_; } const TestTerminator &UtestShell::getCurrentTestTerminatorWithoutExceptions() { return *currentTestTerminatorWithoutExceptions_; } void UtestShell::setCrashOnFail() { currentTestTerminator_ = &crashingTestTerminator; currentTestTerminatorWithoutExceptions_ = &crashingTestTerminatorWithoutExceptions; } void UtestShell::restoreDefaultTestTerminator() { currentTestTerminator_ = &normalTestTerminator; currentTestTerminatorWithoutExceptions_ = &normalTestTerminatorWithoutExceptions; } void UtestShell::setRethrowExceptions(bool rethrowExceptions) { rethrowExceptions_ = rethrowExceptions; } bool UtestShell::isRethrowingExceptions() { return rethrowExceptions_; } ExecFunctionTestShell::~ExecFunctionTestShell() { } ////////////// Utest //////////// Utest::Utest() { } Utest::~Utest() { } #if CPPUTEST_HAVE_EXCEPTIONS void Utest::run() { UtestShell* current = UtestShell::getCurrent(); int jumpResult = 0; try { current->printVeryVerbose("\n-------- before setup: "); jumpResult = PlatformSpecificSetJmp(helperDoTestSetup, this); current->printVeryVerbose("\n-------- after setup: "); if (jumpResult) { current->printVeryVerbose("\n---------- before body: "); PlatformSpecificSetJmp(helperDoTestBody, this); current->printVeryVerbose("\n---------- after body: "); } } catch (CppUTestFailedException&) { PlatformSpecificRestoreJumpBuffer(); } #if CPPUTEST_USE_STD_CPP_LIB catch (const std::exception &e) { current->addFailure(UnexpectedExceptionFailure(current, e)); PlatformSpecificRestoreJumpBuffer(); if (current->isRethrowingExceptions()) { throw; } } #endif catch (...) { current->addFailure(UnexpectedExceptionFailure(current)); PlatformSpecificRestoreJumpBuffer(); if (current->isRethrowingExceptions()) { throw; } } try { current->printVeryVerbose("\n-------- before teardown: "); PlatformSpecificSetJmp(helperDoTestTeardown, this); current->printVeryVerbose("\n-------- after teardown: "); } catch (CppUTestFailedException&) { PlatformSpecificRestoreJumpBuffer(); } #if CPPUTEST_USE_STD_CPP_LIB catch (const std::exception &e) { current->addFailure(UnexpectedExceptionFailure(current, e)); PlatformSpecificRestoreJumpBuffer(); if (current->isRethrowingExceptions()) { throw; } } #endif catch (...) { current->addFailure(UnexpectedExceptionFailure(current)); PlatformSpecificRestoreJumpBuffer(); if (current->isRethrowingExceptions()) { throw; } } } #else void Utest::run() { if (PlatformSpecificSetJmp(helperDoTestSetup, this)) { PlatformSpecificSetJmp(helperDoTestBody, this); } PlatformSpecificSetJmp(helperDoTestTeardown, this); } #endif void Utest::setup() { } void Utest::testBody() { } void Utest::teardown() { } /////////////////// Terminators TestTerminator::~TestTerminator() { } void NormalTestTerminator::exitCurrentTest() const { #if CPPUTEST_HAVE_EXCEPTIONS throw CppUTestFailedException(); #else TestTerminatorWithoutExceptions().exitCurrentTest(); #endif } NormalTestTerminator::~NormalTestTerminator() { } void TestTerminatorWithoutExceptions::exitCurrentTest() const { PlatformSpecificLongJmp(); } // LCOV_EXCL_LINE TestTerminatorWithoutExceptions::~TestTerminatorWithoutExceptions() { } void CrashingTestTerminator::exitCurrentTest() const { UtestShell::crash(); NormalTestTerminator::exitCurrentTest(); } CrashingTestTerminator::~CrashingTestTerminator() { } void CrashingTestTerminatorWithoutExceptions::exitCurrentTest() const { UtestShell::crash(); TestTerminatorWithoutExceptions::exitCurrentTest(); } CrashingTestTerminatorWithoutExceptions::~CrashingTestTerminatorWithoutExceptions() { } //////////////////// ExecFunction // ExecFunction::ExecFunction() { } ExecFunction::~ExecFunction() { } ExecFunctionWithoutParameters::ExecFunctionWithoutParameters(void(*testFunction)()) : testFunction_(testFunction) { } ExecFunctionWithoutParameters::~ExecFunctionWithoutParameters() { } void ExecFunctionWithoutParameters::exec() { if (testFunction_) testFunction_(); } //////////////////// ExecFunctionTest ExecFunctionTest::ExecFunctionTest(ExecFunctionTestShell* shell) : shell_(shell) { } void ExecFunctionTest::testBody() { if (shell_->testFunction_) shell_->testFunction_->exec(); } void ExecFunctionTest::setup() { if (shell_->setup_) shell_->setup_(); } void ExecFunctionTest::teardown() { if (shell_->teardown_) shell_->teardown_(); } /////////////// IgnoredUtestShell ///////////// IgnoredUtestShell::IgnoredUtestShell(): runIgnored_(false) { } IgnoredUtestShell::IgnoredUtestShell(const char* groupName, const char* testName, const char* fileName, size_t lineNumber) : UtestShell(groupName, testName, fileName, lineNumber), runIgnored_(false) { } IgnoredUtestShell::~IgnoredUtestShell() { } bool IgnoredUtestShell::willRun() const { if (runIgnored_) return UtestShell::willRun(); return false; } SimpleString IgnoredUtestShell::getMacroName() const { if (runIgnored_) return "TEST"; return "IGNORE_TEST"; } void IgnoredUtestShell::runOneTest(TestPlugin* plugin, TestResult& result) { if (runIgnored_) { UtestShell::runOneTest(plugin, result); return; } result.countIgnored(); } void IgnoredUtestShell::setRunIgnored() { runIgnored_ = true; } //////////////////// UtestShellPointerArray UtestShellPointerArray::UtestShellPointerArray(UtestShell* firstTest) : arrayOfTests_(NULLPTR), count_(0) { count_ = (firstTest) ? firstTest->countTests() : 0; if (count_ == 0) return; arrayOfTests_ = new UtestShell*[count_]; UtestShell*currentTest = firstTest; for (size_t i = 0; i < count_; i++) { arrayOfTests_[i] = currentTest; currentTest = currentTest->getNext(); } } UtestShellPointerArray::~UtestShellPointerArray() { delete [] arrayOfTests_; } void UtestShellPointerArray::swap(size_t index1, size_t index2) { UtestShell* e2 = arrayOfTests_[index2]; UtestShell* e1 = arrayOfTests_[index1]; arrayOfTests_[index1] = e2; arrayOfTests_[index2] = e1; } void UtestShellPointerArray::shuffle(size_t seed) { if (count_ == 0) return; PlatformSpecificSrand((unsigned int) seed); for (size_t i = count_ - 1; i >= 1; --i) { if (count_ == 0) return; const size_t j = ((size_t)PlatformSpecificRand()) % (i + 1); // distribution biased by modulo, but good enough for shuffling swap(i, j); } relinkTestsInOrder(); } void UtestShellPointerArray::reverse() { if (count_ == 0) return; size_t halfCount = count_ / 2; for (size_t i = 0; i < halfCount; i++) { size_t j = count_ - i - 1; swap(i, j); } relinkTestsInOrder(); } void UtestShellPointerArray::relinkTestsInOrder() { UtestShell *tests = NULLPTR; for (size_t i = 0; i < count_; i++) tests = arrayOfTests_[count_ - i - 1]->addTest(tests); } UtestShell* UtestShellPointerArray::getFirstTest() const { return get(0); } UtestShell* UtestShellPointerArray::get(size_t index) const { if (index >= count_) return NULLPTR; return arrayOfTests_[index]; } ////////////// TestInstaller //////////// TestInstaller::TestInstaller(UtestShell& shell, const char* groupName, const char* testName, const char* fileName, size_t lineNumber) { shell.setGroupName(groupName); shell.setTestName(testName); shell.setFileName(fileName); shell.setLineNumber(lineNumber); TestRegistry::getCurrentRegistry()->addTest(&shell); } TestInstaller::~TestInstaller() { } void TestInstaller::unDo() { TestRegistry::getCurrentRegistry()->unDoLastAddTest(); }
null
197
cpp
cpputest
TestFilter.cpp
src/CppUTest/TestFilter.cpp
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 <organization> 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 <copyright holder> 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/CppUTestConfig.h" #include "CppUTest/TestFilter.h" TestFilter::TestFilter() : strictMatching_(false), invertMatching_(false), next_(NULLPTR) { } TestFilter::TestFilter(const SimpleString& filter) : strictMatching_(false), invertMatching_(false), next_(NULLPTR) { filter_ = filter; } TestFilter::TestFilter(const char* filter) : strictMatching_(false), invertMatching_(false), next_(NULLPTR) { filter_ = filter; } TestFilter* TestFilter::add(TestFilter* filter) { next_ = filter; return this; } TestFilter* TestFilter::getNext() const { return next_; } void TestFilter::strictMatching() { strictMatching_ = true; } void TestFilter::invertMatching() { invertMatching_ = true; } bool TestFilter::match(const SimpleString& name) const { bool matches = false; if(strictMatching_) matches = name == filter_; else matches = name.contains(filter_); return invertMatching_ ? !matches : matches; } bool TestFilter::operator==(const TestFilter& filter) const { return (filter_ == filter.filter_ && strictMatching_ == filter.strictMatching_ && invertMatching_ == filter.invertMatching_); } bool TestFilter::operator!=(const TestFilter& filter) const { return !(filter == *this); } SimpleString TestFilter::asString() const { SimpleString textFilter = StringFromFormat("TestFilter: \"%s\"", filter_.asCharString()); if (strictMatching_ && invertMatching_) textFilter += " with strict, invert matching"; else if (strictMatching_) textFilter += " with strict matching"; else if (invertMatching_) textFilter += " with invert matching"; return textFilter; } SimpleString StringFrom(const TestFilter& filter) { return filter.asString(); }
null
198
cpp
cpputest
MemoryLeakDetector.cpp
src/CppUTest/MemoryLeakDetector.cpp
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 <organization> 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 <copyright holder> 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/SimpleMutex.h" static const char* UNKNOWN = "<unknown>"; static const char GuardBytes[] = {'B','A','S'}; SimpleStringBuffer::SimpleStringBuffer() : positions_filled_(0), write_limit_(SIMPLE_STRING_BUFFER_LEN-1) { buffer_[0] = '\0'; } void SimpleStringBuffer::clear() { positions_filled_ = 0; buffer_[0] = '\0'; } void SimpleStringBuffer::add(const char* format, ...) { const size_t positions_left = write_limit_ - positions_filled_; if (positions_left == 0) return; va_list arguments; va_start(arguments, format); const int count = PlatformSpecificVSNprintf(buffer_ + positions_filled_, positions_left+1, format, arguments); if (count > 0) positions_filled_ += (size_t) count; if (positions_filled_ > write_limit_) positions_filled_ = write_limit_; va_end(arguments); } void SimpleStringBuffer::addMemoryDump(const void* memory, size_t memorySize) { const unsigned char* byteMemory = (const unsigned char*)memory; const size_t maxLineBytes = 16; size_t currentPos = 0; size_t p; while (currentPos < memorySize) { add(" %04lx: ", (unsigned long) currentPos); size_t bytesInLine = memorySize - currentPos; if (bytesInLine > maxLineBytes) { bytesInLine = maxLineBytes; } const size_t leftoverBytes = maxLineBytes - bytesInLine; for (p = 0; p < bytesInLine; p++) { add("%02hx ", (unsigned short) byteMemory[currentPos + p]); if (p == ((maxLineBytes / 2) - 1)) { add(" "); } } for (p = 0; p < leftoverBytes; p++) { add(" "); } if (leftoverBytes > (maxLineBytes/2)) { add(" "); } add("|"); for (p = 0; p < bytesInLine; p++) { char toAdd = (char)byteMemory[currentPos + p]; if (toAdd < ' ' || toAdd > '~') { toAdd = '.'; } add("%c", (int)toAdd); } add("|\n"); currentPos += bytesInLine; } } 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 many 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, size_t allocationLineNumber, size_t allocationSize, TestMemoryAllocator* allocator) { outputBuffer_.add(" allocated at file: %s line: %d size: %lu type: %s\n", allocationFile, (int) allocationLineNumber, (unsigned long) allocationSize, allocator->alloc_name()); } void MemoryLeakOutputStringBuffer::addDeallocationLocation(const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* allocator) { outputBuffer_.add(" deallocated at file: %s line: %d type: %s\n", freeFile, (int) 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\tMemory: <%p> Content:\n", leak->number_, (unsigned long) leak->size_, leak->file_, (int) leak->line_, leak->allocator_->alloc_name(), (void*) leak->memory_); outputBuffer_.addMemoryDump(leak->memory_, leak->size_); if (SimpleString::StrCmp(leak->allocator_->alloc_name(), (const char*) "malloc") == 0) 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(size_t amountOfLeaks) { outputBuffer_.add("%s %d\n", MEM_LEAK_FOOTER, (int) amountOfLeaks); } void MemoryLeakOutputStringBuffer::addWarningForUsingMalloc() { outputBuffer_.add(MEM_LEAK_ADDITION_MALLOC_WARNING); } void MemoryLeakOutputStringBuffer::reportDeallocateNonAllocatedMemoryFailure(const char* freeFile, size_t freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) { reportFailure("Deallocating non-allocated memory\n", "<unknown>", 0, 0, NullUnknownAllocator::defaultAllocator(), freeFile, freeLine, freeAllocator, reporter); } void MemoryLeakOutputStringBuffer::reportAllocationDeallocationMismatchFailure(MemoryLeakDetectorNode* node, const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) { reportFailure("Allocation/deallocation type mismatch\n", node->file_, node->line_, node->size_, node->allocator_, freeFile, freeLineNumber, freeAllocator, reporter); } void MemoryLeakOutputStringBuffer::reportMemoryCorruptionFailure(MemoryLeakDetectorNode* node, const char* freeFile, size_t freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) { reportFailure("Memory corruption (written out of bounds?)\n", node->file_, node->line_, node->size_, node->allocator_, freeFile, freeLineNumber, freeAllocator, reporter); } void MemoryLeakOutputStringBuffer::reportFailure(const char* message, const char* allocFile, size_t allocLine, size_t allocSize, TestMemoryAllocator* allocAllocator, const char* freeFile, size_t 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, unsigned char allocation_stage, const char* file, size_t line) { number_ = number; memory_ = memory; size_ = size; allocator_ = allocator; period_ = period; allocation_stage_ = allocation_stage; file_ = file; line_ = line; } /////////////////////// 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); } bool MemoryLeakDetectorList::isInAllocationStage(MemoryLeakDetectorNode* node, unsigned char allocation_stage) { return node->allocation_stage_ == allocation_stage; } void MemoryLeakDetectorList::clearAllAccounting(MemLeakPeriod period) { MemoryLeakDetectorNode* cur = head_; MemoryLeakDetectorNode* prev = NULLPTR; 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 = NULLPTR; 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 NULLPTR; } MemoryLeakDetectorNode* MemoryLeakDetectorList::retrieveNode(char* memory) { MemoryLeakDetectorNode* cur = head_; while (cur) { if (cur->memory_ == memory) return cur; cur = cur->next_; } return NULLPTR; } MemoryLeakDetectorNode* MemoryLeakDetectorList::getLeakFrom(MemoryLeakDetectorNode* node, MemLeakPeriod period) { for (MemoryLeakDetectorNode* cur = node; cur; cur = cur->next_) if (isInPeriod(cur, period)) return cur; return NULLPTR; } MemoryLeakDetectorNode* MemoryLeakDetectorList::getLeakForAllocationStageFrom(MemoryLeakDetectorNode* node, unsigned char allocation_stage) { for (MemoryLeakDetectorNode* cur = node; cur; cur = cur->next_) if (isInAllocationStage(cur, allocation_stage)) return cur; return NULLPTR; } MemoryLeakDetectorNode* MemoryLeakDetectorList::getFirstLeak(MemLeakPeriod period) { return getLeakFrom(head_, period); } MemoryLeakDetectorNode* MemoryLeakDetectorList::getFirstLeakForAllocationStage(unsigned char allocation_stage) { return getLeakForAllocationStageFrom(head_, allocation_stage); } MemoryLeakDetectorNode* MemoryLeakDetectorList::getNextLeak(MemoryLeakDetectorNode* node, MemLeakPeriod period) { return getLeakFrom(node->next_, period); } MemoryLeakDetectorNode* MemoryLeakDetectorList::getNextLeakForAllocationStage(MemoryLeakDetectorNode* node, unsigned char allocation_stage) { return getLeakForAllocationStageFrom(node->next_, allocation_stage); } size_t MemoryLeakDetectorList::getTotalLeaks(MemLeakPeriod period) { size_t total_leaks = 0; for (MemoryLeakDetectorNode* node = head_; node; node = node->next_) { if (isInPeriod(node, period)) total_leaks++; } return total_leaks; } ///////////////////////////////////////////////////////////// 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); } size_t MemoryLeakDetectorTable::getTotalLeaks(MemLeakPeriod period) { size_t 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 NULLPTR; } MemoryLeakDetectorNode* MemoryLeakDetectorTable::getFirstLeakForAllocationStage(unsigned char allocation_stage) { for (int i = 0; i < hash_prime; i++) { MemoryLeakDetectorNode* node = table_[i].getFirstLeakForAllocationStage(allocation_stage); if (node) return node; } return NULLPTR; } MemoryLeakDetectorNode* MemoryLeakDetectorTable::getNextLeak(MemoryLeakDetectorNode* leak, MemLeakPeriod period) { 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 NULLPTR; } MemoryLeakDetectorNode* MemoryLeakDetectorTable::getNextLeakForAllocationStage(MemoryLeakDetectorNode* leak, unsigned char allocation_stage) { unsigned long i = hash(leak->memory_); MemoryLeakDetectorNode* node = table_[i].getNextLeakForAllocationStage(leak, allocation_stage); if (node) return node; for (++i; i < hash_prime; i++) { node = table_[i].getFirstLeakForAllocationStage(allocation_stage); if (node) return node; } return NULLPTR; } ///////////////////////////////////////////////////////////// MemoryLeakDetector::MemoryLeakDetector(MemoryLeakFailure* reporter) { doAllocationTypeChecking_ = true; allocationSequenceNumber_ = 1; current_period_ = mem_leak_period_disabled; current_allocation_stage_ = 0; reporter_ = reporter; mutex_ = new SimpleMutex; } MemoryLeakDetector::~MemoryLeakDetector() { if (mutex_) { delete mutex_; } } 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; } unsigned char MemoryLeakDetector::getCurrentAllocationStage() const { return current_allocation_stage_; } 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_; } void MemoryLeakDetector::increaseAllocationStage() { current_allocation_stage_++; } void MemoryLeakDetector::decreaseAllocationStage() { current_allocation_stage_--; } SimpleMutex *MemoryLeakDetector::getMutex() { return mutex_; } static size_t calculateVoidPointerAlignedSize(size_t size) { #ifndef CPPUTEST_DISABLE_MEM_CORRUPTION_CHECK return (sizeof(void*) - (size % sizeof(void*))) + size; #else return size; #endif } size_t MemoryLeakDetector::sizeOfMemoryWithCorruptionInfo(size_t size) { 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, size_t line) { node->init(new_memory, allocationSequenceNumber_++, size, allocator, current_period_, current_allocation_stage_, file, line); addMemoryCorruptionInformation(node->memory_ + node->size_); memoryTable_.addNewNode(node); } char* MemoryLeakDetector::reallocateMemoryAndLeakInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, size_t line, bool allocatNodesSeperately) { char* new_memory = reallocateMemoryWithAccountingInformation(allocator, memory, size, file, line, allocatNodesSeperately); if (new_memory == NULLPTR) return NULLPTR; MemoryLeakDetectorNode *node = createMemoryLeakAccountingInformation(allocator, size, new_memory, allocatNodesSeperately); storeLeakInformation(node, new_memory, size, allocator, file, line); return node->memory_; } void MemoryLeakDetector::invalidateMemory(char* memory) { #ifndef CPPUTEST_DISABLE_HEAP_POISON MemoryLeakDetectorNode* node = memoryTable_.retrieveNode(memory); if (node) PlatformSpecificMemset(memory, 0xCD, node->size_); #endif } void MemoryLeakDetector::addMemoryCorruptionInformation(char* memory) { for (size_t i=0; i<memory_corruption_buffer_size; i++) memory[i] = GuardBytes[i % sizeof(GuardBytes)]; } bool MemoryLeakDetector::validMemoryCorruptionInformation(char* memory) { for (size_t i=0; i<memory_corruption_buffer_size; i++) if (memory[i] != GuardBytes[i % sizeof(GuardBytes)]) return false; return true; } 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, size_t line, TestMemoryAllocator* allocator, bool allocateNodesSeperately) { if (!matchingAllocation(node->allocator_->actualAllocator(), allocator->actualAllocator())) outputBuffer_.reportAllocationDeallocationMismatchFailure(node, file, line, allocator->actualAllocator(), reporter_); else if (!validMemoryCorruptionInformation(node->memory_ + node->size_)) outputBuffer_.reportMemoryCorruptionFailure(node, file, line, allocator->actualAllocator(), 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, size_t line, bool allocatNodesSeperately) { if (allocatNodesSeperately) return allocator->alloc_memory(sizeOfMemoryWithCorruptionInfo(size), file, line); else return allocator->alloc_memory(sizeOfMemoryWithCorruptionInfo(size) + sizeof(MemoryLeakDetectorNode), file, line); } char* MemoryLeakDetector::reallocateMemoryWithAccountingInformation(TestMemoryAllocator* /*allocator*/, char* memory, size_t size, const char* /*file*/, size_t /*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, size_t line, bool allocatNodesSeperately) { #ifdef CPPUTEST_DISABLE_MEM_CORRUPTION_CHECK allocatNodesSeperately = true; #endif /* With malloc, it is harder to guarantee that the allocator free is called. * This is because operator new is overloaded via linker symbols, but malloc just via #defines. * If the same allocation is used and the wrong free is called, it will deallocate the memory leak information * 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 == NULLPTR) return NULLPTR; 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, size_t line, bool allocatNodesSeperately) { if (memory == NULLPTR) return; MemoryLeakDetectorNode* node = memoryTable_.removeNode((char*) memory); if (node == NULLPTR) { outputBuffer_.reportDeallocateNonAllocatedMemoryFailure(file, line, allocator, reporter_); return; } #ifdef CPPUTEST_DISABLE_MEM_CORRUPTION_CHECK allocatNodesSeperately = true; #endif if (!allocator->hasBeenDestroyed()) { size_t size = node->size_; checkForCorruption(node, file, line, allocator, allocatNodesSeperately); allocator->free_memory((char*) memory, size, file, line); } } void MemoryLeakDetector::deallocMemory(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately) { deallocMemory(allocator, (char*) memory, UNKNOWN, 0, allocatNodesSeperately); } void MemoryLeakDetector::deallocAllMemoryInCurrentAllocationStage() { char* memory = NULLPTR; MemoryLeakDetectorNode* node = memoryTable_.getFirstLeakForAllocationStage(current_allocation_stage_); while (node) { memory = node->memory_; TestMemoryAllocator* allocator = node->allocator_; node = memoryTable_.getNextLeakForAllocationStage(node, current_allocation_stage_); deallocMemory(allocator, memory, __FILE__, __LINE__); } } char* MemoryLeakDetector::reallocMemory(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, size_t line, bool allocatNodesSeperately) { #ifdef CPPUTEST_DISABLE_MEM_CORRUPTION_CHECK allocatNodesSeperately = true; #endif if (memory) { MemoryLeakDetectorNode* node = memoryTable_.removeNode(memory); if (node == NULLPTR) { outputBuffer_.reportDeallocateNonAllocatedMemoryFailure(file, line, allocator, reporter_); return NULLPTR; } 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) { 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); } } size_t MemoryLeakDetector::totalMemoryLeaks(MemLeakPeriod period) { return memoryTable_.getTotalLeaks(period); }
null
199
cpp
cpputest
TestHarness_c.cpp
src/CppUTest/TestHarness_c.cpp
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 <organization> 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 <copyright holder> 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_BOOL_LOCATION(int expected, int actual, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertEquals(!!expected != !!actual, expected ? "true" : "false", actual ? "true" : "false", text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertLongsEqual((long)expected, (long)actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_UINT_LOCATION(unsigned int expected, unsigned int actual, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertUnsignedLongsEqual((unsigned long)expected, (unsigned long)actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_LONG_LOCATION(long expected, long actual, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertLongsEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_ULONG_LOCATION(unsigned long expected, unsigned long actual, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertUnsignedLongsEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_LONGLONG_LOCATION(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertLongLongsEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_ULONGLONG_LOCATION(cpputest_ulonglong expected, cpputest_ulonglong actual, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertUnsignedLongLongsEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertDoublesEqual(expected, actual, threshold, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertEquals(((expected) != (actual)), StringFrom(expected).asCharString(), StringFrom(actual).asCharString(), text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } extern void CHECK_EQUAL_C_UBYTE_LOCATION(unsigned char expected, unsigned char actual, const char* text, const char* fileName, size_t lineNumber)\ { UtestShell::getCurrent()->assertEquals(((expected) != (actual)),StringFrom((int)expected).asCharString(), StringFrom((int) actual).asCharString(), text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_SBYTE_LOCATION(char signed expected, signed char actual, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertEquals(((expected) != (actual)),StringFrom((int)expected).asCharString(), StringFrom((int) actual).asCharString(), text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertCstrEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_POINTER_LOCATION(const void* expected, const void* actual, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertPointersEqual(expected, actual, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } extern void CHECK_EQUAL_C_MEMCMP_LOCATION(const void* expected, const void* actual, size_t size, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertBinaryEqual(expected, actual, size, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } extern void CHECK_EQUAL_C_BITS_LOCATION(unsigned int expected, unsigned int actual, unsigned int mask, size_t size, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertBitsEqual(expected, actual, mask, size, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->fail(text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } // LCOV_EXCL_LINE void FAIL_C_LOCATION(const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->fail("", fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } // LCOV_EXCL_LINE void CHECK_C_LOCATION(int condition, const char* conditionString, const char* text, const char* fileName, size_t lineNumber) { UtestShell::getCurrent()->assertTrue(condition != 0, "CHECK_C", conditionString, text, fileName, lineNumber, UtestShell::getCurrentTestTerminatorWithoutExceptions()); } 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; } static TestMemoryAllocator* originalAllocator = NULLPTR; void cpputest_malloc_set_out_of_memory() { if (originalAllocator == NULLPTR) originalAllocator = getCurrentMallocAllocator(); setCurrentMallocAllocator(NullUnknownAllocator::defaultAllocator()); } void cpputest_malloc_set_not_out_of_memory() { malloc_out_of_memory_counter = NO_COUNTDOWN; setCurrentMallocAllocator(originalAllocator); originalAllocator = NULLPTR; } 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, "<unknown>", 0); } char* cpputest_strdup(const char* str) { return cpputest_strdup_location(str, "<unknown>", 0); } char* cpputest_strndup(const char* str, size_t n) { return cpputest_strndup_location(str, n, "<unknown>", 0); } void* cpputest_calloc(size_t num, size_t size) { return cpputest_calloc_location(num, size, "<unknown>", 0); } void* cpputest_realloc(void* ptr, size_t size) { return cpputest_realloc_location(ptr, size, "<unknown>", 0); } void cpputest_free(void* buffer) { cpputest_free_location(buffer, "<unknown>", 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, size_t line) { countdown(); malloc_count++; return cpputest_malloc_location_with_leak_detection(size, file, line); } static size_t test_harness_c_strlen(const char * str) { size_t n = 0; while (*str++) n++; return n; } static char* strdup_alloc(const char * str, size_t size, const char* file, size_t line) { char* result = (char*) cpputest_malloc_location(size, file, line); PlatformSpecificMemCpy(result, str, size); result[size-1] = '\0'; return result; } char* cpputest_strdup_location(const char * str, const char* file, size_t line) { size_t length = 1 + test_harness_c_strlen(str); return strdup_alloc(str, length, file, line); } char* cpputest_strndup_location(const char * str, size_t n, const char* file, size_t line) { size_t length = test_harness_c_strlen(str); length = length < n ? length : n; length = length + 1; return strdup_alloc(str, length, file, line); } void* cpputest_calloc_location(size_t num, size_t size, const char* file, size_t line) { void* mem = cpputest_malloc_location(num * size, file, line); if (mem) PlatformSpecificMemset(mem, 0, num*size); return mem; } void* cpputest_realloc_location(void* memory, size_t size, const char* file, size_t line) { return cpputest_realloc_location_with_leak_detection(memory, size, file, line); } void cpputest_free_location(void* buffer, const char* file, size_t line) { cpputest_free_location_with_leak_detection(buffer, file, line); } }
null
200
cpp
cpputest
TestTestingFixture.cpp
src/CppUTest/TestTestingFixture.cpp
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 <organization> 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 <copyright holder> 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/TestTestingFixture.h" bool TestTestingFixture::lineOfCodeExecutedAfterCheck = false; TestTestingFixture::TestTestingFixture() { output_ = new StringBufferTestOutput(); result_ = new TestResult(*output_); genTest_ = new ExecFunctionTestShell(); registry_ = new TestRegistry(); ownsExecFunction_ = false; registry_->setCurrentRegistry(registry_); registry_->addTest(genTest_); lineOfCodeExecutedAfterCheck = false; } void TestTestingFixture::flushOutputAndResetResult() { output_->flush(); delete result_; result_ = new TestResult(*output_); } TestTestingFixture::~TestTestingFixture() { registry_->setCurrentRegistry(NULLPTR); clearExecFunction(); delete registry_; delete result_; delete output_; delete genTest_; } void TestTestingFixture::clearExecFunction() { if (genTest_->testFunction_ && ownsExecFunction_) delete genTest_->testFunction_; } void TestTestingFixture::addTest(UtestShell * test) { registry_->addTest(test); } void TestTestingFixture::setTestFunction(void(*testFunction)()) { clearExecFunction(); genTest_->testFunction_ = new ExecFunctionWithoutParameters(testFunction); ownsExecFunction_ = true; } void TestTestingFixture::setTestFunction(ExecFunction* testFunction) { clearExecFunction(); genTest_->testFunction_ = testFunction; ownsExecFunction_ = false; } void TestTestingFixture::setSetup(void(*setupFunction)()) { genTest_->setup_ = setupFunction; } void TestTestingFixture::setTeardown(void(*teardownFunction)()) { genTest_->teardown_ = teardownFunction; } void TestTestingFixture::installPlugin(TestPlugin* plugin) { registry_->installPlugin(plugin); } void TestTestingFixture::setRunTestsInSeperateProcess() { registry_->setRunTestsInSeperateProcess(); } void TestTestingFixture::setOutputVerbose() { output_->verbose(TestOutput::level_verbose); } void TestTestingFixture::runTestWithMethod(void(*method)()) { setTestFunction(method); runAllTests(); } void TestTestingFixture::runAllTests() { registry_->runAllTests(*result_); } size_t TestTestingFixture::getFailureCount() { return result_->getFailureCount(); } size_t TestTestingFixture::getCheckCount() { return result_->getCheckCount(); } size_t TestTestingFixture::getTestCount() { return result_->getTestCount(); } size_t TestTestingFixture::getIgnoreCount() { return result_->getIgnoredCount(); } TestRegistry* TestTestingFixture::getRegistry() { return registry_; } bool TestTestingFixture::hasTestFailed() { return genTest_->hasFailed(); } void TestTestingFixture::assertPrintContains(const SimpleString& contains) { STRCMP_CONTAINS(contains.asCharString(), getOutput().asCharString()); } void TestTestingFixture::assertPrintContainsNot(const SimpleString& contains) { CHECK(! getOutput().contains(contains)); } const SimpleString& TestTestingFixture::getOutput() { return output_->getOutput(); } size_t TestTestingFixture::getRunCount() { return result_->getRunCount(); } void TestTestingFixture::lineExecutedAfterCheck() { lineOfCodeExecutedAfterCheck = true; } void TestTestingFixture::checkTestFailsWithProperTestLocation(const char* text, const char* file, size_t line) { if (getFailureCount() != 1) FAIL_LOCATION(StringFromFormat("Expected one test failure, but got %d amount of test failures", (int) getFailureCount()).asCharString(), file, line); STRCMP_CONTAINS_LOCATION(text, output_->getOutput().asCharString(), "", file, line); if (lineOfCodeExecutedAfterCheck) FAIL_LOCATION("The test should jump/throw on failure and not execute the next line. However, the next line was executed.", file, line); }
null