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
401
cpp
blalor-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/PlatformSpecificFunctions.h" SimpleString removeAllPrintableCharactersFrom(const SimpleString& str) { size_t bufferSize = str.size()+1; char* buffer = (char*) PlatformSpecificMalloc(bufferSize); str.copyToBuffer(buffer, bufferSize); for (size_t i = 0; i < bufferSize-1; i++) if (buffer[i] != '\t' && buffer[i] != '\n') buffer[i] = ' '; SimpleString result(buffer); PlatformSpecificFree(buffer); return result; } SimpleString addMarkerToString(const SimpleString& str, int markerPos) { size_t bufferSize = str.size()+1; char* buffer = (char*) PlatformSpecificMalloc(bufferSize); str.copyToBuffer(buffer, bufferSize); buffer[markerPos] = '^'; SimpleString result(buffer); PlatformSpecificFree(buffer); return result; } TestFailure::TestFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& theMessage) : testName_(test->getFormattedName()), fileName_(fileName), lineNumber_(lineNumber), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_(theMessage) { } TestFailure::TestFailure(Utest* test, const SimpleString& theMessage) : testName_(test->getFormattedName()), fileName_(test->getFile()), lineNumber_(test->getLineNumber()), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_(theMessage) { } TestFailure::TestFailure(Utest* test, const char* fileName, int lineNum) : testName_(test->getFormattedName()), fileName_(fileName), lineNumber_(lineNum), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_("no message") { } TestFailure::TestFailure(const TestFailure& f) : testName_(f.testName_), fileName_(f.fileName_), lineNumber_(f.lineNumber_), testFileName_(f.testFileName_), testLineNumber_(f.testLineNumber_), message_(f.message_) { } TestFailure::~TestFailure() { } SimpleString TestFailure::getFileName() const { return fileName_; } SimpleString TestFailure::getTestFileName() const { return testFileName_; } SimpleString TestFailure::getTestName() const { return testName_; } int TestFailure::getFailureLineNumber() const { return lineNumber_; } int TestFailure::getTestLineNumber() const { return testLineNumber_; } SimpleString TestFailure::getMessage() const { return message_; } bool TestFailure::isOutsideTestFile() const { return testFileName_ != fileName_; } bool TestFailure::isInHelperFunction() const { return lineNumber_ < testLineNumber_; } SimpleString TestFailure::createButWasString(const SimpleString& expected, const SimpleString& actual) { const char* format = "expected <%s>\n\tbut was <%s>"; return StringFromFormat(format, expected.asCharString(), actual.asCharString()); } SimpleString TestFailure::createDifferenceAtPosString(const SimpleString& actual, int position) { SimpleString result; const int extraCharactersWindow = 20; const int halfOfExtraCharactersWindow = extraCharactersWindow / 2; SimpleString paddingForPreventingOutOfBounds (" ", halfOfExtraCharactersWindow); SimpleString actualString = paddingForPreventingOutOfBounds + actual + paddingForPreventingOutOfBounds; SimpleString differentString = StringFromFormat("difference starts at position %d at: <", position); result += "\n"; result += StringFromFormat("\t%s%s>\n", differentString.asCharString(), actualString.subString(position, extraCharactersWindow).asCharString()); SimpleString markString = actualString.subString(position, halfOfExtraCharactersWindow+1); markString = removeAllPrintableCharactersFrom(markString); markString = addMarkerToString(markString, halfOfExtraCharactersWindow); result += StringFromFormat("\t%s%s", SimpleString(" ", differentString.size()).asCharString(), markString.asCharString()); return result; } EqualsFailure::EqualsFailure(Utest* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : TestFailure(test, fileName, lineNumber) { message_ = createButWasString(StringFromOrNull(expected), StringFromOrNull(actual)); } EqualsFailure::EqualsFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) : TestFailure(test, fileName, lineNumber) { message_ = createButWasString(expected, actual); } static SimpleString StringFromOrNan(double d) { if (PlatformSpecificIsNan(d)) return "Nan - Not a number"; return StringFrom(d); } DoublesEqualFailure::DoublesEqualFailure(Utest* test, const char* fileName, int lineNumber, double expected, double actual, double threshold) : TestFailure(test, fileName, lineNumber) { message_ = createButWasString(StringFromOrNan(expected), StringFromOrNan(actual)); message_ += " threshold used was <"; message_ += StringFromOrNan(threshold); message_ += ">"; if (PlatformSpecificIsNan(expected) || PlatformSpecificIsNan(actual) || PlatformSpecificIsNan(threshold)) message_ += "\n\tCannot make comparisons with Nan"; } CheckEqualFailure::CheckEqualFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) : TestFailure(test, fileName, lineNumber) { int failStart; for (failStart = 0; actual.asCharString()[failStart] == expected.asCharString()[failStart]; failStart++) ; message_ = createButWasString(expected, actual); message_ += createDifferenceAtPosString(actual, failStart); } ContainsFailure::ContainsFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) : TestFailure(test, fileName, lineNumber) { const char* format = "actual <%s>\n\tdid not contain <%s>"; message_ = StringFromFormat(format, actual.asCharString(), expected.asCharString()); } CheckFailure::CheckFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& checkString, const SimpleString& conditionString) : TestFailure(test, fileName, lineNumber) { message_ = checkString; message_ += "("; message_ += conditionString; message_ += ") failed"; } FailFailure::FailFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& message) : TestFailure(test, fileName, lineNumber) { message_ = message; } LongsEqualFailure::LongsEqualFailure(Utest* test, const char* fileName, int lineNumber, long expected, long actual) : TestFailure(test, fileName, lineNumber) { SimpleString aDecimal = StringFrom(actual); SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom(expected); SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString::padStringsToSameLength(aHex, eHex, '0'); SimpleString actualReported = aDecimal + " 0x" + aHex; SimpleString expectedReported = eDecimal + " 0x" + eHex; message_ = createButWasString(expectedReported, actualReported); } StringEqualFailure::StringEqualFailure(Utest* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : TestFailure(test, fileName, lineNumber) { int failStart; for (failStart = 0; actual[failStart] == expected[failStart]; failStart++) ; message_ = createButWasString(expected, actual); message_ += createDifferenceAtPosString(actual, failStart); } StringEqualNoCaseFailure::StringEqualNoCaseFailure(Utest* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : TestFailure(test, fileName, lineNumber) { int failStart; for (failStart = 0; PlatformSpecificToLower(actual[failStart]) == PlatformSpecificToLower(expected[failStart]); failStart++) ; message_ = createButWasString(expected, actual); message_ += createDifferenceAtPosString(actual, failStart); }
null
402
cpp
blalor-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/MemoryLeakAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" class MemoryLeakWarningReporter: public MemoryLeakFailure { public: virtual ~MemoryLeakWarningReporter() { } ; virtual void fail(char* fail_string) { FAIL(fail_string); } }; static MemoryLeakWarningReporter* globalReporter = 0; static MemoryLeakDetector* globalDetector = 0; void destroyDetector() { PlatformSpecificFree(globalDetector); globalReporter->~MemoryLeakWarningReporter(); PlatformSpecificFree(globalReporter); globalReporter = 0; globalDetector = 0; } MemoryLeakDetector* MemoryLeakWarningPlugin::getGlobalDetector() { if (globalDetector == 0) { /* Want to void using operator new here, however.. still need to init the vtable. * Now just memcpy a local stack variable in the malloced memory. Ought to work everywhere :)) */ MemoryLeakWarningReporter reporter; globalReporter = (MemoryLeakWarningReporter*) PlatformSpecificMalloc(sizeof(MemoryLeakWarningReporter)); PlatformSpecificMemCpy(globalReporter, &reporter, sizeof(MemoryLeakWarningReporter)); globalDetector = (MemoryLeakDetector*) PlatformSpecificMalloc(sizeof(MemoryLeakDetector)); if (globalDetector == 0) FAIL("operator new(size, bool) not enough memory"); globalDetector->init(globalReporter); } return globalDetector; } MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::firstPlugin_ = 0; MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::getFirstPlugin() { return firstPlugin_; } MemoryLeakDetector* MemoryLeakWarningPlugin::getMemoryLeakDetector() { return memLeakDetector_; } void MemoryLeakWarningPlugin::ignoreAllLeaksInTest() { ignoreAllWarnings_ = true; } void MemoryLeakWarningPlugin::expectLeaksInTest(int n) { expectedLeaks_ = n; } MemoryLeakWarningPlugin::MemoryLeakWarningPlugin(const SimpleString& name, MemoryLeakDetector* localDetector) : TestPlugin(name), ignoreAllWarnings_(false), expectedLeaks_(0) { if (firstPlugin_ == 0) firstPlugin_ = this; if (localDetector) memLeakDetector_ = localDetector; else memLeakDetector_ = getGlobalDetector(); memLeakDetector_->enable(); } MemoryLeakWarningPlugin::~MemoryLeakWarningPlugin() { if (this == firstPlugin_) firstPlugin_ = 0; } void MemoryLeakWarningPlugin::preTestAction(Utest& /*test*/, TestResult& result) { memLeakDetector_->startChecking(); failureCount_ = result.getFailureCount(); } void MemoryLeakWarningPlugin::postTestAction(Utest& test, TestResult& result) { memLeakDetector_->stopChecking(); int leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_checking); if (!ignoreAllWarnings_ && expectedLeaks_ != leaks && failureCount_ == result.getFailureCount()) { TestFailure f(&test, memLeakDetector_->report(mem_leak_period_checking)); result.addFailure(f); } memLeakDetector_->markCheckingPeriodLeaksAsNonCheckingPeriod(); ignoreAllWarnings_ = false; expectedLeaks_ = 0; } const char* MemoryLeakWarningPlugin::FinalReport(int toBeDeletedLeaks) { int leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_enabled); if (leaks != toBeDeletedLeaks) return memLeakDetector_->report(mem_leak_period_enabled); return ""; } #if CPPUTEST_USE_MEM_LEAK_DETECTION #undef new #if CPPUTEST_USE_STD_CPP_LIB #define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) if (memory == NULL) throw std::bad_alloc(); #define UT_THROW(except) throw (except) #define UT_THROW_EMPTY() throw () #else #define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) #define UT_THROW(except) #define UT_THROW_EMPTY() #endif void* operator new(size_t size) UT_THROW(std::bad_alloc) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(MemoryLeakAllocator::getCurrentNewAllocator(), size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } void* operator new(size_t size, const char* file, int line) UT_THROW(std::bad_alloc) { void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(MemoryLeakAllocator::getCurrentNewAllocator(), size, (char*) file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } void operator delete(void* mem) UT_THROW_EMPTY() { MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(MemoryLeakAllocator::getCurrentNewAllocator(), (char*) mem); } void* operator new[](size_t size) UT_THROW(std::bad_alloc) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(MemoryLeakAllocator::getCurrentNewArrayAllocator(), size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } void* operator new [](size_t size, const char* file, int line) UT_THROW(std::bad_alloc) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(MemoryLeakAllocator::getCurrentNewArrayAllocator(), size, (char*) file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } void operator delete[](void* mem) UT_THROW_EMPTY() { MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(MemoryLeakAllocator::getCurrentNewArrayAllocator(), (char*) mem); } #endif
null
403
cpp
blalor-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/MemoryLeakAllocator.h" MemoryLeakAllocator* SimpleString::stringAllocator_ = NULL; MemoryLeakAllocator* SimpleString::getStringAllocator() { if (stringAllocator_ == NULL) return StandardNewArrayAllocator::defaultAllocator(); return stringAllocator_; } void SimpleString::setStringAllocator(MemoryLeakAllocator* allocator) { stringAllocator_ = allocator; } /* Avoid using the memory leak detector INSIDE SimpleString as its used inside the detector */ char* SimpleString::allocStringBuffer(size_t _size) { return getStringAllocator()->alloc_memory(_size, __FILE__, __LINE__); } void SimpleString::deallocStringBuffer(char* str) { getStringAllocator()->free_memory(str, __FILE__, __LINE__); } char* SimpleString::getEmptyString() const { char* empty = allocStringBuffer(1); empty[0] = '\0'; return empty; } SimpleString::SimpleString(const char *otherBuffer) { if (otherBuffer == 0) { buffer_ = getEmptyString(); } else { size_t len = PlatformSpecificStrLen(otherBuffer) + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrCpy(buffer_, otherBuffer); } } SimpleString::SimpleString(const char *other, size_t repeatCount) { size_t len = PlatformSpecificStrLen(other) * repeatCount + 1; buffer_ = allocStringBuffer(len); char* next = buffer_; for (size_t i = 0; i < repeatCount; i++) { PlatformSpecificStrCpy(next, other); next += PlatformSpecificStrLen(other); } *next = 0; } SimpleString::SimpleString(const SimpleString& other) { size_t len = other.size() + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrCpy(buffer_, other.buffer_); } SimpleString& SimpleString::operator=(const SimpleString& other) { if (this != &other) { deallocStringBuffer(buffer_); size_t len = other.size() + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrCpy(buffer_, other.buffer_); } return *this; } bool SimpleString::contains(const SimpleString& other) const { //strstr on some machines does not handle "" //the right way. "" should be found in any string if (PlatformSpecificStrLen(other.buffer_) == 0) return true; else if (PlatformSpecificStrLen(buffer_) == 0) return false; else return PlatformSpecificStrStr(buffer_, other.buffer_) != 0; } bool SimpleString::containsNoCase(const SimpleString& other) const { return toLower().contains(other.toLower()); } bool SimpleString::startsWith(const SimpleString& other) const { if (PlatformSpecificStrLen(other.buffer_) == 0) return true; else if (PlatformSpecificStrLen(buffer_) == 0) return false; else return PlatformSpecificStrStr(buffer_, other.buffer_) == buffer_; } bool SimpleString::endsWith(const SimpleString& other) const { size_t buffer_length = PlatformSpecificStrLen(buffer_); size_t other_buffer_length = PlatformSpecificStrLen(other.buffer_); if (other_buffer_length == 0) return true; if (buffer_length == 0) return false; if (buffer_length < other_buffer_length) return false; return PlatformSpecificStrCmp(buffer_ + buffer_length - other_buffer_length, other.buffer_) == 0; } size_t SimpleString::count(const SimpleString& substr) const { size_t num = 0; char* str = buffer_; while ((str = PlatformSpecificStrStr(str, substr.buffer_))) { num++; str++; } return num; } void SimpleString::split(const SimpleString& delimiter, SimpleStringCollection& col) const { size_t num = count(delimiter); size_t extraEndToken = (endsWith(delimiter)) ? 0 : 1; col.allocate(num + extraEndToken); char* str = buffer_; char* prev; for (size_t i = 0; i < num; ++i) { prev = str; str = PlatformSpecificStrStr(str, delimiter.buffer_) + 1; size_t len = str - prev; char* sub = allocStringBuffer(len + 1); PlatformSpecificStrNCpy(sub, prev, len); sub[len] = '\0'; col[i] = sub; deallocStringBuffer(sub); } if (extraEndToken) { col[num] = str; } } void SimpleString::replace(char to, char with) { size_t s = size(); for (size_t i = 0; i < s; i++) { if (buffer_[i] == to) buffer_[i] = with; } } void SimpleString::replace(const char* to, const char* with) { size_t c = count(to); size_t len = size(); size_t tolen = PlatformSpecificStrLen(to); size_t withlen = PlatformSpecificStrLen(with); size_t newsize = len + (withlen * c) - (tolen * c) + 1; if (newsize) { char* newbuf = allocStringBuffer(newsize); for (size_t i = 0, j = 0; i < len;) { if (PlatformSpecificStrNCmp(&buffer_[i], to, tolen) == 0) { PlatformSpecificStrNCpy(&newbuf[j], with, withlen); j += withlen; i += tolen; } else { newbuf[j] = buffer_[i]; j++; i++; } } deallocStringBuffer(buffer_); buffer_ = newbuf; buffer_[newsize - 1] = '\0'; } else { buffer_ = getEmptyString(); buffer_[0] = '\0'; } } SimpleString SimpleString::toLower() const { SimpleString str(*this); size_t str_size = str.size(); for (size_t i = 0; i < str_size; i++) str.buffer_[i] = PlatformSpecificToLower(str.buffer_[i]); return str; } const char *SimpleString::asCharString() const { return buffer_; } size_t SimpleString::size() const { return PlatformSpecificStrLen(buffer_); } bool SimpleString::isEmpty() const { return size() == 0; } SimpleString::~SimpleString() { deallocStringBuffer(buffer_); } bool operator==(const SimpleString& left, const SimpleString& right) { return 0 == PlatformSpecificStrCmp(left.asCharString(), right.asCharString()); } bool SimpleString::equalsNoCase(const SimpleString& str) const { return toLower() == str.toLower(); } bool operator!=(const SimpleString& left, const SimpleString& right) { return !(left == right); } SimpleString SimpleString::operator+(const SimpleString& rhs) { SimpleString t(buffer_); t += rhs.buffer_; return t; } SimpleString& SimpleString::operator+=(const SimpleString& rhs) { return operator+=(rhs.buffer_); } SimpleString& SimpleString::operator+=(const char* rhs) { size_t len = this->size() + PlatformSpecificStrLen(rhs) + 1; char* tbuffer = allocStringBuffer(len); PlatformSpecificStrCpy(tbuffer, this->buffer_); PlatformSpecificStrCat(tbuffer, rhs); deallocStringBuffer(buffer_); buffer_ = tbuffer; return *this; } void SimpleString::padStringsToSameLength(SimpleString& str1, SimpleString& str2, char padCharacter) { if (str1.size() > str2.size()) { padStringsToSameLength(str2, str1, padCharacter); return; } char pad[2]; pad[0] = padCharacter; pad[1] = 0; str1 = SimpleString(pad, str2.size() - str1.size()) + str1; } SimpleString SimpleString::subString(size_t beginPos, size_t amount) const { if (beginPos > size()-1) return ""; SimpleString newString = buffer_ + beginPos; if (newString.size() > amount) newString.buffer_[amount] = '\0'; return newString; } void SimpleString::copyToBuffer(char* bufferToCopy, size_t bufferSize) const { if (bufferToCopy == NULL || bufferSize == 0) return; size_t sizeToCopy = (bufferSize-1 < size()) ? bufferSize-1 : size(); PlatformSpecificStrNCpy(bufferToCopy, buffer_, sizeToCopy); bufferToCopy[sizeToCopy] = '\0'; } SimpleString StringFrom(bool value) { return SimpleString(StringFromFormat("%s", value ? "true" : "false")); } SimpleString StringFrom(const char *value) { return SimpleString(value); } SimpleString StringFromOrNull(const char * expected) { return (expected) ? StringFrom(expected) : "(null)"; } SimpleString StringFrom(int value) { return StringFromFormat("%d", value); } SimpleString StringFrom(long value) { return StringFromFormat("%ld", value); } SimpleString StringFrom(const void* value) { return SimpleString("0x") + HexStringFrom((long) value); } SimpleString HexStringFrom(long value) { return StringFromFormat("%lx", value); } SimpleString StringFrom(double value, int precision) { SimpleString format = StringFromFormat("%%.%df", precision); return StringFromFormat(format.asCharString(), 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; } #if CPPUTEST_USE_STD_CPP_LIB #include <string> SimpleString StringFrom(const std::string& value) { return SimpleString(value.c_str()); } SimpleString StringFrom(uint32_t i) { return StringFromFormat("%10u (0x%08x)", i, i); } SimpleString StringFrom(uint16_t i) { return StringFromFormat("%5u (0x%04x)", i, i); } SimpleString StringFrom(uint8_t i) { return StringFromFormat("%3u (0x%02x)", i, i); } #endif //Kludge to get a va_copy in VC++ V6 #ifndef va_copy #define va_copy(copy, original) copy = original; #endif SimpleString VStringFromFormat(const char* format, va_list args) { va_list argsCopy; va_copy(argsCopy, args); enum { sizeOfdefaultBuffer = 100 }; char defaultBuffer[sizeOfdefaultBuffer]; SimpleString resultString; int size = PlatformSpecificVSNprintf(defaultBuffer, sizeOfdefaultBuffer, format, args); if (size < sizeOfdefaultBuffer) { resultString = SimpleString(defaultBuffer); } else { char* newBuffer = SimpleString::allocStringBuffer(size + 1); PlatformSpecificVSNprintf(newBuffer, size + 1, format, argsCopy); resultString = SimpleString(newBuffer); SimpleString::deallocStringBuffer(newBuffer); } return resultString; } SimpleStringCollection::SimpleStringCollection() { collection_ = 0; size_ = 0; } void SimpleStringCollection::allocate(size_t _size) { if (collection_) delete[] collection_; size_ = _size; collection_ = new SimpleString[size_]; } SimpleStringCollection::~SimpleStringCollection() { delete[] (collection_); } size_t SimpleStringCollection::size() const { return size_; } SimpleString& SimpleStringCollection::operator[](size_t index) { if (index >= size_) { empty_ = ""; return empty_; } return collection_[index]; }
null
404
cpp
blalor-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) { } void TestResult::setProgressIndicator(const char* indicator) { output_.setProgressIndicator(indicator); } TestResult::~TestResult() { } void TestResult::currentGroupStarted(Utest* test) { output_.printCurrentGroupStarted(*test); currentGroupTimeStarted_ = GetPlatformSpecificTimeInMillis(); } void TestResult::currentGroupEnded(Utest* /*test*/) { currentGroupTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentGroupTimeStarted_; output_.printCurrentGroupEnded(*this); } void TestResult::currentTestStarted(Utest* test) { output_.printCurrentTestStarted(*test); currentTestTimeStarted_ = GetPlatformSpecificTimeInMillis(); } void TestResult::print(const char* text) { output_.print(text); } void TestResult::currentTestEnded(Utest* /*test*/) { currentTestTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentTestTimeStarted_; output_.printCurrentTestEnded(*this); } void TestResult::addFailure(const TestFailure& failure) { output_.print(failure); failureCount_++; } void TestResult::countTest() { testCount_++; } void TestResult::countRun() { runCount_++; } void TestResult::countCheck() { checkCount_++; } void TestResult::countFilteredOut() { filteredOutCount_++; } void TestResult::countIgnored() { ignoredCount_++; } void TestResult::testsStarted() { timeStarted_ = GetPlatformSpecificTimeInMillis(); output_.printTestsStarted(); } void TestResult::testsEnded() { long timeEnded = GetPlatformSpecificTimeInMillis(); totalExecutionTime_ = timeEnded - timeStarted_; output_.printTestsEnded(*this); } long TestResult::getTotalExecutionTime() const { return totalExecutionTime_; } void TestResult::setTotalExecutionTime(long exTime) { totalExecutionTime_ = exTime; } long TestResult::getCurrentTestTotalExecutionTime() const { return currentTestTotalExecutionTime_; } long TestResult::getCurrentGroupTotalExecutionTime() const { return currentGroupTotalExecutionTime_; }
null
405
cpp
blalor-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" TestRegistry::TestRegistry() : tests_(&NullTest::instance()), nameFilter_(0), groupFilter_(0), firstPlugin_(NullTestPlugin::instance()) { } TestRegistry::~TestRegistry() { cleanup(); } void TestRegistry::cleanup() { delete nameFilter_; delete groupFilter_; nameFilter_ = 0; groupFilter_ = 0; } void TestRegistry::addTest(Utest *test) { tests_ = test->addTest(tests_); } void TestRegistry::runAllTests(TestResult& result) { bool groupStart = true; result.testsStarted(); for (Utest *test = tests_; !test->isNull(); test = test->getNext()) { if (groupStart) { result.currentGroupStarted(test); groupStart = false; } result.setProgressIndicator(test->getProgressIndicator()); result.countTest(); if (testShouldRun(test, result)) { result.currentTestStarted(test); test->runOneTestWithPlugins(firstPlugin_, result); result.currentTestEnded(test); } if (endOfGroup(test)) { groupStart = true; result.currentGroupEnded(test); } } result.testsEnded(); } bool TestRegistry::endOfGroup(Utest* test) { return (test->isNull() || test->getGroup() != test->getNext()->getGroup()); } int TestRegistry::countTests() { return tests_->countTests(); } TestRegistry* TestRegistry::currentRegistry_ = 0; TestRegistry* TestRegistry::getCurrentRegistry() { static TestRegistry registry; return (currentRegistry_ == 0) ? &registry : currentRegistry_; } void TestRegistry::setCurrentRegistry(TestRegistry* registry) { currentRegistry_ = registry; } void TestRegistry::unDoLastAddTest() { tests_ = tests_->getNext(); } void TestRegistry::nameFilter(SimpleString f) { delete nameFilter_; nameFilter_ = new SimpleString(f); } void TestRegistry::groupFilter(SimpleString f) { delete groupFilter_; groupFilter_ = new SimpleString(f); } SimpleString TestRegistry::getGroupFilter() { return *groupFilter_; } SimpleString TestRegistry::getNameFilter() { return *nameFilter_; } bool TestRegistry::testShouldRun(Utest* test, TestResult& result) { if (groupFilter_ == 0) groupFilter_ = new SimpleString(); if (nameFilter_ == 0) nameFilter_ = new SimpleString(); if (test->shouldRun(*groupFilter_, *nameFilter_)) return true; else { result.countFilteredOut(); return false; } } void TestRegistry::resetPlugins() { firstPlugin_ = NullTestPlugin::instance(); } void TestRegistry::installPlugin(TestPlugin* plugin) { firstPlugin_ = plugin->addPlugin(firstPlugin_); } TestPlugin* TestRegistry::getFirstPlugin() { return firstPlugin_; } TestPlugin* TestRegistry::getPluginByName(const SimpleString& name) { return firstPlugin_->getPluginByName(name); } void TestRegistry::removePluginByName(const SimpleString& name) { if (firstPlugin_->removePluginByName(name) == firstPlugin_) firstPlugin_ = firstPlugin_->getNext(); if (firstPlugin_->getName() == name) firstPlugin_ = firstPlugin_->getNext(); firstPlugin_->removePluginByName(name); } Utest* TestRegistry::getFirstTest() { return tests_; } Utest* TestRegistry::getLastTest() { Utest* current = tests_; while (!current->getNext()->isNull()) current = current->getNext(); return current; } Utest* TestRegistry::getTestWithNext(Utest* test) { Utest* current = tests_; while (!current->getNext()->isNull() && current->getNext() != test) current = current->getNext(); return current; }
null
406
cpp
blalor-cpputest
MemoryLeakAllocator.cpp
src/CppUTest/MemoryLeakAllocator.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/MemoryLeakAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" static char* checkedMalloc(size_t size) { char* mem = (char*) PlatformSpecificMalloc(size); if (mem == 0) FAIL("malloc returned nul pointer"); return mem; } MemoryLeakAllocator* MemoryLeakAllocator::currentNewAllocator = 0; MemoryLeakAllocator* MemoryLeakAllocator::currentNewArrayAllocator = 0; MemoryLeakAllocator* MemoryLeakAllocator::currentMallocAllocator = 0; bool MemoryLeakAllocator::isOfEqualType(MemoryLeakAllocator* allocator) { return PlatformSpecificStrCmp(this->name(), allocator->name()) == 0; } void MemoryLeakAllocator::setCurrentNewAllocator(MemoryLeakAllocator* allocator) { currentNewAllocator = allocator; } MemoryLeakAllocator* MemoryLeakAllocator::getCurrentNewAllocator() { if (currentNewAllocator == 0) setCurrentNewAllocatorToDefault(); return currentNewAllocator; } void MemoryLeakAllocator::setCurrentNewAllocatorToDefault() { currentNewAllocator = StandardNewAllocator::defaultAllocator(); } void MemoryLeakAllocator::setCurrentNewArrayAllocator(MemoryLeakAllocator* allocator) { currentNewArrayAllocator = allocator; } MemoryLeakAllocator* MemoryLeakAllocator::getCurrentNewArrayAllocator() { if (currentNewArrayAllocator == 0) setCurrentNewArrayAllocatorToDefault(); return currentNewArrayAllocator; } void MemoryLeakAllocator::setCurrentNewArrayAllocatorToDefault() { currentNewArrayAllocator = StandardNewArrayAllocator::defaultAllocator(); } void MemoryLeakAllocator::setCurrentMallocAllocator(MemoryLeakAllocator* allocator) { currentMallocAllocator = allocator; } MemoryLeakAllocator* MemoryLeakAllocator::getCurrentMallocAllocator() { if (currentMallocAllocator == 0) setCurrentMallocAllocatorToDefault(); return currentMallocAllocator; } void MemoryLeakAllocator::setCurrentMallocAllocatorToDefault() { currentMallocAllocator = StandardMallocAllocator::defaultAllocator(); } bool MemoryLeakAllocator::allocateMemoryLeakNodeSeparately() { return false; } char* MemoryLeakAllocator::allocMemoryLeakNode(size_t size) { return alloc_memory(size, "MemoryLeakNode", 1); } void MemoryLeakAllocator::freeMemoryLeakNode(char* memory) { free_memory(memory, "MemoryLeakNode", 1); } char* StandardMallocAllocator::alloc_memory(size_t size, const char*, int) { return checkedMalloc(size); } void StandardMallocAllocator::free_memory(char* memory, const char*, int) { PlatformSpecificFree(memory); } const char* StandardMallocAllocator::name() { return "Standard Malloc Allocator"; } const char* StandardMallocAllocator::alloc_name() { return "malloc"; } const char* StandardMallocAllocator::free_name() { return "free"; } bool StandardMallocAllocator::allocateMemoryLeakNodeSeparately() { return true; } MemoryLeakAllocator* StandardMallocAllocator::defaultAllocator() { static StandardMallocAllocator allocator; return &allocator; } char* StandardNewAllocator::alloc_memory(size_t size, const char*, int) { return checkedMalloc(size); } void StandardNewAllocator::free_memory(char* memory, const char*, int) { PlatformSpecificFree(memory); } const char* StandardNewAllocator::name() { return "Standard New Allocator"; } const char* StandardNewAllocator::alloc_name() { return "new"; } const char* StandardNewAllocator::free_name() { return "delete"; } MemoryLeakAllocator* StandardNewAllocator::defaultAllocator() { static StandardNewAllocator allocator; return &allocator; } char* StandardNewArrayAllocator::alloc_memory(size_t size, const char*, int) { return checkedMalloc(size); } void StandardNewArrayAllocator::free_memory(char* memory, const char*, int) { PlatformSpecificFree(memory); } const char* StandardNewArrayAllocator::name() { return "Standard New [] Allocator"; } const char* StandardNewArrayAllocator::alloc_name() { return "new []"; } const char* StandardNewArrayAllocator::free_name() { return "delete []"; } MemoryLeakAllocator* StandardNewArrayAllocator::defaultAllocator() { static StandardNewArrayAllocator allocator; return &allocator; } char* NullUnknownAllocator::alloc_memory(size_t /*size*/, const char*, int) { return 0; } void NullUnknownAllocator::free_memory(char* /*memory*/, const char*, int) { } const char* NullUnknownAllocator::name() { return "Null Allocator"; } const char* NullUnknownAllocator::alloc_name() { return "unknown"; } const char* NullUnknownAllocator::free_name() { return "unknown"; } MemoryLeakAllocator* NullUnknownAllocator::defaultAllocator() { static NullUnknownAllocator allocator; return &allocator; }
null
407
cpp
blalor-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::TestOutput() : dotCount_(0), verbose_(false), progressIndication_(".") { } TestOutput::~TestOutput() { } void TestOutput::verbose() { verbose_ = true; } void TestOutput::print(const char* str) { printBuffer(str); } void TestOutput::print(long n) { print(StringFrom(n).asCharString()); } void TestOutput::printDouble(double d) { print(StringFrom(d, 3).asCharString()); } void TestOutput::printHex(long n) { print(HexStringFrom(n).asCharString()); } TestOutput& operator<<(TestOutput& p, const char* s) { p.print(s); return p; } TestOutput& operator<<(TestOutput& p, long int i) { p.print(i); return p; } void TestOutput::printCurrentTestStarted(const Utest& test) { if (verbose_) print(test.getFormattedName().asCharString()); } void TestOutput::printCurrentTestEnded(const TestResult& res) { if (verbose_) { print(" - "); print(res.getCurrentTestTotalExecutionTime()); print(" ms\n"); } else { printProgressIndicator(); } } void TestOutput::printProgressIndicator() { print(progressIndication_); if (++dotCount_ % 50 == 0) print("\n"); } void TestOutput::setProgressIndicator(const char* indicator) { progressIndication_ = indicator; } void TestOutput::printTestsStarted() { } void TestOutput::printCurrentGroupStarted(const Utest& /*test*/) { } void TestOutput::printCurrentGroupEnded(const TestResult& /*res*/) { } void TestOutput::flush() { } void TestOutput::printTestsEnded(const TestResult& result) { if (result.getFailureCount() > 0) { print("\nErrors ("); print(result.getFailureCount()); print(" failures, "); } else { print("\nOK ("); } print(result.getTestCount()); print(" tests, "); print(result.getRunCount()); print(" ran, "); print(result.getCheckCount()); print(" checks, "); print(result.getIgnoredCount()); print(" ignored, "); print(result.getFilteredOutCount()); print(" filtered out, "); print(result.getTotalExecutionTime()); print(" ms)\n\n"); } void TestOutput::printTestRun(int number, int total) { if (total > 1) { print("Test run "); print(number); print(" of "); print(total); print("\n"); } } void TestOutput::print(const TestFailure& failure) { if (failure.isOutsideTestFile() || failure.isInHelperFunction()) printFileAndLineForTestAndFailure(failure); else printFileAndLineForFailure(failure); printFailureMessage(failure.getMessage()); } void TestOutput::printFileAndLineForTestAndFailure(const TestFailure& failure) { printEclipseErrorInFileOnLine(failure.getTestFileName(), failure.getTestLineNumber()); printFailureInTest(failure.getTestName()); printEclipseErrorInFileOnLine(failure.getFileName(), failure.getFailureLineNumber()); } void TestOutput::printFileAndLineForFailure(const TestFailure& failure) { printEclipseErrorInFileOnLine(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::printEclipseErrorInFileOnLine(SimpleString file, int lineNumber) { print("\n"); print(file.asCharString()); print(":"); print(lineNumber); print(":"); print(" error:"); } void ConsoleTestOutput::printBuffer(const char* s) { while (*s) { if ('\n' == *s) PlatformSpecificPutchar('\r'); PlatformSpecificPutchar(*s); s++; } flush(); } void ConsoleTestOutput::flush() { PlatformSpecificFlush(); }
null
408
cpp
blalor-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** av) : ac_(ac), av_(av), verbose_(false), repeat_(1), groupFilter_(""), nameFilter_(""), outputType_(OUTPUT_ECLIPSE) { } CommandLineArguments::~CommandLineArguments() { } bool CommandLineArguments::parse(TestPlugin* plugin) { bool correctParameters = true; for (int i = 1; i < ac_; i++) { SimpleString argument = av_[i]; if (argument == "-v") verbose_ = true; else if (argument.startsWith("-r")) SetRepeatCount(ac_, av_, i); else if (argument.startsWith("-g")) SetGroupFilter(ac_, av_, i); else if (argument.startsWith("-n")) SetNameFilter(ac_, av_, i); else if (argument.startsWith("-o")) correctParameters = SetOutputType(ac_, av_, i); else if (argument.startsWith("-p")) correctParameters = plugin->parseAllArguments(ac_, av_, i); else correctParameters = false; if (correctParameters == false) { return false; } } return true; } const char* CommandLineArguments::usage() const { return "usage [-v] [-r#] [-g groupName] [-n testName] [-o{normal, junit}]\n"; } bool CommandLineArguments::isVerbose() const { return verbose_; } int CommandLineArguments::getRepeatCount() const { return repeat_; } SimpleString CommandLineArguments::getGroupFilter() const { return groupFilter_; } SimpleString CommandLineArguments::getNameFilter() const { return nameFilter_; } void CommandLineArguments::SetRepeatCount(int ac, const char** av, int& i) { repeat_ = 0; SimpleString repeatParameter(av[i]); if (repeatParameter.size() > 2) repeat_ = PlatformSpecificAtoI(av[i] + 2); else if (i + 1 < ac) { repeat_ = PlatformSpecificAtoI(av[i + 1]); if (repeat_ != 0) i++; } if (0 == repeat_) repeat_ = 2; } SimpleString CommandLineArguments::getParameterField(int ac, const char** av, int& i) { SimpleString parameter(av[i]); if (parameter.size() > 2) return av[i] + 2; else if (i + 1 < ac) return av[++i]; return ""; } void CommandLineArguments::SetGroupFilter(int ac, const char** av, int& i) { SimpleString gf = getParameterField(ac, av, i); groupFilter_ = gf; } void CommandLineArguments::SetNameFilter(int ac, const char** av, int& i) { nameFilter_ = getParameterField(ac, av, i); } bool CommandLineArguments::SetOutputType(int ac, const char** av, int& i) { SimpleString outputType = getParameterField(ac, av, i); if (outputType.size() == 0) return false; if (outputType == "normal" || outputType == "eclipse") { outputType_ = OUTPUT_ECLIPSE; return true; } if (outputType == "junit") { outputType_ = OUTPUT_JUNIT; return true; } return false; } bool CommandLineArguments::isEclipseOutput() const { return outputType_ == OUTPUT_ECLIPSE; } bool CommandLineArguments::isJUnitOutput() const { return outputType_ == OUTPUT_JUNIT; }
null
409
cpp
blalor-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_(0), next_(0) { } ; SimpleString name_; long execTime_; TestFailure* failure_; JUnitTestCaseResultNode* next_; }; struct JUnitTestGroupResult { JUnitTestGroupResult() : testCount_(0), failureCount_(0), groupExecTime_(0), head_(0), tail_(0) { } ; int testCount_; int failureCount_; long startTime_; long groupExecTime_; SimpleString group_; JUnitTestCaseResultNode* head_; JUnitTestCaseResultNode* tail_; }; struct JUnitTestOutputImpl { JUnitTestGroupResult results_; PlatformSpecificFile file_; }; JUnitTestOutput::JUnitTestOutput() : impl_(new JUnitTestOutputImpl) { } JUnitTestOutput::~JUnitTestOutput() { resetTestGroupResult(); delete impl_; } void JUnitTestOutput::resetTestGroupResult() { impl_->results_.testCount_ = 0; impl_->results_.failureCount_ = 0; impl_->results_.group_ = ""; JUnitTestCaseResultNode* cur = impl_->results_.head_; while (cur) { JUnitTestCaseResultNode* tmp = cur->next_; ; if (cur->failure_) delete cur->failure_; delete cur; cur = tmp; } impl_->results_.head_ = 0; impl_->results_.tail_ = 0; } void JUnitTestOutput::printTestsStarted() { } void JUnitTestOutput::printCurrentGroupStarted(const Utest& /*test*/) { } void JUnitTestOutput::printCurrentTestEnded(const TestResult& result) { impl_->results_.tail_->execTime_ = result.getCurrentTestTotalExecutionTime(); } void JUnitTestOutput::printTestsEnded(const TestResult& /*result*/) { } void JUnitTestOutput::printCurrentGroupEnded(const TestResult& result) { impl_->results_.groupExecTime_ = result.getCurrentGroupTotalExecutionTime(); writeTestGroupToFile(); resetTestGroupResult(); } void JUnitTestOutput::printCurrentTestStarted(const Utest& test) { impl_->results_.testCount_++; impl_->results_.group_ = test.getGroup(); impl_->results_.startTime_ = GetPlatformSpecificTimeInMillis(); if (impl_->results_.tail_ == 0) { impl_->results_.head_ = impl_->results_.tail_ = new JUnitTestCaseResultNode; } else { impl_->results_.tail_->next_ = new JUnitTestCaseResultNode; impl_->results_.tail_ = impl_->results_.tail_->next_; } impl_->results_.tail_->name_ = test.getName(); } static SimpleString createFileName(const SimpleString& group) { SimpleString fileName = "cpputest_"; fileName += group; fileName += ".xml"; return fileName; } void JUnitTestOutput::writeXmlHeader() { writeToFile("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); } void JUnitTestOutput::writeTestSuiteSummery() { SimpleString buf = StringFromFormat( "<testsuite errors=\"0\" failures=\"%d\" hostname=\"localhost\" name=\"%s\" tests=\"%d\" time=\"%d.%03d\" timestamp=\"%s\">\n", impl_->results_.failureCount_, impl_->results_.group_.asCharString(), impl_->results_.testCount_, (int) (impl_->results_.groupExecTime_ / 1000), (int) (impl_->results_.groupExecTime_ % 1000), GetPlatformSpecificTimeString()); writeToFile(buf.asCharString()); } void JUnitTestOutput::writeProperties() { writeToFile("<properties>\n"); writeToFile("</properties>\n"); } void JUnitTestOutput::writeTestCases() { JUnitTestCaseResultNode* cur = impl_->results_.head_; while (cur) { SimpleString buf = StringFromFormat( "<testcase classname=\"%s\" name=\"%s\" time=\"%d.%03d\">\n", impl_->results_.group_.asCharString(), cur->name_.asCharString(), (int) (cur->execTime_ / 1000), (int)(cur->execTime_ % 1000)); writeToFile(buf.asCharString()); if (cur->failure_) { writeFailure(cur); } writeToFile("</testcase>\n"); cur = cur->next_; } } void JUnitTestOutput::writeFailure(JUnitTestCaseResultNode* node) { SimpleString message = node->failure_->getMessage().asCharString(); message.replace('"', '\''); message.replace('<', '['); message.replace('>', ']'); message.replace("\n", "{newline}"); SimpleString buf = StringFromFormat( "<failure message=\"%s:%d: %s\" type=\"AssertionFailedError\">\n", node->failure_->getFileName().asCharString(), node->failure_->getFailureLineNumber(), message.asCharString()); writeToFile(buf.asCharString()); writeToFile("</failure>\n"); } void JUnitTestOutput::writeFileEnding() { writeToFile("<system-out></system-out>\n"); writeToFile("<system-err></system-err>\n"); writeToFile("</testsuite>"); } void JUnitTestOutput::writeTestGroupToFile() { openFileForWrite(createFileName(impl_->results_.group_)); writeXmlHeader(); writeTestSuiteSummery(); writeProperties(); writeTestCases(); writeFileEnding(); closeFile(); } void JUnitTestOutput::verbose() { } void JUnitTestOutput::printBuffer(const char*) { } void JUnitTestOutput::print(const char*) { } void JUnitTestOutput::print(long) { } void JUnitTestOutput::print(const TestFailure& failure) { if (impl_->results_.tail_->failure_ == 0) { impl_->results_.failureCount_++; impl_->results_.tail_->failure_ = new TestFailure(failure); } } void JUnitTestOutput::printTestRun(int /*number*/, int /*total*/) { } void JUnitTestOutput::flush() { } void JUnitTestOutput::openFileForWrite(const SimpleString& fileName) { impl_->file_ = PlatformSpecificFOpen(fileName.asCharString(), "w"); } void JUnitTestOutput::writeToFile(const SimpleString& buffer) { PlatformSpecificFPuts(buffer.asCharString(), impl_->file_); } void JUnitTestOutput::closeFile() { PlatformSpecificFClose(impl_->file_); }
null
410
cpp
blalor-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" bool doubles_equal(double d1, double d2, double threshold) { if (PlatformSpecificIsNan(d1) || PlatformSpecificIsNan(d2) || PlatformSpecificIsNan(threshold)) return false; 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 Utest { public: static OutsideTestRunnerUTest& instance() { static OutsideTestRunnerUTest instance_; return instance_; } virtual TestResult& getTestResult() { return defaultTestResult; } virtual void exitCurrentTest() { } virtual ~OutsideTestRunnerUTest() { } private: OutsideTestRunnerUTest() : Utest("\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; }; Utest::Utest() : group_("UndefinedTestGroup"), name_("UndefinedTest"), file_("UndefinedFile"), lineNumber_(0), next_(&NullTest::instance()) { } Utest::Utest(const char* groupName, const char* testName, const char* fileName, int lineNumber) : group_(groupName), name_(testName), file_(fileName), lineNumber_(lineNumber), next_(&NullTest::instance()) { } Utest::Utest(const char* groupName, const char* testName, const char* fileName, int lineNumber, Utest* nextTest) : group_(groupName), name_(testName), file_(fileName), lineNumber_(lineNumber), next_(nextTest) { } Utest::~Utest() { } void Utest::runOneTestWithPlugins(TestPlugin* plugin, TestResult& result) { executePlatformSpecificRunOneTest(plugin, result); } void Utest::runOneTest(TestPlugin* plugin, TestResult& result) { plugin->runAllPreTestAction(*this, result); run(result); plugin->runAllPostTestAction(*this, result); } void Utest::run(TestResult& result) { //save test context, so that test class can be tested Utest* savedTest = getCurrent(); TestResult* savedResult = getTestResult(); result.countRun(); setTestResult(&result); setCurrentTest(this); if (executePlatformSpecificSetup()) { executePlatformSpecificTestBody(); } executePlatformSpecificTeardown(); setCurrentTest(savedTest); setTestResult(savedResult); } void Utest::exitCurrentTest() { executePlatformSpecificExitCurrentTest(); } Utest *Utest::getNext() const { return next_; } Utest* Utest::addTest(Utest *test) { next_ = test; return this; } int Utest::countTests() { return next_->countTests() + 1; } bool Utest::isNull() const { return false; } SimpleString Utest::getMacroName() const { return "TEST"; } const SimpleString Utest::getName() const { return SimpleString(name_); } const SimpleString Utest::getGroup() const { return SimpleString(group_); } SimpleString Utest::getFormattedName() const { SimpleString formattedName(getMacroName()); formattedName += "("; formattedName += group_; formattedName += ", "; formattedName += name_; formattedName += ")"; return formattedName; } const char* Utest::getProgressIndicator() const { return "."; } void Utest::setFileName(const char* fileName) { file_ = fileName; } void Utest::setLineNumber(int lineNumber) { lineNumber_ = lineNumber; } void Utest::setGroupName(const char* groupName) { group_ = groupName; } void Utest::setTestName(const char* testName) { name_ = testName; } const SimpleString Utest::getFile() const { return SimpleString(file_); } int Utest::getLineNumber() const { return lineNumber_; } void Utest::setup() { } void Utest::testBody() { } void Utest::teardown() { } bool Utest::shouldRun(const SimpleString& groupFilter, const SimpleString& nameFilter) const { SimpleString group(group_); SimpleString name(name_); if (group.contains(groupFilter) && name.contains(nameFilter)) return true; return false; } void Utest::failWith(const TestFailure& failure) { getTestResult()->addFailure(failure); Utest::getCurrent()->exitCurrentTest(); } void Utest::assertTrue(bool condition, const char * checkString, const char* conditionString, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (!condition) failWith(CheckFailure(this, fileName, lineNumber, checkString, conditionString)); } void Utest::fail(const char *text, const char* fileName, int lineNumber) { failWith(FailFailure(this, fileName, lineNumber, text)); } void Utest::assertCstrEqual(const char* expected, const char* actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if (actual == 0 || expected == 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual)); if (PlatformSpecificStrCmp(expected, actual) != 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual)); } void Utest::assertCstrNoCaseEqual(const char* expected, const char* actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if (actual == 0 || expected == 0) failWith(StringEqualNoCaseFailure(this, fileName, lineNumber, expected, actual)); if (!SimpleString(expected).equalsNoCase(actual)) failWith(StringEqualNoCaseFailure(this, fileName, lineNumber, expected, actual)); } void Utest::assertCstrContains(const char* expected, const char* actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if(actual == 0 || expected == 0) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual)); if (!SimpleString(actual).contains(expected)) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual)); } void Utest::assertCstrNoCaseContains(const char* expected, const char* actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if(actual == 0 || expected == 0) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual)); if (!SimpleString(actual).containsNoCase(expected)) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual)); } void Utest::assertLongsEqual(long expected, long actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (expected != actual) { LongsEqualFailure f(this, fileName, lineNumber, expected, actual); getTestResult()->addFailure(f); Utest::getCurrent()->exitCurrentTest(); } } void Utest::assertPointersEqual(const void* expected, const void* actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (expected != actual) failWith(EqualsFailure(this, fileName, lineNumber, StringFrom(expected), StringFrom(actual))); } void Utest::assertDoublesEqual(double expected, double actual, double threshold, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (!doubles_equal(expected, actual, threshold)) failWith(DoublesEqualFailure(this, fileName, lineNumber, expected, actual, threshold)); } void Utest::print(const char *text, const char* fileName, int lineNumber) { SimpleString stringToPrint = "\n"; stringToPrint += fileName; stringToPrint += ":"; stringToPrint += StringFrom(lineNumber); stringToPrint += " "; stringToPrint += text; getTestResult()->print(stringToPrint.asCharString()); } void Utest::print(const SimpleString& text, const char* fileName, int lineNumber) { print(text.asCharString(), fileName, lineNumber); } TestResult* Utest::testResult_ = NULL; Utest* Utest::currentTest_ = NULL; void Utest::setTestResult(TestResult* result) { testResult_ = result; } void Utest::setCurrentTest(Utest* test) { currentTest_ = test; } TestResult* Utest::getTestResult() { if (testResult_ == NULL) return &OutsideTestRunnerUTest::instance().getTestResult(); return testResult_; } Utest* Utest::getCurrent() { if (currentTest_ == NULL) return &OutsideTestRunnerUTest::instance(); return currentTest_; } ////////////// NullTest //////////// NullTest::NullTest() : Utest("NullGroup", "NullName", "NullFile", -1, 0) { } NullTest::NullTest(const char* fileName, int lineNumber) : Utest("NullGroup", "NullName", fileName, lineNumber, 0) { } NullTest::~NullTest() { } NullTest& NullTest::instance() { static NullTest _instance; return _instance; } int NullTest::countTests() { return 0; } Utest* NullTest::getNext() const { return &instance(); } bool NullTest::isNull() const { return true; } ////////////// TestInstaller //////////// TestInstaller::TestInstaller(Utest* t, const char* groupName, const char* testName, const char* fileName, int lineNumber) { t->setGroupName(groupName); t->setTestName(testName); t->setFileName(fileName); t->setLineNumber(lineNumber); TestRegistry::getCurrentRegistry()->addTest(t); } TestInstaller::~TestInstaller() { } void TestInstaller::unDo() { TestRegistry::getCurrentRegistry()->unDoLastAddTest(); }
null
411
cpp
blalor-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/MemoryLeakAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" #define UNKNOWN ((char*)("<unknown>")) SimpleStringBuffer::SimpleStringBuffer() : positions_filled_(0), write_limit_(SIMPLE_STRING_BUFFER_LEN-1) { } void SimpleStringBuffer::clear() { positions_filled_ = 0; buffer_[0] = '\0'; } void SimpleStringBuffer::add(const char* format, ...) { int count = 0; int positions_left = write_limit_ - positions_filled_; if (positions_left <= 0) return; va_list arguments; va_start(arguments, format); count = PlatformSpecificVSNprintf(buffer_ + positions_filled_, positions_left+1, format, arguments); if (count > 0) positions_filled_ += count; if (positions_filled_ > write_limit_) positions_filled_ = write_limit_; va_end(arguments); } char* SimpleStringBuffer::toString() { return buffer_; } void SimpleStringBuffer::setWriteLimit(int 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_; } //////////////////////// void MemoryLeakDetectorNode::init(char* memory, size_t size, MemoryLeakAllocator* allocator, MemLeakPeriod period, const char* file, int line) { memory_ = memory; size_ = size; allocator_ = allocator; period_ = period; file_ = file; line_ = line; } /////////////////////// bool MemoryLeakDetectorList::isInPeriod(MemoryLeakDetectorNode* node, MemLeakPeriod period) { return period == mem_leak_period_all || node->period_ == period || (node->period_ != mem_leak_period_disabled && period == mem_leak_period_enabled); } void MemoryLeakDetectorList::clearAllAccounting(MemLeakPeriod period) { MemoryLeakDetectorNode* cur = head_; MemoryLeakDetectorNode* prev = 0; while (cur) { if (isInPeriod(cur, period)) { if (prev) { prev->next_ = cur->next_; cur = prev; } else { head_ = cur->next_; cur = head_; continue; } } prev = cur; cur = cur->next_; } } void MemoryLeakDetectorList::addNewNode(MemoryLeakDetectorNode* node) { node->next_ = head_; head_ = node; } MemoryLeakDetectorNode* MemoryLeakDetectorList::removeNode(char* memory) { MemoryLeakDetectorNode* cur = head_; MemoryLeakDetectorNode* prev = 0; while (cur) { if (cur->memory_ == memory) { if (prev) { prev->next_ = cur->next_; return cur; } else { head_ = cur->next_; return cur; } } prev = cur; cur = cur->next_; } return 0; } MemoryLeakDetectorNode* MemoryLeakDetectorList::retrieveNode(char* memory) { MemoryLeakDetectorNode* cur = head_; while (cur) { if (cur->memory_ == memory) return cur; cur = cur->next_; } return NULL; } MemoryLeakDetectorNode* MemoryLeakDetectorList::getLeakFrom(MemoryLeakDetectorNode* node, MemLeakPeriod period) { for (MemoryLeakDetectorNode* cur = node; cur; cur = cur->next_) if (isInPeriod(cur, period)) return cur; return 0; } MemoryLeakDetectorNode* MemoryLeakDetectorList::getFirstLeak(MemLeakPeriod period) { return getLeakFrom(head_, period); } MemoryLeakDetectorNode* MemoryLeakDetectorList::getNextLeak(MemoryLeakDetectorNode* node, MemLeakPeriod period) { return getLeakFrom(node->next_, period); } int MemoryLeakDetectorList::getTotalLeaks(MemLeakPeriod period) { int total_leaks = 0; for (MemoryLeakDetectorNode* node = head_; node; node = node->next_) { if (isInPeriod(node, period)) total_leaks++; } return total_leaks; } bool MemoryLeakDetectorList::hasLeaks(MemLeakPeriod period) { for (MemoryLeakDetectorNode* node = head_; node; node = node->next_) if (isInPeriod(node, period)) return true; return false; } ///////////////////////////////////////////////////////////// unsigned long MemoryLeakDetectorTable::hash(char* memory) { return ((unsigned long) memory) % hash_prime; } void MemoryLeakDetectorTable::clearAllAccounting(MemLeakPeriod period) { for (int i = 0; i < hash_prime; i++) table_[i].clearAllAccounting(period); } void MemoryLeakDetectorTable::addNewNode(MemoryLeakDetectorNode* node) { table_[hash(node->memory_)].addNewNode(node); } MemoryLeakDetectorNode* MemoryLeakDetectorTable::removeNode(char* memory) { return table_[hash(memory)].removeNode(memory); } MemoryLeakDetectorNode* MemoryLeakDetectorTable::retrieveNode(char* memory) { return table_[hash(memory)].retrieveNode(memory); } bool MemoryLeakDetectorTable::hasLeaks(MemLeakPeriod period) { for (int i = 0; i < hash_prime; i++) if (table_[i].hasLeaks(period)) return true; return false; } int MemoryLeakDetectorTable::getTotalLeaks(MemLeakPeriod period) { int total_leaks = 0; for (int i = 0; i < hash_prime; i++) total_leaks += table_[i].getTotalLeaks(period); return total_leaks; } MemoryLeakDetectorNode* MemoryLeakDetectorTable::getFirstLeak(MemLeakPeriod period) { for (int i = 0; i < hash_prime; i++) { MemoryLeakDetectorNode* node = table_[i].getFirstLeak(period); if (node) return node; } return 0; } MemoryLeakDetectorNode* MemoryLeakDetectorTable::getNextLeak(MemoryLeakDetectorNode* leak, MemLeakPeriod period) { int i = hash(leak->memory_); MemoryLeakDetectorNode* node = table_[i].getNextLeak(leak, period); if (node) return node; for (++i; i < hash_prime; i++) { node = table_[i].getFirstLeak(period); if (node) return node; } return 0; } ///////////////////////////////////////////////////////////// MemoryLeakDetector::MemoryLeakDetector() { } void MemoryLeakDetector::init(MemoryLeakFailure* reporter) { doAllocationTypeChecking_ = true; current_period_ = mem_leak_period_disabled; reporter_ = reporter; output_buffer_ = SimpleStringBuffer(); memoryTable_ = MemoryLeakDetectorTable(); } void MemoryLeakDetector::clearAllAccounting(MemLeakPeriod period) { memoryTable_.clearAllAccounting(period); } void MemoryLeakDetector::startChecking() { output_buffer_.clear(); current_period_ = mem_leak_period_checking; } void MemoryLeakDetector::stopChecking() { current_period_ = mem_leak_period_enabled; } void MemoryLeakDetector::enable() { current_period_ = mem_leak_period_enabled; } void MemoryLeakDetector::disable() { current_period_ = mem_leak_period_disabled; } void MemoryLeakDetector::disableAllocationTypeChecking() { doAllocationTypeChecking_ = false; } void MemoryLeakDetector::enableAllocationTypeChecking() { doAllocationTypeChecking_ = true; } void MemoryLeakDetector::reportFailure(const char* message, const char* allocFile, int allocLine, size_t allocSize, MemoryLeakAllocator* allocAllocator, const char* freeFile, int freeLine, MemoryLeakAllocator* freeAllocator) { output_buffer_.add(message); output_buffer_.add(MEM_LEAK_ALLOC_LOCATION, allocFile, allocLine, allocSize, allocAllocator->alloc_name()); output_buffer_.add(MEM_LEAK_DEALLOC_LOCATION, freeFile, freeLine, freeAllocator->free_name()); reporter_->fail(output_buffer_.toString()); } size_t calculateIntAlignedSize(size_t size) { return (sizeof(int) - (size % sizeof(int))) + size; } size_t MemoryLeakDetector::sizeOfMemoryWithCorruptionInfo(size_t size) { return calculateIntAlignedSize(size + memory_corruption_buffer_size); } MemoryLeakDetectorNode* MemoryLeakDetector::getNodeFromMemoryPointer(char* memory, size_t memory_size) { return (MemoryLeakDetectorNode*) (memory + sizeOfMemoryWithCorruptionInfo(memory_size)); } void MemoryLeakDetector::storeLeakInformation(MemoryLeakDetectorNode *& node, char *new_memory, size_t size, MemoryLeakAllocator *allocator, const char *file, int line) { node->init(new_memory, size, allocator, current_period_, file, line); addMemoryCorruptionInformation(node->memory_ + node->size_); memoryTable_.addNewNode(node); } char* MemoryLeakDetector::reallocateMemoryAndLeakInformation(MemoryLeakAllocator* allocator, char* memory, size_t size, const char* file, int line) { char* new_memory = (char*) (PlatformSpecificRealloc(memory, sizeOfMemoryWithCorruptionInfo(size))); if (new_memory == NULL) return NULL; MemoryLeakDetectorNode *node = (MemoryLeakDetectorNode*) (allocator->allocMemoryLeakNode(sizeof(MemoryLeakDetectorNode))); storeLeakInformation(node, new_memory, size, allocator, file, line); return node->memory_; } void MemoryLeakDetector::invalidateMemory(char* memory) { MemoryLeakDetectorNode* node = memoryTable_.retrieveNode(memory); if (node) PlatformSpecificMemset(memory, 0xCD, node->size_); } void MemoryLeakDetector::addMemoryCorruptionInformation(char* memory) { memory[0] = 'B'; memory[1] = 'A'; memory[2] = 'S'; } bool MemoryLeakDetector::validMemoryCorruptionInformation(char* memory) { return memory[0] == 'B' && memory[1] == 'A' && memory[2] == 'S'; } bool MemoryLeakDetector::matchingAllocation(MemoryLeakAllocator *alloc_allocator, MemoryLeakAllocator *free_allocator) { if (alloc_allocator == free_allocator) return true; if (!doAllocationTypeChecking_) return true; return free_allocator->isOfEqualType(alloc_allocator); } void MemoryLeakDetector::checkForCorruption(MemoryLeakDetectorNode* node, const char* file, int line, MemoryLeakAllocator* allocator) { if (!matchingAllocation(node->allocator_, allocator)) reportFailure(MEM_LEAK_ALLOC_DEALLOC_MISMATCH, node->file_, node->line_, node->size_, node->allocator_, file, line, allocator); else if (!validMemoryCorruptionInformation(node->memory_ + node->size_)) reportFailure(MEM_LEAK_MEMORY_CORRUPTION, node->file_, node->line_, node->size_, node->allocator_, file, line, allocator); else if (allocator->allocateMemoryLeakNodeSeparately()) allocator->freeMemoryLeakNode((char*) node); } char* MemoryLeakDetector::allocMemory(MemoryLeakAllocator* allocator, size_t size) { return allocMemory(allocator, size, UNKNOWN, 0); } char* MemoryLeakDetector::allocMemory(MemoryLeakAllocator* allocator, size_t size, const char* file, int line) { /* 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; MemoryLeakDetectorNode* node; if (allocator->allocateMemoryLeakNodeSeparately()) { memory = allocator->alloc_memory(sizeOfMemoryWithCorruptionInfo(size), file, line); if (memory == NULL) return NULL; node = (MemoryLeakDetectorNode*) allocator->allocMemoryLeakNode(sizeof(MemoryLeakDetectorNode)); } else { memory = allocator->alloc_memory(sizeOfMemoryWithCorruptionInfo(size) + sizeof(MemoryLeakDetectorNode), file, line); if (memory == NULL) return NULL; node = getNodeFromMemoryPointer(memory, size); } storeLeakInformation(node, memory, size, allocator, file, line); return node->memory_; } void MemoryLeakDetector::removeMemoryLeakInformationWithoutCheckingOrDeallocating(void* memory) { memoryTable_.removeNode((char*) memory); } void MemoryLeakDetector::deallocMemory(MemoryLeakAllocator* allocator, void* memory, const char* file, int line) { if (memory == 0) return; MemoryLeakDetectorNode* node = memoryTable_.removeNode((char*) memory); if (node == NULL) { reportFailure(MEM_LEAK_DEALLOC_NON_ALLOCATED, "<unknown>", 0, 0, NullUnknownAllocator::defaultAllocator(), file, line, allocator); return; } checkForCorruption(node, file, line, allocator); allocator->free_memory((char*) memory, file, line); } void MemoryLeakDetector::deallocMemory(MemoryLeakAllocator* allocator, void* memory) { deallocMemory(allocator, (char*) memory, UNKNOWN, 0); } char* MemoryLeakDetector::reallocMemory(MemoryLeakAllocator* allocator, char* memory, size_t size, const char* file, int line) { if (memory) { MemoryLeakDetectorNode* node = memoryTable_.removeNode(memory); if (node == NULL) { reportFailure(MEM_LEAK_DEALLOC_NON_ALLOCATED, "<unknown>", 0, 0, NullUnknownAllocator::defaultAllocator(), file, line, allocator); return NULL; } checkForCorruption(node, file, line, allocator); } return reallocateMemoryAndLeakInformation(allocator, memory, size, file, line); } void MemoryLeakDetector::ConstructMemoryLeakReport(MemLeakPeriod period) { MemoryLeakDetectorNode* leak = memoryTable_.getFirstLeak(period); int total_leaks = 0; bool giveWarningOnUsingMalloc = false; output_buffer_.add(MEM_LEAK_HEADER); output_buffer_.setWriteLimit(SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN - MEM_LEAK_NORMAL_MALLOC_FOOTER_SIZE); while (leak) { output_buffer_.add(MEM_LEAK_LEAK, leak->size_, leak->file_, leak->line_, leak->allocator_->alloc_name(), leak->memory_); if (leak->allocator_->allocateMemoryLeakNodeSeparately()) giveWarningOnUsingMalloc = true; total_leaks++; leak = memoryTable_.getNextLeak(leak, period); } bool buffer_reached_its_capacity = output_buffer_.reachedItsCapacity(); output_buffer_.resetWriteLimit(); if (buffer_reached_its_capacity) output_buffer_.add(MEM_LEAK_TOO_MUCH); output_buffer_.add("%s %d\n", MEM_LEAK_FOOTER, total_leaks); if (giveWarningOnUsingMalloc) output_buffer_.add(MEM_LEAK_ADDITION_MALLOC_WARNING); } const char* MemoryLeakDetector::report(MemLeakPeriod period) { if (!memoryTable_.hasLeaks(period)) return MEM_LEAK_NONE; output_buffer_.clear(); ConstructMemoryLeakReport(period); return output_buffer_.toString(); } void MemoryLeakDetector::markCheckingPeriodLeaksAsNonCheckingPeriod() { MemoryLeakDetectorNode* leak = memoryTable_.getFirstLeak(mem_leak_period_checking); while (leak) { if (leak->period_ == mem_leak_period_checking) leak->period_ = mem_leak_period_enabled; leak = memoryTable_.getNextLeak(leak, mem_leak_period_checking); } } int MemoryLeakDetector::totalMemoryLeaks(MemLeakPeriod period) { return memoryTable_.getTotalLeaks(period); }
null
412
cpp
blalor-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. */ /////////////////////////////////////////////////////////////////////////////// // // TESTHARNESS_c.H // // /////////////////////////////////////////////////////////////////////////////// #include "CppUTest/TestHarness.h" #include "CppUTest/MemoryLeakDetector.h" #include "CppUTest/MemoryLeakAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" extern "C" { #include "CppUTest/TestHarness_c.h" void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, const char* fileName, int lineNumber) { CHECK_EQUAL_LOCATION((long)expected, (long)actual, fileName, lineNumber); } void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* fileName, int lineNumber) { DOUBLES_EQUAL_LOCATION(expected, actual, threshold, fileName, lineNumber); } void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* fileName, int lineNumber) { CHECK_EQUAL_LOCATION(expected, actual, fileName, lineNumber); } void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* fileName, int lineNumber) { STRCMP_EQUAL_LOCATION(expected, actual, fileName, lineNumber); } void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, int lineNumber) { FAIL_LOCATION(text, fileName, lineNumber); } void FAIL_C_LOCATION(const char* fileName, int lineNumber) { FAIL_LOCATION("", fileName, lineNumber); } void CHECK_C_LOCATION(int condition, const char* conditionString, const char* fileName, int lineNumber) { CHECK_LOCATION_TRUE(((condition) == 0 ? false : true), "CHECK_C", conditionString, fileName, lineNumber); } enum { NO_COUNTDOWN = -1, OUT_OF_MEMORRY = 0 }; static int malloc_out_of_memory_counter = NO_COUNTDOWN; static int malloc_count = 0; void cpputest_malloc_count_reset(void) { malloc_count = 0; } int cpputest_malloc_get_count() { return malloc_count; } void cpputest_malloc_set_out_of_memory() { MemoryLeakAllocator::setCurrentMallocAllocator(NullUnknownAllocator::defaultAllocator()); } void cpputest_malloc_set_not_out_of_memory() { malloc_out_of_memory_counter = NO_COUNTDOWN; MemoryLeakAllocator::setCurrentMallocAllocatorToDefault(); } void cpputest_malloc_set_out_of_memory_countdown(int count) { malloc_out_of_memory_counter = count; if (malloc_out_of_memory_counter == OUT_OF_MEMORRY) cpputest_malloc_set_out_of_memory(); } void* cpputest_malloc(size_t size) { return cpputest_malloc_location(size, "<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, int line) { countdown(); malloc_count++; return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(MemoryLeakAllocator::getCurrentMallocAllocator(), size, file, line); } void* cpputest_calloc_location(size_t num, size_t size, const char* file, int line) { void* mem = cpputest_malloc_location(num * size, file, line); PlatformSpecificMemset(mem, 0, num*size); return mem; } void* cpputest_realloc_location(void* memory, size_t size, const char* file, int line) { return MemoryLeakWarningPlugin::getGlobalDetector()->reallocMemory(MemoryLeakAllocator::getCurrentMallocAllocator(), (char*) memory, size, file, line); } void cpputest_free_location(void* buffer, const char* file, int line) { MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) buffer); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(MemoryLeakAllocator::getCurrentMallocAllocator(), (char*) buffer, file, line); } }
null
413
cpp
blalor-cpputest
NullJUnitTestOutput.cpp
src/CppUTest/Nulls/NullJUnitTestOutput.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/Failure.h" //struct JUnitTestOutputImpl //{ // //}; // JUnitTestOutput::JUnitTestOutput() : impl_(0) { } JUnitTestOutput::~JUnitTestOutput() { } void JUnitTestOutput::resetTestGroupResult() { } void JUnitTestOutput::printTestsStarted() { } void JUnitTestOutput::printCurrentGroupStarted(const Utest& test) { } void JUnitTestOutput::printCurrentTestEnded(const TestResult& result) { } void JUnitTestOutput::printTestsEnded(const TestResult& result) { } void JUnitTestOutput::printCurrentGroupEnded(const TestResult& result) { } void JUnitTestOutput::printCurrentTestStarted(const Utest& test) { } void JUnitTestOutput::writeXmlHeader() { } void JUnitTestOutput::writeTestSuiteSummery() { } void JUnitTestOutput::writeProperties() { } void JUnitTestOutput::writeTestCases() { } void JUnitTestOutput::writeFailure(JUnitTestCaseResultNode* node) { } void JUnitTestOutput::writeFileEnding() { } void JUnitTestOutput::writeTestGroupToFile() { } void JUnitTestOutput::verbose() { } void JUnitTestOutput::print(const char*) { } void JUnitTestOutput::print(long) { } void JUnitTestOutput::print(const TestFailure& failure) { } void JUnitTestOutput::printTestRun(int number, int total) { } void JUnitTestOutput::flush() { } void JUnitTestOutput::openFileForWrite(const SimpleString& fileName) { } void JUnitTestOutput::writeToFile(const SimpleString& buffer) { } void JUnitTestOutput::closeFile() { }
null
414
cpp
blalor-cpputest
OrderedTest.cpp
src/CppUTestExt/OrderedTest.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 "CppUTestExt/OrderedTest.h" OrderedTest* OrderedTest::_orderedTestsHead = 0; OrderedTest::OrderedTest() : _nextOrderedTest(0) { } OrderedTest::~OrderedTest() { } int OrderedTest::getLevel() { return _level; } void OrderedTest::setLevel(int level) { _level = level; } void OrderedTest::setOrderedTestHead(OrderedTest* test) { _orderedTestsHead = test; } OrderedTest* OrderedTest::getOrderedTestHead() { return _orderedTestsHead; } bool OrderedTest::firstOrderedTest() { return (getOrderedTestHead() == 0); } OrderedTest* OrderedTest::addOrderedTest(OrderedTest* test) { Utest::addTest(test); _nextOrderedTest = test; return this; } void OrderedTest::addOrderedTestToHead(OrderedTest* test) { TestRegistry *reg = TestRegistry::getCurrentRegistry(); if (reg->getFirstTest()->isNull() || getOrderedTestHead() == reg->getFirstTest()) reg->addTest(test); else reg->getTestWithNext(getOrderedTestHead())->addTest(test); test->_nextOrderedTest = getOrderedTestHead(); setOrderedTestHead(test); } OrderedTest* OrderedTest::getNextOrderedTest() { return _nextOrderedTest; } OrderedTestInstaller::OrderedTestInstaller(OrderedTest* test, const char* groupName, const char* testName, const char* fileName, int lineNumber, int level) { test->setTestName(testName); test->setGroupName(groupName); test->setFileName(fileName); test->setLineNumber(lineNumber); test->setLevel(level); if (OrderedTest::firstOrderedTest()) OrderedTest::addOrderedTestToHead(test); else addOrderedTestInOrder(test); } void OrderedTestInstaller::addOrderedTestInOrder(OrderedTest* test) { if (test->getLevel() < OrderedTest::getOrderedTestHead()->getLevel()) OrderedTest::addOrderedTestToHead( test); else addOrderedTestInOrderNotAtHeadPosition(test); } void OrderedTestInstaller::addOrderedTestInOrderNotAtHeadPosition( OrderedTest* test) { OrderedTest* current = OrderedTest::getOrderedTestHead(); while (current->getNextOrderedTest()) { if (current->getNextOrderedTest()->getLevel() > test->getLevel()) { test->addOrderedTest(current->getNextOrderedTest()); current->addOrderedTest(test); return; } current = current->getNextOrderedTest(); } test->addOrderedTest(current->getNextOrderedTest()); current->addOrderedTest(test); } OrderedTestInstaller::~OrderedTestInstaller() { }
null
415
cpp
blalor-cpputest
MemoryReportAllocator.cpp
src/CppUTestExt/MemoryReportAllocator.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 "CppUTestExt/MemoryReportAllocator.h" #include "CppUTestExt/MemoryReportFormatter.h" MemoryReportAllocator::MemoryReportAllocator() : result_(NULL), realAllocator_(NULL), formatter_(NULL) { } MemoryReportAllocator::~MemoryReportAllocator() { } const char* MemoryReportAllocator::name() { return realAllocator_->name(); } const char* MemoryReportAllocator::alloc_name() { return realAllocator_->alloc_name(); } const char* MemoryReportAllocator::free_name() { return realAllocator_->free_name(); } void MemoryReportAllocator::setRealAllocator(MemoryLeakAllocator* allocator) { realAllocator_ = allocator; } bool MemoryReportAllocator::allocateMemoryLeakNodeSeparately() { return realAllocator_->allocateMemoryLeakNodeSeparately(); } MemoryLeakAllocator* MemoryReportAllocator::getRealAllocator() { return realAllocator_; } void MemoryReportAllocator::setTestResult(TestResult* result) { result_ = result; } void MemoryReportAllocator::setFormatter(MemoryReportFormatter* formatter) { formatter_ = formatter; } char* MemoryReportAllocator::alloc_memory(size_t size, const char* file, int line) { char* memory = realAllocator_->alloc_memory(size, file, line); if (result_ && formatter_) formatter_->report_alloc_memory(result_, this, size, memory, file, line); return memory; } void MemoryReportAllocator::free_memory(char* memory, const char* file, int line) { realAllocator_->free_memory(memory, file, line); if (result_ && formatter_) formatter_->report_free_memory(result_, this, memory, file, line); }
null
416
cpp
blalor-cpputest
MockFailure.cpp
src/CppUTestExt/MockFailure.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 "CppUTestExt/MockFailure.h" #include "CppUTestExt/MockExpectedFunctionCall.h" #include "CppUTestExt/MockExpectedFunctionsList.h" void MockFailureReporter::failTest(const MockFailure& failure) { getTestToFail()->getTestResult()->addFailure(failure); if (crashOnFailure_) UT_CRASH(); getTestToFail()->exitCurrentTest(); } Utest* MockFailureReporter::getTestToFail() { return Utest::getCurrent(); } MockFailure::MockFailure(Utest* test) : TestFailure(test, "Test failed with MockFailure without an error! Something went seriously wrong.") { } void MockFailure::addExpectationsAndCallHistory(const MockExpectedFunctionsList& expectations) { message_ += "\tEXPECTED calls that did NOT happen:\n"; message_ += expectations.unfulfilledFunctionsToString("\t\t"); message_ += "\n\tACTUAL calls that did happen (in call order):\n"; message_ += expectations.fulfilledFunctionsToString("\t\t"); } void MockFailure::addExpectationsAndCallHistoryRelatedTo(const SimpleString& name, const MockExpectedFunctionsList& expectations) { MockExpectedFunctionsList expectationsForFunction; expectationsForFunction.addExpectationsRelatedTo(name, expectations); message_ += "\tEXPECTED calls that DID NOT happen related to function: "; message_ += name; message_ += "\n"; message_ += expectationsForFunction.unfulfilledFunctionsToString("\t\t"); message_ += "\n\tACTUAL calls that DID happen related to function: "; message_ += name; message_ += "\n"; message_ += expectationsForFunction.fulfilledFunctionsToString("\t\t"); } MockExpectedCallsDidntHappenFailure::MockExpectedCallsDidntHappenFailure(Utest* test, const MockExpectedFunctionsList& expectations) : MockFailure(test) { message_ = "Mock Failure: Expected call did not happen.\n"; addExpectationsAndCallHistory(expectations); } MockUnexpectedCallHappenedFailure::MockUnexpectedCallHappenedFailure(Utest* test, const SimpleString& name, const MockExpectedFunctionsList& expectations) : MockFailure(test) { int amountOfExpectations = expectations.amountOfExpectationsFor(name); if (amountOfExpectations) message_ = StringFromFormat("Mock Failure: Unexpected additional (%dth) call to function: ", amountOfExpectations+1); else message_ = "Mock Failure: Unexpected call to function: "; message_ += name; message_ += "\n"; addExpectationsAndCallHistory(expectations); } MockCallOrderFailure::MockCallOrderFailure(Utest* test, const MockExpectedFunctionsList& expectations) : MockFailure(test) { message_ = "Mock Failure: Out of order calls"; message_ += "\n"; addExpectationsAndCallHistory(expectations); } MockUnexpectedParameterFailure::MockUnexpectedParameterFailure(Utest* test, const SimpleString& functionName, const MockNamedValue& parameter, const MockExpectedFunctionsList& expectations) : MockFailure(test) { MockExpectedFunctionsList expectationsForFunctionWithParameterName; expectationsForFunctionWithParameterName.addExpectationsRelatedTo(functionName, expectations); expectationsForFunctionWithParameterName.onlyKeepExpectationsWithParameterName(parameter.getName()); if (expectationsForFunctionWithParameterName.isEmpty()) { message_ = "Mock Failure: Unexpected parameter name to function \""; message_ += functionName; message_ += "\": "; message_ += parameter.getName(); } else { message_ = "Mock Failure: Unexpected parameter value to parameter \""; message_ += parameter.getName(); message_ += "\" to function \""; message_ += functionName; message_ += "\": <"; message_ += StringFrom(parameter); message_ += ">"; } message_ += "\n"; addExpectationsAndCallHistoryRelatedTo(functionName, expectations); message_ += "\n\tACTUAL unexpected parameter passed to function: "; message_ += functionName; message_ += "\n"; message_ += "\t\t"; message_ += parameter.getType(); message_ += " "; message_ += parameter.getName(); message_ += ": <"; message_ += StringFrom(parameter); message_ += ">"; } MockExpectedParameterDidntHappenFailure::MockExpectedParameterDidntHappenFailure(Utest* test, const SimpleString& functionName, const MockExpectedFunctionsList& expectations) : MockFailure(test) { MockExpectedFunctionsList expectationsForFunction; expectationsForFunction.addExpectationsRelatedTo(functionName, expectations); message_ = "Mock Failure: Expected parameter for function \""; message_ += functionName; message_ += "\" did not happen.\n"; addExpectationsAndCallHistoryRelatedTo(functionName, expectations); message_ += "\n\tMISSING parameters that didn't happen:\n"; message_ += "\t\t"; message_ += expectationsForFunction.missingParametersToString(); } MockNoWayToCompareCustomTypeFailure::MockNoWayToCompareCustomTypeFailure(Utest* test, const SimpleString& typeName) : MockFailure(test) { message_ = StringFromFormat("MockFailure: No way to compare type <%s>. Please install a ParameterTypeComparator.", typeName.asCharString()); } MockUnexpectedObjectFailure::MockUnexpectedObjectFailure(Utest* test, const SimpleString& functionName, void* actual, const MockExpectedFunctionsList& expectations) : MockFailure(test) { message_ = StringFromFormat ("MockFailure: Function called on a unexpected object: %s\n" "\tActual object for call has address: <%p>\n", functionName.asCharString(),actual); addExpectationsAndCallHistoryRelatedTo(functionName, expectations); } MockExpectedObjectDidntHappenFailure::MockExpectedObjectDidntHappenFailure(Utest* test, const SimpleString& functionName, const MockExpectedFunctionsList& expectations) : MockFailure(test) { message_ = StringFromFormat("Mock Failure: Expected call on object for function \"%s\" but it did not happen.\n", functionName.asCharString()); addExpectationsAndCallHistoryRelatedTo(functionName, expectations); }
null
417
cpp
blalor-cpputest
MemoryReporterPlugin.cpp
src/CppUTestExt/MemoryReporterPlugin.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 "CppUTestExt/MemoryReporterPlugin.h" #include "CppUTestExt/MemoryReportFormatter.h" #include "CppUTestExt/CodeMemoryReportFormatter.h" MemoryReporterPlugin::MemoryReporterPlugin() : TestPlugin("MemoryReporterPlugin"), formatter_(NULL) { } MemoryReporterPlugin::~MemoryReporterPlugin() { removeGlobalMemoryReportAllocators(); destroyMemoryFormatter(formatter_); } bool MemoryReporterPlugin::parseArguments(int /* ac */, const char** av, int index) { SimpleString argument (av[index]); if (argument.contains("-pmemoryreport=")) { argument.replace("-pmemoryreport=", ""); destroyMemoryFormatter(formatter_); formatter_ = createMemoryFormatter(argument); return true; } return false; } MemoryReportFormatter* MemoryReporterPlugin::createMemoryFormatter(const SimpleString& type) { if (type == "normal") { return new NormalMemoryReportFormatter; } else if (type == "code") { return new CodeMemoryReportFormatter(StandardMallocAllocator::defaultAllocator()); } return NULL; } void MemoryReporterPlugin::destroyMemoryFormatter(MemoryReportFormatter* formatter) { delete formatter; } void MemoryReporterPlugin::setGlobalMemoryReportAllocators() { mallocAllocator.setRealAllocator(MemoryLeakAllocator::getCurrentMallocAllocator()); MemoryLeakAllocator::setCurrentMallocAllocator(&mallocAllocator); newAllocator.setRealAllocator(MemoryLeakAllocator::getCurrentNewAllocator()); MemoryLeakAllocator::setCurrentNewAllocator(&newAllocator); newArrayAllocator.setRealAllocator(MemoryLeakAllocator::getCurrentNewArrayAllocator()); MemoryLeakAllocator::setCurrentNewArrayAllocator(&newArrayAllocator); } void MemoryReporterPlugin::removeGlobalMemoryReportAllocators() { if (MemoryLeakAllocator::getCurrentNewAllocator() == &newAllocator) MemoryLeakAllocator::setCurrentNewAllocator(newAllocator.getRealAllocator()); if (MemoryLeakAllocator::getCurrentNewArrayAllocator() == &newArrayAllocator) MemoryLeakAllocator::setCurrentNewArrayAllocator(newArrayAllocator.getRealAllocator()); if (MemoryLeakAllocator::getCurrentMallocAllocator() == &mallocAllocator) MemoryLeakAllocator::setCurrentMallocAllocator(mallocAllocator.getRealAllocator()); } void MemoryReporterPlugin::initializeAllocator(MemoryReportAllocator* allocator, TestResult & result) { allocator->setFormatter(formatter_); allocator->setTestResult((&result)); } void MemoryReporterPlugin::preTestAction(Utest& test, TestResult& result) { if (formatter_ == NULL) return; initializeAllocator(&mallocAllocator, result); initializeAllocator(&newAllocator, result); initializeAllocator(&newArrayAllocator, result); setGlobalMemoryReportAllocators(); if (test.getGroup() != currentTestGroup_) { formatter_->report_testgroup_start(&result, test); currentTestGroup_ = test.getGroup(); } formatter_->report_test_start(&result, test); } void MemoryReporterPlugin::postTestAction(Utest& test, TestResult& result) { if (formatter_ == NULL) return; removeGlobalMemoryReportAllocators(); formatter_->report_test_end(&result, test); if (test.getNext()->getGroup() != currentTestGroup_) formatter_->report_testgroup_end(&result, test); }
null
418
cpp
blalor-cpputest
MockSupport.cpp
src/CppUTestExt/MockSupport.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 "CppUTestExt/MockSupport.h" #include "CppUTestExt/MockActualFunctionCall.h" #include "CppUTestExt/MockExpectedFunctionCall.h" #include "CppUTestExt/MockFailure.h" #define MOCK_SUPPORT_SCOPE_PREFIX "!!!$$$MockingSupportScope$$$!!!" static MockSupport global_mock; int MockSupport::callOrder_ = 0; int MockSupport::expectedCallOrder_ = 0; MockSupport& mock(const SimpleString& mockName) { if (mockName != "") return *global_mock.getMockSupportScope(mockName); return global_mock; } MockSupport::MockSupport() : strictOrdering_(false), reporter_(&defaultReporter_), ignoreOtherCalls_(false), enabled_(true), lastActualFunctionCall_(NULL), tracing_(false) { } MockSupport::~MockSupport() { } void MockSupport::crashOnFailure() { reporter_->crashOnFailure(); } void MockSupport::setMockFailureReporter(MockFailureReporter* reporter) { reporter_ = (reporter != NULL) ? reporter : &defaultReporter_; if (lastActualFunctionCall_) lastActualFunctionCall_->setMockFailureReporter(reporter_); for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->setMockFailureReporter(reporter_); } void MockSupport::installComparator(const SimpleString& typeName, MockNamedValueComparator& comparator) { comparatorRepository_.installComparator(typeName, comparator); for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->installComparator(typeName, comparator); } void MockSupport::installComparators(const MockNamedValueComparatorRepository& repository) { comparatorRepository_.installComparators(repository); for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->installComparators(repository); } void MockSupport::removeAllComparators() { comparatorRepository_.clear(); for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->removeAllComparators(); } void MockSupport::clear() { delete lastActualFunctionCall_; lastActualFunctionCall_ = NULL; tracing_ = false; MockFunctionCallTrace::instance().clear(); expectations_.deleteAllExpectationsAndClearList(); compositeCalls_.clear(); ignoreOtherCalls_ = false; enabled_ = true; callOrder_ = 0; expectedCallOrder_ = 0; strictOrdering_ = false; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) { MockSupport* support = getMockSupport(p); if (support) { support->clear(); delete support; } } data_.clear(); } void MockSupport::strictOrder() { strictOrdering_ = true; } MockFunctionCall& MockSupport::expectOneCall(const SimpleString& functionName) { if (!enabled_) return MockIgnoredCall::instance(); MockExpectedFunctionCall* call = new MockExpectedFunctionCall; call->setComparatorRepository(&comparatorRepository_); call->withName(functionName); if (strictOrdering_) call->withCallOrder(++expectedCallOrder_); expectations_.addExpectedCall(call); return *call; } MockFunctionCall& MockSupport::expectNCalls(int amount, const SimpleString& functionName) { compositeCalls_.clear(); for (int i = 0; i < amount; i++) compositeCalls_.add(expectOneCall(functionName)); return compositeCalls_; } MockActualFunctionCall* MockSupport::createActualFunctionCall() { lastActualFunctionCall_ = new MockActualFunctionCall(++callOrder_, reporter_, expectations_); return lastActualFunctionCall_; } MockFunctionCall& MockSupport::actualCall(const SimpleString& functionName) { if (lastActualFunctionCall_) { lastActualFunctionCall_->checkExpectations(); delete lastActualFunctionCall_; lastActualFunctionCall_ = NULL; } if (!enabled_) return MockIgnoredCall::instance(); if (tracing_) return MockFunctionCallTrace::instance().withName(functionName); if (!expectations_.hasExpectationWithName(functionName) && ignoreOtherCalls_) { return MockIgnoredCall::instance(); } MockActualFunctionCall* call = createActualFunctionCall(); call->setComparatorRepository(&comparatorRepository_); call->withName(functionName); return *call; } void MockSupport::ignoreOtherCalls() { ignoreOtherCalls_ = true; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->ignoreOtherCalls(); } void MockSupport::disable() { enabled_ = false; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->disable(); } void MockSupport::enable() { enabled_ = true; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->enable(); } void MockSupport::tracing(bool enabled) { tracing_ = enabled; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->tracing(enabled); } const char* MockSupport::getTraceOutput() { return MockFunctionCallTrace::instance().getTraceOutput(); } bool MockSupport::expectedCallsLeft() { int callsLeft = expectations_.hasUnfullfilledExpectations(); for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) callsLeft += getMockSupport(p)->expectedCallsLeft(); return callsLeft; } bool MockSupport::wasLastCallFulfilled() { if (lastActualFunctionCall_ && !lastActualFunctionCall_->isFulfilled()) return false; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p) && !getMockSupport(p)->wasLastCallFulfilled()) return false; return true; } void MockSupport::failTestWithUnexpectedCalls() { MockExpectedFunctionsList expectationsList; expectationsList.addExpectations(expectations_); for(MockNamedValueListNode *p = data_.begin();p;p = p->next()) if(getMockSupport(p)) expectationsList.addExpectations(getMockSupport(p)->expectations_); MockExpectedCallsDidntHappenFailure failure(reporter_->getTestToFail(), expectationsList); clear(); reporter_->failTest(failure); } void MockSupport::failTestWithOutOfOrderCalls() { MockExpectedFunctionsList expectationsList; expectationsList.addExpectations(expectations_); for(MockNamedValueListNode *p = data_.begin();p;p = p->next()) if(getMockSupport(p)) expectationsList.addExpectations(getMockSupport(p)->expectations_); MockCallOrderFailure failure(reporter_->getTestToFail(), expectationsList); clear(); reporter_->failTest(failure); } void MockSupport::checkExpectationsOfLastCall() { if(lastActualFunctionCall_) lastActualFunctionCall_->checkExpectations(); for(MockNamedValueListNode *p = data_.begin();p;p = p->next()) if(getMockSupport(p) && getMockSupport(p)->lastActualFunctionCall_) getMockSupport(p)->lastActualFunctionCall_->checkExpectations(); } void MockSupport::checkExpectations() { checkExpectationsOfLastCall(); if (wasLastCallFulfilled() && expectedCallsLeft()) failTestWithUnexpectedCalls(); if (expectations_.hasCallsOutOfOrder()) failTestWithOutOfOrderCalls(); } bool MockSupport::hasData(const SimpleString& name) { return data_.getValueByName(name) != NULL; } MockNamedValue* MockSupport::retrieveDataFromStore(const SimpleString& name) { MockNamedValue* newData = data_.getValueByName(name); if (newData == NULL) { newData = new MockNamedValue(name); data_.add(newData); } return newData; } void MockSupport::setData(const SimpleString& name, int value) { MockNamedValue* newData = retrieveDataFromStore(name); newData->setValue(value); } void MockSupport::setData(const SimpleString& name, const char* value) { MockNamedValue* newData = retrieveDataFromStore(name); newData->setValue(value); } void MockSupport::setData(const SimpleString& name, double value) { MockNamedValue* newData = retrieveDataFromStore(name); newData->setValue(value); } void MockSupport::setData(const SimpleString& name, void* value) { MockNamedValue* newData = retrieveDataFromStore(name); newData->setValue(value); } void MockSupport::setDataObject(const SimpleString& name, const SimpleString& type, void* value) { MockNamedValue* newData = retrieveDataFromStore(name); newData->setObjectPointer(type, value); } MockNamedValue MockSupport::getData(const SimpleString& name) { MockNamedValue* value = data_.getValueByName(name); if (value == NULL) return MockNamedValue(""); return *value; } MockSupport* MockSupport::getMockSupportScope(const SimpleString& name) { SimpleString mockingSupportName = MOCK_SUPPORT_SCOPE_PREFIX; mockingSupportName += name; if (hasData(mockingSupportName)) { STRCMP_EQUAL("MockSupport", getData(mockingSupportName).getType().asCharString()); return (MockSupport*) getData(mockingSupportName).getObjectPointer(); } MockSupport *newMock = new MockSupport; newMock->setMockFailureReporter(reporter_); if (ignoreOtherCalls_) newMock->ignoreOtherCalls(); if (!enabled_) newMock->disable(); newMock->tracing(tracing_); newMock->installComparators(comparatorRepository_); setDataObject(mockingSupportName, "MockSupport", newMock); return newMock; } MockSupport* MockSupport::getMockSupport(MockNamedValueListNode* node) { if (node->getType() == "MockSupport" && node->getName().contains(MOCK_SUPPORT_SCOPE_PREFIX)) return (MockSupport*) node->item()->getObjectPointer(); return NULL; } MockNamedValue MockSupport::returnValue() { if (lastActualFunctionCall_) return lastActualFunctionCall_->returnValue(); return MockNamedValue(""); } int MockSupport::intReturnValue() { return returnValue().getIntValue(); } const char* MockSupport::stringReturnValue() { return returnValue().getStringValue(); } double MockSupport::doubleReturnValue() { return returnValue().getDoubleValue(); } void* MockSupport::pointerReturnValue() { return returnValue().getPointerValue(); } bool MockSupport::hasReturnValue() { if (lastActualFunctionCall_) return lastActualFunctionCall_->hasReturnValue(); return false; }
null
419
cpp
blalor-cpputest
MockSupport_c.cpp
src/CppUTestExt/MockSupport_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 "CppUTestExt/MockSupport.h" extern "C" { #include "CppUTestExt/MockSupport_c.h" } #include <string.h> static MockSupport* currentMockSupport = NULL; static MockFunctionCall* currentCall = NULL; class MockCFunctionComparatorNode : public MockNamedValueComparator { public: MockCFunctionComparatorNode(MockCFunctionComparatorNode* next, MockTypeEqualFunction_c equal, MockTypeValueToStringFunction_c toString) : next_(next), equal_(equal), toString_(toString) {} virtual ~MockCFunctionComparatorNode() {}; virtual bool isEqual(void* object1, void* object2) { return (bool) equal_(object1, object2); } virtual SimpleString valueToString(void* object) { return SimpleString(toString_(object)); } MockCFunctionComparatorNode* next_; MockTypeEqualFunction_c equal_; MockTypeValueToStringFunction_c toString_; }; static MockCFunctionComparatorNode* comparatorList_ = NULL; extern "C" { MockFunctionCall_c* expectOneCall_c(const char* name); MockFunctionCall_c* actualCall_c(const char* name); void setIntData_c(const char* name, int value); void setDoubleData_c(const char* name, double value); void setStringData_c(const char* name, const char* value); void setPointerData_c(const char* name, void* value); void setDataObject_c(const char* name, const char* type, void* value); MockValue_c getData_c(const char* name); void checkExpectations_c(); int expectedCallsLeft_c(); void clear_c(); MockFunctionCall_c* withIntParameters_c(const char* name, int value); MockFunctionCall_c* withDoubleParameters_c(const char* name, double value); MockFunctionCall_c* withStringParameters_c(const char* name, const char* value); MockFunctionCall_c* withPointerParameters_c(const char* name, void* value); MockFunctionCall_c* withParameterOfType_c(const char* type, const char* name, void* value); MockFunctionCall_c* andReturnIntValue_c(int value); MockFunctionCall_c* andReturnDoubleValue_c(double value); MockFunctionCall_c* andReturnStringValue_c(const char* value); MockFunctionCall_c* andReturnPointerValue_c(void* value); MockValue_c returnValue_c(); void installComparator_c (const char* typeName, MockTypeEqualFunction_c isEqual, MockTypeValueToStringFunction_c valueToString) { comparatorList_ = new MockCFunctionComparatorNode(comparatorList_, isEqual, valueToString); currentMockSupport->installComparator(typeName, *comparatorList_); } void removeAllComparators_c() { while (comparatorList_) { MockCFunctionComparatorNode *next = comparatorList_->next_; delete comparatorList_; comparatorList_ = next; } currentMockSupport->removeAllComparators(); } static MockFunctionCall_c gFunctionCall = { withIntParameters_c, withDoubleParameters_c, withStringParameters_c, withPointerParameters_c, withParameterOfType_c, andReturnIntValue_c, andReturnDoubleValue_c, andReturnStringValue_c, andReturnPointerValue_c, returnValue_c }; static MockSupport_c gMockSupport = { expectOneCall_c, actualCall_c, returnValue_c, setIntData_c, setDoubleData_c, setStringData_c, setPointerData_c, setDataObject_c, getData_c, checkExpectations_c, expectedCallsLeft_c, clear_c, installComparator_c, removeAllComparators_c }; MockFunctionCall_c* withIntParameters_c(const char* name, int value) { currentCall = &currentCall->withParameter(name, value); return &gFunctionCall; } MockFunctionCall_c* withDoubleParameters_c(const char* name, double value) { currentCall = &currentCall->withParameter(name, value); return &gFunctionCall; } MockFunctionCall_c* withStringParameters_c(const char* name, const char* value) { currentCall = &currentCall->withParameter(name, value); return &gFunctionCall; } MockFunctionCall_c* withPointerParameters_c(const char* name, void* value) { currentCall = &currentCall->withParameter(name, value); return &gFunctionCall; } MockFunctionCall_c* withParameterOfType_c(const char* type, const char* name, void* value) { currentCall = &currentCall->withParameterOfType(type, name, value); return &gFunctionCall; } MockFunctionCall_c* andReturnIntValue_c(int value) { currentCall = &currentCall->andReturnValue(value); return &gFunctionCall; } MockFunctionCall_c* andReturnDoubleValue_c(double value) { currentCall = &currentCall->andReturnValue(value); return &gFunctionCall; } MockFunctionCall_c* andReturnStringValue_c(const char* value) { currentCall = &currentCall->andReturnValue(value); return &gFunctionCall; } MockFunctionCall_c* andReturnPointerValue_c(void* value) { currentCall = &currentCall->andReturnValue(value); return &gFunctionCall; } static MockValue_c getMockValueCFromNamedValue(const MockNamedValue& namedValue) { MockValue_c returnValue; if (strcmp(namedValue.getType().asCharString(), "int") == 0) { returnValue.type = MOCKVALUETYPE_INTEGER; returnValue.value.intValue = namedValue.getIntValue(); } else if (strcmp(namedValue.getType().asCharString(), "double") == 0) { returnValue.type = MOCKVALUETYPE_DOUBLE; returnValue.value.doubleValue = namedValue.getDoubleValue(); } else if (strcmp(namedValue.getType().asCharString(), "char*") == 0) { returnValue.type = MOCKVALUETYPE_STRING; returnValue.value.stringValue = namedValue.getStringValue(); } else if (strcmp(namedValue.getType().asCharString(), "void*") == 0) { returnValue.type = MOCKVALUETYPE_POINTER; returnValue.value.pointerValue = namedValue.getPointerValue(); } else { returnValue.type = MOCKVALUETYPE_OBJECT; returnValue.value.objectValue = namedValue.getObjectPointer(); } return returnValue; } MockValue_c returnValue_c() { return getMockValueCFromNamedValue(currentCall->returnValue()); } MockFunctionCall_c* expectOneCall_c(const char* name) { currentCall = &currentMockSupport->expectOneCall(name); return &gFunctionCall; } MockFunctionCall_c* actualCall_c(const char* name) { currentCall = &currentMockSupport->actualCall(name); return &gFunctionCall; } void setIntData_c(const char* name, int value) { return currentMockSupport->setData(name, value); } void setDoubleData_c(const char* name, double value) { return currentMockSupport->setData(name, value); } void setStringData_c(const char* name, const char* value) { return currentMockSupport->setData(name, value); } void setPointerData_c(const char* name, void* value) { return currentMockSupport->setData(name, value); } void setDataObject_c(const char* name, const char* type, void* value) { return currentMockSupport->setDataObject(name, type, value); } MockValue_c getData_c(const char* name) { return getMockValueCFromNamedValue(currentMockSupport->getData(name)); } void checkExpectations_c() { currentMockSupport->checkExpectations(); } int expectedCallsLeft_c() { return currentMockSupport->expectedCallsLeft(); } void clear_c() { currentMockSupport->clear(); } MockSupport_c* mock_c() { currentMockSupport = &mock(); return &gMockSupport; } MockSupport_c* mock_scope_c(const char* scope) { currentMockSupport = &mock(scope); return &gMockSupport; } }
null
420
cpp
blalor-cpputest
CodeMemoryReportFormatter.cpp
src/CppUTestExt/CodeMemoryReportFormatter.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 "CppUTestExt/CodeMemoryReportFormatter.h" #include "CppUTestExt/MemoryReportAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" #define MAX_VARIABLE_NAME_LINE_PART 10 #define MAX_VARIABLE_NAME_FILE_PART 53 #define MAX_VARIABLE_NAME_SEPERATOR_PART 1 #define MAX_VARIABLE_NAME_LENGTH MAX_VARIABLE_NAME_FILE_PART + MAX_VARIABLE_NAME_SEPERATOR_PART + MAX_VARIABLE_NAME_LINE_PART struct CodeReportingAllocationNode { char variableName_[MAX_VARIABLE_NAME_LENGTH + 1]; void* memory_; CodeReportingAllocationNode* next_; }; CodeMemoryReportFormatter::CodeMemoryReportFormatter(MemoryLeakAllocator* internalAllocator) : codeReportingList_(NULL), internalAllocator_(internalAllocator) { } CodeMemoryReportFormatter::~CodeMemoryReportFormatter() { clearReporting(); } void CodeMemoryReportFormatter::clearReporting() { while (codeReportingList_) { CodeReportingAllocationNode* oldNode = codeReportingList_; codeReportingList_ = codeReportingList_->next_; internalAllocator_->free_memory((char*) oldNode, __FILE__, __LINE__); } } void CodeMemoryReportFormatter::addNodeToList(const char* variableName, void* memory, CodeReportingAllocationNode* next) { CodeReportingAllocationNode* newNode = (CodeReportingAllocationNode*) internalAllocator_->alloc_memory(sizeof(CodeReportingAllocationNode), __FILE__, __LINE__); newNode->memory_ = memory; newNode->next_ = next; PlatformSpecificStrNCpy(newNode->variableName_, variableName, MAX_VARIABLE_NAME_LENGTH); codeReportingList_ = newNode; } CodeReportingAllocationNode* CodeMemoryReportFormatter::findNode(void* memory) { CodeReportingAllocationNode* current = codeReportingList_; while (current && current->memory_ != memory) { current = current->next_; } return current; } static SimpleString extractFileNameFromPath(const char* file) { const char* fileNameOnly = file + PlatformSpecificStrLen(file); while (fileNameOnly != file && *fileNameOnly != '/') fileNameOnly--; if (*fileNameOnly == '/') fileNameOnly++; return fileNameOnly; } SimpleString CodeMemoryReportFormatter::createVariableNameFromFileLineInfo(const char *file, int line) { SimpleString fileNameOnly = extractFileNameFromPath(file); fileNameOnly.replace(".", "_"); for (int i = 1; i < 100000; i++) { SimpleString variableName = StringFromFormat("%s_%d_%d", fileNameOnly.asCharString(), line, i); if (!variableExists(variableName)) return variableName; } return ""; } bool CodeMemoryReportFormatter::isNewAllocator(MemoryLeakAllocator* allocator) { return PlatformSpecificStrCmp(allocator->alloc_name(), StandardNewAllocator::defaultAllocator()->alloc_name()) == 0 || PlatformSpecificStrCmp(allocator->alloc_name(), StandardNewArrayAllocator::defaultAllocator()->alloc_name()) == 0; } bool CodeMemoryReportFormatter::variableExists(const SimpleString& variableName) { CodeReportingAllocationNode* current = codeReportingList_; while (current) { if (variableName == current->variableName_) return true; current = current->next_; } return false; } SimpleString CodeMemoryReportFormatter::getAllocationString(MemoryLeakAllocator* allocator, const SimpleString& variableName, size_t size) { if (isNewAllocator(allocator)) return StringFromFormat("char* %s = new char[%d]; /* using %s */", variableName.asCharString(), size, allocator->alloc_name()); else return StringFromFormat("void* %s = malloc(%d);", variableName.asCharString(), size); } SimpleString CodeMemoryReportFormatter::getDeallocationString(MemoryLeakAllocator* allocator, const SimpleString& variableName, const char* file, int line) { if (isNewAllocator(allocator)) return StringFromFormat("delete [] %s; /* using %s at %s:%d */", variableName.asCharString(), allocator->free_name(), file, line); else return StringFromFormat("free(%s); /* at %s:%d */", variableName.asCharString(), file, line); } void CodeMemoryReportFormatter::report_test_start(TestResult* result, Utest& test) { clearReporting(); result->print(StringFromFormat("*/\nTEST(%s_memoryReport, %s)\n{ /* at %s:%d */\n", test.getGroup().asCharString(), test.getName().asCharString(), test.getFile().asCharString(), test.getLineNumber()).asCharString()); } void CodeMemoryReportFormatter::report_test_end(TestResult* result, Utest&) { result->print("}/*"); } void CodeMemoryReportFormatter::report_testgroup_start(TestResult* result, Utest& test) { result->print(StringFromFormat("*/TEST_GROUP(%s_memoryReport)\n{\n};\n/*", test.getGroup().asCharString()).asCharString()); } void CodeMemoryReportFormatter::report_alloc_memory(TestResult* result, MemoryLeakAllocator* allocator, size_t size, char* memory, const char* file, int line) { SimpleString variableName = createVariableNameFromFileLineInfo(file, line); result->print(StringFromFormat("\t%s\n", getAllocationString(allocator, variableName, size).asCharString()).asCharString()); addNodeToList(variableName.asCharString(), memory, codeReportingList_); } void CodeMemoryReportFormatter::report_free_memory(TestResult* result, MemoryLeakAllocator* allocator, char* memory, const char* file, int line) { SimpleString variableName; CodeReportingAllocationNode* node = findNode(memory); if (memory == NULL) variableName = "NULL"; else variableName = node->variableName_; result->print(StringFromFormat("\t%s\n", getDeallocationString(allocator, variableName, file, line).asCharString()).asCharString()); }
null
421
cpp
blalor-cpputest
MockSupportPlugin.cpp
src/CppUTestExt/MockSupportPlugin.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 "CppUTestExt/MockSupport.h" #include "CppUTestExt/MockSupportPlugin.h" class MockSupportPluginReporter : public MockFailureReporter { Utest& test_; TestResult& result_; public: MockSupportPluginReporter(Utest& test, TestResult& result) : test_(test), result_(result) { } virtual void failTest(const MockFailure& failure) { result_.addFailure(failure); } virtual Utest* getTestToFail() { return &test_; } }; MockSupportPlugin::MockSupportPlugin(const SimpleString& name) : TestPlugin(name) { } MockSupportPlugin::~MockSupportPlugin() { repository_.clear(); } void MockSupportPlugin::preTestAction(Utest&, TestResult&) { mock().installComparators(repository_); } void MockSupportPlugin::postTestAction(Utest& test, TestResult& result) { MockSupportPluginReporter reporter(test, result); mock().setMockFailureReporter(&reporter); mock().checkExpectations(); mock().clear(); mock().setMockFailureReporter(NULL); mock().removeAllComparators(); } void MockSupportPlugin::installComparator(const SimpleString& name, MockNamedValueComparator& comparator) { repository_.installComparator(name, comparator); }
null
422
cpp
blalor-cpputest
MockFunctionCall.cpp
src/CppUTestExt/MockFunctionCall.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 "CppUTestExt/MockFunctionCall.h" #include "CppUTestExt/MockNamedValue.h" MockFunctionCall::MockFunctionCall() : comparatorRepository_(NULL) { } MockFunctionCall::~MockFunctionCall() { } void MockFunctionCall::setComparatorRepository(MockNamedValueComparatorRepository* repository) { comparatorRepository_ = repository; } void MockFunctionCall::setName(const SimpleString& name) { functionName_ = name; } SimpleString MockFunctionCall::getName() const { return functionName_; } MockNamedValueComparator* MockFunctionCall::getComparatorForType(const SimpleString& type) const { if (comparatorRepository_) return comparatorRepository_->getComparatorForType(type); return NULL; } struct MockFunctionCallCompositeNode { MockFunctionCallCompositeNode(MockFunctionCall& functionCall, MockFunctionCallCompositeNode* next) : next_(next), call_(functionCall){} MockFunctionCallCompositeNode* next_; MockFunctionCall& call_; }; MockFunctionCallComposite::MockFunctionCallComposite() : head_(NULL) { } MockFunctionCallComposite::~MockFunctionCallComposite() { } void MockFunctionCallComposite::add(MockFunctionCall& call) { head_ = new MockFunctionCallCompositeNode(call, head_); } void MockFunctionCallComposite::clear() { while (head_) { MockFunctionCallCompositeNode* next = head_->next_; delete head_; head_ = next; } } MockFunctionCall& MockFunctionCallComposite::withName(const SimpleString& name) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withName(name); return *this; } MockFunctionCall& MockFunctionCallComposite::withCallOrder(int) { FAIL("withCallOrder not supported for CompositeCalls"); return *this; } MockFunctionCall& MockFunctionCallComposite::withParameter(const SimpleString& name, int value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withParameter(name, value); return *this; } MockFunctionCall& MockFunctionCallComposite::withParameter(const SimpleString& name, double value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withParameter(name, value); return *this; } MockFunctionCall& MockFunctionCallComposite::withParameter(const SimpleString& name, const char* value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withParameter(name, value); return *this; } MockFunctionCall& MockFunctionCallComposite::withParameter(const SimpleString& name, void* value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withParameter(name, value); return *this; } MockFunctionCall& MockFunctionCallComposite::withParameterOfType(const SimpleString& typeName, const SimpleString& name, void* value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withParameterOfType(typeName, name, value); return *this; } MockFunctionCall& MockFunctionCallComposite::ignoreOtherParameters() { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.ignoreOtherParameters(); return *this; } MockFunctionCall& MockFunctionCallComposite::andReturnValue(int value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.andReturnValue(value); return *this; } MockFunctionCall& MockFunctionCallComposite::MockFunctionCallComposite::andReturnValue(double value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.andReturnValue(value); return *this; } MockFunctionCall& MockFunctionCallComposite::andReturnValue(const char* value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.andReturnValue(value); return *this; } MockFunctionCall& MockFunctionCallComposite::andReturnValue(void* value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.andReturnValue(value); return *this; } bool MockFunctionCallComposite::hasReturnValue() { return head_->call_.hasReturnValue(); } MockNamedValue MockFunctionCallComposite::returnValue() { return head_->call_.returnValue(); } MockFunctionCall& MockFunctionCallComposite::onObject(void* object) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.onObject(object); return *this; } MockFunctionCallTrace::MockFunctionCallTrace() { } MockFunctionCallTrace::~MockFunctionCallTrace() { } MockFunctionCall& MockFunctionCallTrace::withName(const SimpleString& name) { traceBuffer_ += "\nFunction name: "; traceBuffer_ += name; return *this; } MockFunctionCall& MockFunctionCallTrace::withCallOrder(int callOrder) { traceBuffer_ += "\nwithCallOrder: "; traceBuffer_ += StringFrom(callOrder); return *this; } MockFunctionCall& MockFunctionCallTrace::withParameter(const SimpleString& name, int value) { traceBuffer_ += " "; traceBuffer_ += name; traceBuffer_ += ":"; traceBuffer_ += StringFrom(value); return *this; } MockFunctionCall& MockFunctionCallTrace::withParameter(const SimpleString& name, double value) { traceBuffer_ += " "; traceBuffer_ += name; traceBuffer_ += ":"; traceBuffer_ += StringFrom(value); return *this; } MockFunctionCall& MockFunctionCallTrace::withParameter(const SimpleString& name, const char* value) { traceBuffer_ += " "; traceBuffer_ += name; traceBuffer_ += ":"; traceBuffer_ += StringFrom(value); return *this; } MockFunctionCall& MockFunctionCallTrace::withParameter(const SimpleString& name, void* value) { traceBuffer_ += " "; traceBuffer_ += name; traceBuffer_ += ":"; traceBuffer_ += StringFrom(value); return *this; } MockFunctionCall& MockFunctionCallTrace::withParameterOfType(const SimpleString& typeName, const SimpleString& name, void* value) { traceBuffer_ += " "; traceBuffer_ += typeName; traceBuffer_ += " "; traceBuffer_ += name; traceBuffer_ += ":"; traceBuffer_ += StringFrom(value); return *this; } MockFunctionCall& MockFunctionCallTrace::ignoreOtherParameters() { return *this; } MockFunctionCall& MockFunctionCallTrace::andReturnValue(int) { return *this; } MockFunctionCall& MockFunctionCallTrace::andReturnValue(double) { return *this; } MockFunctionCall& MockFunctionCallTrace::andReturnValue(const char*) { return *this; } MockFunctionCall& MockFunctionCallTrace::andReturnValue(void*) { return *this; } bool MockFunctionCallTrace::hasReturnValue() { return false; } MockNamedValue MockFunctionCallTrace::returnValue() { return MockNamedValue(""); } MockFunctionCall& MockFunctionCallTrace::onObject(void* objectPtr) { traceBuffer_ += StringFrom(objectPtr); return *this; } void MockFunctionCallTrace::clear() { traceBuffer_ = ""; } const char* MockFunctionCallTrace::getTraceOutput() { return traceBuffer_.asCharString(); } MockFunctionCallTrace& MockFunctionCallTrace::instance() { static MockFunctionCallTrace call; return call; }
null
423
cpp
blalor-cpputest
MockExpectedFunctionsList.cpp
src/CppUTestExt/MockExpectedFunctionsList.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 "CppUTestExt/MockExpectedFunctionsList.h" #include "CppUTestExt/MockExpectedFunctionCall.h" MockExpectedFunctionsList::MockExpectedFunctionsList() : head_(NULL) { } MockExpectedFunctionsList::~MockExpectedFunctionsList() { while (head_) { MockExpectedFunctionsListNode* next = head_->next_; delete head_; head_ = next; } } bool MockExpectedFunctionsList::hasCallsOutOfOrder() const { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (p->expectedCall_->isOutOfOrder()) return true; return false; } int MockExpectedFunctionsList::size() const { int count = 0; for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) count++; return count; } bool MockExpectedFunctionsList::isEmpty() const { return size() == 0; } int MockExpectedFunctionsList::amountOfExpectationsFor(const SimpleString& name) const { int count = 0; for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (p->expectedCall_->relatesTo(name)) count++; return count; } int MockExpectedFunctionsList::amountOfUnfulfilledExpectations() const { int count = 0; for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->isFulfilled()) count++; return count; } bool MockExpectedFunctionsList::hasFulfilledExpectations() const { return (size() - amountOfUnfulfilledExpectations()) != 0; } bool MockExpectedFunctionsList::hasUnfullfilledExpectations() const { return amountOfUnfulfilledExpectations() != 0; } bool MockExpectedFunctionsList::hasExpectationWithName(const SimpleString& name) const { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (p->expectedCall_->relatesTo(name)) return true; return false; } void MockExpectedFunctionsList::addExpectedCall(MockExpectedFunctionCall* call) { MockExpectedFunctionsListNode* newCall = new MockExpectedFunctionsListNode(call); if (head_ == NULL) head_ = newCall; else { MockExpectedFunctionsListNode* lastCall = head_; while (lastCall->next_) lastCall = lastCall->next_; lastCall->next_ = newCall; } } void MockExpectedFunctionsList::addUnfilfilledExpectations(const MockExpectedFunctionsList& list) { for (MockExpectedFunctionsListNode* p = list.head_; p; p = p->next_) if (! p->expectedCall_->isFulfilled()) addExpectedCall(p->expectedCall_); } void MockExpectedFunctionsList::addExpectationsRelatedTo(const SimpleString& name, const MockExpectedFunctionsList& list) { for (MockExpectedFunctionsListNode* p = list.head_; p; p = p->next_) if (p->expectedCall_->relatesTo(name)) addExpectedCall(p->expectedCall_); } void MockExpectedFunctionsList::addExpectations(const MockExpectedFunctionsList& list) { for (MockExpectedFunctionsListNode* p = list.head_; p; p = p->next_) addExpectedCall(p->expectedCall_); } void MockExpectedFunctionsList::onlyKeepExpectationsRelatedTo(const SimpleString& name) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->relatesTo(name)) p->expectedCall_ = NULL; pruneEmptyNodeFromList(); } void MockExpectedFunctionsList::onlyKeepUnfulfilledExpectations() { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (p->expectedCall_->isFulfilled()) p->expectedCall_ = NULL; pruneEmptyNodeFromList(); } void MockExpectedFunctionsList::onlyKeepUnfulfilledExpectationsRelatedTo(const SimpleString& name) { onlyKeepUnfulfilledExpectations(); onlyKeepExpectationsRelatedTo(name); } void MockExpectedFunctionsList::onlyKeepExpectationsWithParameterName(const SimpleString& name) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->hasParameterWithName(name)) p->expectedCall_ = NULL; pruneEmptyNodeFromList(); } void MockExpectedFunctionsList::onlyKeepExpectationsWithParameter(const MockNamedValue& parameter) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->hasParameter(parameter)) p->expectedCall_ = NULL; pruneEmptyNodeFromList(); } void MockExpectedFunctionsList::onlyKeepExpectationsOnObject(void* objectPtr) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->relatesToObject(objectPtr)) p->expectedCall_ = NULL; pruneEmptyNodeFromList(); } void MockExpectedFunctionsList::onlyKeepUnfulfilledExpectationsWithParameter(const MockNamedValue& parameter) { onlyKeepUnfulfilledExpectations(); onlyKeepExpectationsWithParameter(parameter); } void MockExpectedFunctionsList::onlyKeepUnfulfilledExpectationsOnObject(void* objectPtr) { onlyKeepUnfulfilledExpectations(); onlyKeepExpectationsOnObject(objectPtr); } MockExpectedFunctionCall* MockExpectedFunctionsList::removeOneFulfilledExpectation() { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) { if (p->expectedCall_->isFulfilled()) { MockExpectedFunctionCall* fulfilledCall = p->expectedCall_; p->expectedCall_ = NULL; pruneEmptyNodeFromList(); return fulfilledCall; } } return NULL; } MockExpectedFunctionCall* MockExpectedFunctionsList::removeOneFulfilledExpectationWithIgnoredParameters() { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) { if (p->expectedCall_->isFulfilledWithoutIgnoredParameters()) { MockExpectedFunctionCall* fulfilledCall = p->expectedCall_; p->expectedCall_->parametersWereIgnored(); p->expectedCall_ = NULL; pruneEmptyNodeFromList(); return fulfilledCall; } } return NULL; } void MockExpectedFunctionsList::pruneEmptyNodeFromList() { MockExpectedFunctionsListNode* current = head_; MockExpectedFunctionsListNode* previous = NULL; MockExpectedFunctionsListNode* toBeDeleted = NULL; while (current) { if (current->expectedCall_ == NULL) { toBeDeleted = current; if (previous == NULL) head_ = current = current->next_; else current = previous->next_ = current->next_; delete toBeDeleted; } else { previous = current; current = current->next_; } } } void MockExpectedFunctionsList::deleteAllExpectationsAndClearList() { while (head_) { MockExpectedFunctionsListNode* next = head_->next_; delete head_->expectedCall_; delete head_; head_ = next; } } void MockExpectedFunctionsList::resetExpectations() { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) p->expectedCall_->resetExpectation(); } void MockExpectedFunctionsList::callWasMade(int callOrder) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) p->expectedCall_->callWasMade(callOrder); } void MockExpectedFunctionsList::wasPassedToObject() { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) p->expectedCall_->wasPassedToObject(); } void MockExpectedFunctionsList::parameterWasPassed(const SimpleString& parameterName) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) p->expectedCall_->parameterWasPassed(parameterName); } MockExpectedFunctionsList::MockExpectedFunctionsListNode* MockExpectedFunctionsList::findNodeWithCallOrderOf(int callOrder) const { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (p->expectedCall_->getCallOrder() == callOrder && p->expectedCall_->isFulfilled()) return p; return NULL; } SimpleString stringOrNoneTextWhenEmpty(const SimpleString& inputString, const SimpleString& linePrefix) { SimpleString str = inputString; if (str == "") { str += linePrefix; str += "<none>"; } return str; } SimpleString appendStringOnANewLine(const SimpleString& inputString, const SimpleString& linePrefix, const SimpleString& stringToAppend) { SimpleString str = inputString; if (str != "") str += "\n"; str += linePrefix; str += stringToAppend; return str; } SimpleString MockExpectedFunctionsList::unfulfilledFunctionsToString(const SimpleString& linePrefix) const { SimpleString str; for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (!p->expectedCall_->isFulfilled()) str = appendStringOnANewLine(str, linePrefix, p->expectedCall_->callToString()); return stringOrNoneTextWhenEmpty(str, linePrefix); } SimpleString MockExpectedFunctionsList::fulfilledFunctionsToString(const SimpleString& linePrefix) const { SimpleString str; MockExpectedFunctionsListNode* nextNodeInOrder = head_; for (int callOrder = 1; (nextNodeInOrder = findNodeWithCallOrderOf(callOrder)); callOrder++) if (nextNodeInOrder) str = appendStringOnANewLine(str, linePrefix, nextNodeInOrder->expectedCall_->callToString()); return stringOrNoneTextWhenEmpty(str, linePrefix); } SimpleString MockExpectedFunctionsList::missingParametersToString() const { SimpleString str; for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->isFulfilled()) str = appendStringOnANewLine(str, "", p->expectedCall_->missingParametersToString()); return stringOrNoneTextWhenEmpty(str, ""); } bool MockExpectedFunctionsList::hasUnfulfilledExpectationsBecauseOfMissingParameters() const { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->areParametersFulfilled()) return true; return false; }
null
424
cpp
blalor-cpputest
MockExpectedFunctionCall.cpp
src/CppUTestExt/MockExpectedFunctionCall.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 "CppUTestExt/MockExpectedFunctionCall.h" SimpleString StringFrom(const MockNamedValue& parameter) { return parameter.toString(); } MockExpectedFunctionCall::MockExpectedFunctionCall() : ignoreOtherParameters_(false), parametersWereIgnored_(false), callOrder_(0), expectedCallOrder_(NO_EXPECTED_CALL_ORDER), outOfOrder_(true), returnValue_(""), objectPtr_(NULL), wasPassedToObject_(true) { parameters_ = new MockNamedValueList(); } MockExpectedFunctionCall::~MockExpectedFunctionCall() { parameters_->clear(); delete parameters_; } MockFunctionCall& MockExpectedFunctionCall::withName(const SimpleString& name) { setName(name); callOrder_ = NOT_CALLED_YET; return *this; } MockFunctionCall& MockExpectedFunctionCall::withParameter(const SimpleString& name, int value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withParameter(const SimpleString& name, double value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withParameter(const SimpleString& name, const char* value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withParameter(const SimpleString& name, void* value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withParameterOfType(const SimpleString& type, const SimpleString& name, void* value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setObjectPointer(type, value); newParameter->setComparator(getComparatorForType(type)); return *this; } SimpleString MockExpectedFunctionCall::getParameterType(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return (p) ? p->getType() : ""; } bool MockExpectedFunctionCall::hasParameterWithName(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return p != NULL; } MockNamedValue MockExpectedFunctionCall::getParameter(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return (p) ? *p : MockNamedValue(""); } bool MockExpectedFunctionCall::areParametersFulfilled() { for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) if (! item(p)->isFulfilled()) return false; return true; } bool MockExpectedFunctionCall::areIgnoredParametersFulfilled() { if (ignoreOtherParameters_) return parametersWereIgnored_; return true; } MockFunctionCall& MockExpectedFunctionCall::ignoreOtherParameters() { ignoreOtherParameters_ = true; return *this; } bool MockExpectedFunctionCall::isFulfilled() { return isFulfilledWithoutIgnoredParameters() && areIgnoredParametersFulfilled(); } bool MockExpectedFunctionCall::isFulfilledWithoutIgnoredParameters() { return callOrder_ != NOT_CALLED_YET && areParametersFulfilled() && wasPassedToObject_; } void MockExpectedFunctionCall::callWasMade(int callOrder) { callOrder_ = callOrder; if (expectedCallOrder_ == NO_EXPECTED_CALL_ORDER) outOfOrder_ = false; else if (callOrder_ == expectedCallOrder_) outOfOrder_ = false; else outOfOrder_ = true; } void MockExpectedFunctionCall::parametersWereIgnored() { parametersWereIgnored_ = true; } void MockExpectedFunctionCall::wasPassedToObject() { wasPassedToObject_ = true; } void MockExpectedFunctionCall::resetExpectation() { callOrder_ = NOT_CALLED_YET; wasPassedToObject_ = (objectPtr_ == NULL); for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) item(p)->setFulfilled(false); } void MockExpectedFunctionCall::parameterWasPassed(const SimpleString& name) { for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) { if (p->getName() == name) item(p)->setFulfilled(true); } } SimpleString MockExpectedFunctionCall::getParameterValueString(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return (p) ? StringFrom(*p) : "failed"; } bool MockExpectedFunctionCall::hasParameter(const MockNamedValue& parameter) { MockNamedValue * p = parameters_->getValueByName(parameter.getName()); return (p) ? p->equals(parameter) : ignoreOtherParameters_; } SimpleString MockExpectedFunctionCall::callToString() { SimpleString str; if (objectPtr_) str = StringFromFormat("(object address: %p)::", objectPtr_); str += getName(); str += " -> "; if (expectedCallOrder_ != NO_EXPECTED_CALL_ORDER) { str += StringFromFormat("expected call order: <%d> -> ", expectedCallOrder_); } if (parameters_->begin() == NULL) { str += (ignoreOtherParameters_) ? "all parameters ignored" : "no parameters"; return str; } for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) { str += StringFromFormat("%s %s: <%s>", p->getType().asCharString(), p->getName().asCharString(), getParameterValueString(p->getName()).asCharString()); if (p->next()) str += ", "; } if (ignoreOtherParameters_) str += ", other parameters are ignored"; return str; } SimpleString MockExpectedFunctionCall::missingParametersToString() { SimpleString str; for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) { if (! item(p)->isFulfilled()) { if (str != "") str += ", "; str += StringFromFormat("%s %s", p->getType().asCharString(), p->getName().asCharString()); } } return str; } bool MockExpectedFunctionCall::relatesTo(const SimpleString& functionName) { return functionName == getName(); } bool MockExpectedFunctionCall::relatesToObject(void*objectPtr) const { return objectPtr_ == objectPtr; } MockExpectedFunctionCall::MockExpectedFunctionParameter* MockExpectedFunctionCall::item(MockNamedValueListNode* node) { return (MockExpectedFunctionParameter*) node->item(); } MockExpectedFunctionCall::MockExpectedFunctionParameter::MockExpectedFunctionParameter(const SimpleString& name) : MockNamedValue(name), fulfilled_(false) { } void MockExpectedFunctionCall::MockExpectedFunctionParameter::setFulfilled(bool b) { fulfilled_ = b; } bool MockExpectedFunctionCall::MockExpectedFunctionParameter::isFulfilled() const { return fulfilled_; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(int value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(const char* value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(double value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(void* value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::onObject(void* objectPtr) { wasPassedToObject_ = false; objectPtr_ = objectPtr; return *this; } bool MockExpectedFunctionCall::hasReturnValue() { return ! returnValue_.getName().isEmpty(); } MockNamedValue MockExpectedFunctionCall::returnValue() { return returnValue_; } int MockExpectedFunctionCall::getCallOrder() const { return callOrder_; } MockFunctionCall& MockExpectedFunctionCall::withCallOrder(int callOrder) { expectedCallOrder_ = callOrder; return *this; } bool MockExpectedFunctionCall::isOutOfOrder() const { return outOfOrder_; }
null
425
cpp
blalor-cpputest
MockActualFunctionCall.cpp
src/CppUTestExt/MockActualFunctionCall.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 "CppUTestExt/MockActualFunctionCall.h" #include "CppUTestExt/MockExpectedFunctionsList.h" #include "CppUTestExt/MockExpectedFunctionCall.h" #include "CppUTestExt/MockFailure.h" MockActualFunctionCall::MockActualFunctionCall(int callOrder, MockFailureReporter* reporter, const MockExpectedFunctionsList& allExpectations) : callOrder_(callOrder), reporter_(reporter), state_(CALL_SUCCEED), _fulfilledExpectation(NULL), allExpectations_(allExpectations) { unfulfilledExpectations_.addUnfilfilledExpectations(allExpectations); } MockActualFunctionCall::~MockActualFunctionCall() { } void MockActualFunctionCall::setMockFailureReporter(MockFailureReporter* reporter) { reporter_ = reporter; } Utest* MockActualFunctionCall::getTest() const { return reporter_->getTestToFail(); } void MockActualFunctionCall::failTest(const MockFailure& failure) { setState(CALL_FAILED); reporter_->failTest(failure); } void MockActualFunctionCall::finnalizeCallWhenFulfilled() { if (unfulfilledExpectations_.hasFulfilledExpectations()) { _fulfilledExpectation = unfulfilledExpectations_.removeOneFulfilledExpectation(); callHasSucceeded(); } } void MockActualFunctionCall::callHasSucceeded() { setState(CALL_SUCCEED); unfulfilledExpectations_.resetExpectations(); } MockFunctionCall& MockActualFunctionCall::withName(const SimpleString& name) { setName(name); setState(CALL_IN_PROGESS); unfulfilledExpectations_.onlyKeepUnfulfilledExpectationsRelatedTo(name); if (unfulfilledExpectations_.isEmpty()) { MockUnexpectedCallHappenedFailure failure(getTest(), name, allExpectations_); failTest(failure); return *this; } unfulfilledExpectations_.callWasMade(callOrder_); finnalizeCallWhenFulfilled(); return *this; } MockFunctionCall& MockActualFunctionCall::withCallOrder(int) { return *this; } void MockActualFunctionCall::checkActualParameter(const MockNamedValue& actualParameter) { unfulfilledExpectations_.onlyKeepUnfulfilledExpectationsWithParameter(actualParameter); if (unfulfilledExpectations_.isEmpty()) { MockUnexpectedParameterFailure failure(getTest(), getName(), actualParameter, allExpectations_); failTest(failure); return; } unfulfilledExpectations_.parameterWasPassed(actualParameter.getName()); finnalizeCallWhenFulfilled(); } MockFunctionCall& MockActualFunctionCall::withParameter(const SimpleString& name, int value) { MockNamedValue actualParameter(name); actualParameter.setValue(value); checkActualParameter(actualParameter); return *this; } MockFunctionCall& MockActualFunctionCall::withParameter(const SimpleString& name, double value) { MockNamedValue actualParameter(name); actualParameter.setValue(value); checkActualParameter(actualParameter); return *this; } MockFunctionCall& MockActualFunctionCall::withParameter(const SimpleString& name, const char* value) { MockNamedValue actualParameter(name); actualParameter.setValue(value); checkActualParameter(actualParameter); return *this; } MockFunctionCall& MockActualFunctionCall::withParameter(const SimpleString& name, void* value) { MockNamedValue actualParameter(name); actualParameter.setValue(value); checkActualParameter(actualParameter); return *this; } MockFunctionCall& MockActualFunctionCall::withParameterOfType(const SimpleString& type, const SimpleString& name, void* value) { if (getComparatorForType(type) == NULL) { MockNoWayToCompareCustomTypeFailure failure(getTest(), type); failTest(failure); return *this; } MockNamedValue actualParameter(name); actualParameter.setObjectPointer(type, value); actualParameter.setComparator(getComparatorForType(type)); checkActualParameter(actualParameter); return *this; } bool MockActualFunctionCall::isFulfilled() const { return state_ == CALL_SUCCEED; } bool MockActualFunctionCall::hasFailed() const { return state_ == CALL_FAILED; } void MockActualFunctionCall::checkExpectations() { if (state_ != CALL_IN_PROGESS) return; if (! unfulfilledExpectations_.hasUnfullfilledExpectations()) FAIL("Actual call is in progress. Checking expectations. But no unfulfilled expectations. Cannot happen.") _fulfilledExpectation = unfulfilledExpectations_.removeOneFulfilledExpectationWithIgnoredParameters(); if (_fulfilledExpectation) { callHasSucceeded(); return; } if (unfulfilledExpectations_.hasUnfulfilledExpectationsBecauseOfMissingParameters()) { MockExpectedParameterDidntHappenFailure failure(getTest(), getName(), allExpectations_); failTest(failure); } else { MockExpectedObjectDidntHappenFailure failure(getTest(), getName(), allExpectations_); failTest(failure); } } const char* MockActualFunctionCall::stringFromState(ActualCallState state) { switch (state) { case CALL_IN_PROGESS: return "In progress"; case CALL_FAILED: return "Failed"; case CALL_SUCCEED: return "Succeed"; default: ; } return "No valid state info"; } void MockActualFunctionCall::checkStateConsistency(ActualCallState oldState, ActualCallState newState) { if (oldState == newState) FAIL(StringFromFormat("State change to the same state: %s.", stringFromState(newState)).asCharString()); if (oldState == CALL_FAILED) FAIL("State was already failed. Cannot change state again."); } void MockActualFunctionCall::setState(ActualCallState state) { checkStateConsistency(state_, state); state_ = state; } MockFunctionCall& MockActualFunctionCall::andReturnValue(int) { FAIL("andReturnValue cannot be called on an ActualFunctionCall. Use returnValue instead to get the value."); return *this; } MockFunctionCall& MockActualFunctionCall::andReturnValue(const char*) { FAIL("andReturnValue cannot be called on an ActualFunctionCall. Use returnValue instead to get the value."); return *this; } MockFunctionCall& MockActualFunctionCall::andReturnValue(double) { FAIL("andReturnValue cannot be called on an ActualFunctionCall. Use returnValue instead to get the value."); return *this; } MockFunctionCall& MockActualFunctionCall::andReturnValue(void*) { FAIL("andReturnValue cannot be called on an ActualFunctionCall. Use returnValue instead to get the value."); return *this; } MockNamedValue MockActualFunctionCall::returnValue() { checkExpectations(); if (_fulfilledExpectation) return _fulfilledExpectation->returnValue(); return MockNamedValue("no return value"); } bool MockActualFunctionCall::hasReturnValue() { return ! returnValue().getName().isEmpty(); } MockFunctionCall& MockActualFunctionCall::onObject(void* objectPtr) { unfulfilledExpectations_.onlyKeepUnfulfilledExpectationsOnObject(objectPtr); if (unfulfilledExpectations_.isEmpty()) { MockUnexpectedObjectFailure failure(getTest(), getName(), objectPtr, allExpectations_); failTest(failure); return *this; } unfulfilledExpectations_.wasPassedToObject(); finnalizeCallWhenFulfilled(); return *this; }
null
426
cpp
blalor-cpputest
MemoryReportFormatter.cpp
src/CppUTestExt/MemoryReportFormatter.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 "CppUTestExt/MemoryReportAllocator.h" #include "CppUTestExt/MemoryReportFormatter.h" NormalMemoryReportFormatter::NormalMemoryReportFormatter() { } NormalMemoryReportFormatter::~NormalMemoryReportFormatter() { } void NormalMemoryReportFormatter::report_test_start(TestResult* result, Utest& test) { result->print(StringFromFormat("TEST(%s, %s)\n", test.getGroup().asCharString(), test.getName().asCharString()).asCharString()); } void NormalMemoryReportFormatter::report_test_end(TestResult* result, Utest& test) { result->print(StringFromFormat("ENDTEST(%s, %s)\n", test.getGroup().asCharString(), test.getName().asCharString()).asCharString()); } void NormalMemoryReportFormatter::report_alloc_memory(TestResult* result, MemoryLeakAllocator* allocator, size_t size, char* memory, const char* file, int line) { result->print(StringFromFormat("\tAllocation using %s of size: %d pointer: %p at %s:%d\n", allocator->alloc_name(), size, memory, file, line).asCharString()); } void NormalMemoryReportFormatter::report_free_memory(TestResult* result, MemoryLeakAllocator* allocator, char* memory, const char* file, int line) { result->print(StringFromFormat("\tDeallocation using %s of pointer: %p at %s:%d\n", allocator->free_name(), memory, file, line).asCharString()); } void NormalMemoryReportFormatter::report_testgroup_start(TestResult* result, Utest& test) { const size_t line_size = 80; SimpleString groupName = StringFromFormat("TEST GROUP(%s)", test.getGroup().asCharString()); size_t beginPos = (line_size/2) - (groupName.size()/2); SimpleString line("-", beginPos); line += groupName; line += SimpleString("-", line_size - line.size()); line += "\n"; result->print(line.asCharString()); }
null
427
cpp
blalor-cpputest
MockNamedValue.cpp
src/CppUTestExt/MockNamedValue.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 "CppUTestExt/MockNamedValue.h" #include "CppUTest/PlatformSpecificFunctions.h" MockNamedValue::MockNamedValue(const SimpleString& name) : name_(name), type_("int"), comparator_(NULL) { value_.intValue_ = 0; } MockNamedValue::~MockNamedValue() { } void MockNamedValue::setValue(int value) { type_ = "int"; value_.intValue_ = value; } void MockNamedValue::setValue(double value) { type_ = "double"; value_.doubleValue_ = value; } void MockNamedValue::setValue(void* value) { type_ = "void*"; value_.pointerValue_ = value; } void MockNamedValue::setValue(const char* value) { type_ = "char*"; value_.stringValue_ = value; } void MockNamedValue::setObjectPointer(const SimpleString& type, void* objectPtr) { type_ = type; value_.objectPointerValue_ = objectPtr; } void MockNamedValue::setName(const char* name) { name_ = name; } SimpleString MockNamedValue::getName() const { return name_; } SimpleString MockNamedValue::getType() const { return type_; } int MockNamedValue::getIntValue() const { STRCMP_EQUAL("int", type_.asCharString()); return value_.intValue_; } double MockNamedValue::getDoubleValue() const { STRCMP_EQUAL("double", type_.asCharString()); return value_.doubleValue_; } const char* MockNamedValue::getStringValue() const { STRCMP_EQUAL("char*", type_.asCharString()); return value_.stringValue_; } void* MockNamedValue::getPointerValue() const { STRCMP_EQUAL("void*", type_.asCharString()); return value_.pointerValue_; } void* MockNamedValue::getObjectPointer() const { return value_.objectPointerValue_; } void MockNamedValue::setComparator(MockNamedValueComparator* comparator) { comparator_ = comparator; } bool MockNamedValue::equals(const MockNamedValue& p) const { if (type_ != p.type_) return false; if (type_ == "int") return value_.intValue_ == p.value_.intValue_; else if (type_ == "char*") return SimpleString(value_.stringValue_) == SimpleString(p.value_.stringValue_); else if (type_ == "void*") return value_.pointerValue_ == p.value_.pointerValue_; else if (type_ == "double") return (doubles_equal(value_.doubleValue_, p.value_.doubleValue_, 0.005)); if (comparator_) return comparator_->isEqual(value_.objectPointerValue_, p.value_.objectPointerValue_); return false; } SimpleString MockNamedValue::toString() const { if (type_ == "int") return StringFrom(value_.intValue_); else if (type_ == "char*") return value_.stringValue_; else if (type_ == "void*") return StringFrom(value_.pointerValue_); else if (type_ == "double") return StringFrom(value_.doubleValue_); if (comparator_) return comparator_->valueToString(value_.objectPointerValue_); return StringFromFormat("No comparator found for type: \"%s\"", type_.asCharString()); } void MockNamedValueListNode::setNext(MockNamedValueListNode* node) { next_ = node; } MockNamedValueListNode* MockNamedValueListNode::next() { return next_; } MockNamedValue* MockNamedValueListNode::item() { return data_; } void MockNamedValueListNode::destroy() { delete data_; } MockNamedValueListNode::MockNamedValueListNode(MockNamedValue* newValue) : data_(newValue), next_(NULL) { } SimpleString MockNamedValueListNode::getName() const { return data_->getName(); } SimpleString MockNamedValueListNode::getType() const { return data_->getType(); } MockNamedValueList::MockNamedValueList() : head_(NULL) { } void MockNamedValueList::clear() { while (head_) { MockNamedValueListNode* n = head_->next(); head_->destroy(); delete head_; head_ = n; } } void MockNamedValueList::add(MockNamedValue* newValue) { MockNamedValueListNode* newNode = new MockNamedValueListNode(newValue); if (head_ == NULL) head_ = newNode; else { MockNamedValueListNode* lastNode = head_; while (lastNode->next()) lastNode = lastNode->next(); lastNode->setNext(newNode); } } MockNamedValue* MockNamedValueList::getValueByName(const SimpleString& name) { for (MockNamedValueListNode * p = head_; p; p = p->next()) if (p->getName() == name) return p->item(); return NULL; } MockNamedValueListNode* MockNamedValueList::begin() { return head_; } struct MockNamedValueComparatorRepositoryNode { MockNamedValueComparatorRepositoryNode(const SimpleString& name, MockNamedValueComparator& comparator, MockNamedValueComparatorRepositoryNode* next) : name_(name), comparator_(comparator), next_(next) {}; SimpleString name_; MockNamedValueComparator& comparator_; MockNamedValueComparatorRepositoryNode* next_; }; MockNamedValueComparatorRepository::MockNamedValueComparatorRepository() : head_(NULL) { } MockNamedValueComparatorRepository::~MockNamedValueComparatorRepository() { clear(); } void MockNamedValueComparatorRepository::clear() { while (head_) { MockNamedValueComparatorRepositoryNode* next = head_->next_; delete head_; head_ = next; } } void MockNamedValueComparatorRepository::installComparator(const SimpleString& name, MockNamedValueComparator& comparator) { head_ = new MockNamedValueComparatorRepositoryNode(name, comparator, head_); } MockNamedValueComparator* MockNamedValueComparatorRepository::getComparatorForType(const SimpleString& name) { for (MockNamedValueComparatorRepositoryNode* p = head_; p; p = p->next_) if (p->name_ == name) return &p->comparator_; return NULL;; } void MockNamedValueComparatorRepository::installComparators(const MockNamedValueComparatorRepository& repository) { for (MockNamedValueComparatorRepositoryNode* p = repository.head_; p; p = p->next_) installComparator(p->name_, p->comparator_); }
null
428
cpp
blalor-cpputest
SymbianMemoryLeakWarning.cpp
src/Platforms/Symbian/SymbianMemoryLeakWarning.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde and Timo Puronen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <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 "MemoryLeakWarning.h" #include <e32base.h> MemoryLeakWarning* MemoryLeakWarning::_latest = NULL; // naming convention due to CppUTest generic class name class MemoryLeakWarningData : public CBase { public: TInt iInitialAllocCells; TInt iExpectedLeaks; TInt iInitialThreadHandleCount; TInt iInitialProcessHandleCount; }; MemoryLeakWarning::MemoryLeakWarning() { _latest = this; CreateData(); } MemoryLeakWarning::~MemoryLeakWarning() { DestroyData(); } void MemoryLeakWarning::Enable() { } const char* MemoryLeakWarning::FinalReport(int toBeDeletedLeaks) { TInt cellDifference(User::CountAllocCells() - _impl->iInitialAllocCells); if( cellDifference != toBeDeletedLeaks ) { return "Heap imbalance after test\n"; } TInt processHandles; TInt threadHandles; RThread().HandleCount(processHandles, threadHandles); if(_impl->iInitialProcessHandleCount != processHandles || _impl->iInitialThreadHandleCount != threadHandles) { return "Handle count imbalance after test\n"; } return ""; } void MemoryLeakWarning::CheckPointUsage() { _impl->iInitialAllocCells = User::CountAllocCells(); RThread().HandleCount(_impl->iInitialProcessHandleCount, _impl->iInitialThreadHandleCount); } bool MemoryLeakWarning::UsageIsNotBalanced() { TInt allocatedCells(User::CountAllocCells()); if(_impl->iExpectedLeaks != 0) { TInt difference(Abs(_impl->iInitialAllocCells - allocatedCells)); return difference != _impl->iExpectedLeaks; } return allocatedCells != _impl->iInitialAllocCells; } const char* MemoryLeakWarning::Message() { return ""; } void MemoryLeakWarning::ExpectLeaks(int n) { _impl->iExpectedLeaks = n; } // this method leaves (no naming convention followed due to CppUTest framework void MemoryLeakWarning::CreateData() { _impl = new(ELeave) MemoryLeakWarningData(); } void MemoryLeakWarning::DestroyData() { delete _impl; _impl = NULL; } MemoryLeakWarning* MemoryLeakWarning::GetLatest() { return _latest; } void MemoryLeakWarning::SetLatest(MemoryLeakWarning* latest) { _latest = latest; }
null
429
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/Symbian/UtestPlatform.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde and Timo Puronen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <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 <e32def.h> #include <e32std.h> #include <sys/time.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <stdlib.h> #include "CppUTest/PlatformSpecificFunctions.h" void Utest::executePlatformSpecificTestBody() { TInt err(KErrNone); TRAP(err, testBody()); if(err != KErrNone) { Utest::getCurrent()->fail("Leave in test method", "", 0); } } void Utest::executePlatformSpecificExitCurrentTest() { User::Leave(KErrNone); } bool Utest::executePlatformSpecificSetup() { setup(); return true; } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { runOneTest(plugin, result); } void Utest::executePlatformSpecificTeardown() { teardown(); } static long TimeInMillisImplementation() { struct timeval tv; struct timezone tz; ::gettimeofday(&tv, &tz); return (tv.tv_sec * 1000) + (long)(tv.tv_usec * 0.001); } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static SimpleString TimeStringImplementation() { time_t tm = time(NULL); return ctime(&tm); } static SimpleString (*timeStringFp) () = TimeStringImplementation; SimpleString GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(SimpleString (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } int PlatformSpecificVSNprintf(char* str, unsigned int size, const char* format, va_list args) { return vsnprintf(str, size, format, args); } char PlatformSpecificToLower(char c) { return tolower(c); } void PlatformSpecificFlush() { fflush(stdout); } int PlatformSpecificPutchar(int c) { return putchar(c); } char* PlatformSpecificStrCpy(char* s1, const char* s2) { return strcpy(s1, s2); } size_t PlatformSpecificStrLen(const char* s) { return strlen(s); } char* PlatformSpecificStrStr(const char* s1, const char* s2) { return strstr(s1, s2); } int PlatformSpecificStrCmp(const char* s1, const char* s2) { return strcmp(s1, s2); } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { return strncpy(s1, s2, size); } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { return strncmp(s1, s2, size); } char* PlatformSpecificStrCat(char* s1, const char* s2) { return strcat(s1, s2); } double PlatformSpecificFabs(double d) { return fabs(d); } void* PlatformSpecificMalloc(size_t size) { return malloc(size); } void* PlatformSpecificRealloc (void* memory, size_t size) { return realloc(memory, size); } void PlatformSpecificFree(void* memory) { free(memory); } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { return memcpy(s1, s2, size); } void* PlatformSpecificMemset(void* mem, int c, size_t size) { return memset(mem, c, size); } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { return fopen(filename, flag); } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { fputs(str, (FILE*)file); } void PlatformSpecificFClose(PlatformSpecificFile file) { fclose((FILE*)file); } int PlatformSpecificAtoI(const char*str) { return atoi(str); }
null
430
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/Gcc/UtestPlatform.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 <stdlib.h> #include "CppUTest/TestHarness.h" #undef malloc #undef free #undef calloc #undef realloc #include "CppUTest/TestRegistry.h" #include <sys/time.h> #include <time.h> #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #include <string.h> #include <math.h> #include <ctype.h> #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; bool Utest::executePlatformSpecificSetup() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; setup(); jmp_buf_index--; return true; } return false; } void Utest::executePlatformSpecificTestBody() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; testBody(); jmp_buf_index--; } } void Utest::executePlatformSpecificTeardown() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; teardown(); jmp_buf_index--; } } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; runOneTest(plugin, result); jmp_buf_index--; } } void Utest::executePlatformSpecificExitCurrentTest() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } ///////////// Time in millis static long TimeInMillisImplementation() { struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001); } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static const char* TimeStringImplementation() { time_t tm = time(NULL); return ctime(&tm); } static const char* (*timeStringFp) () = TimeStringImplementation; const char* GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } int PlatformSpecificAtoI(const char*str) { return atoi(str); } size_t PlatformSpecificStrLen(const char* str) { return strlen(str); } char* PlatformSpecificStrCat(char* s1, const char* s2) { return strcat(s1, s2); } char* PlatformSpecificStrCpy(char* s1, const char* s2) { return strcpy(s1, s2); } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { return strncpy(s1, s2, size); } int PlatformSpecificStrCmp(const char* s1, const char* s2) { return strcmp(s1, s2); } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { return strncmp(s1, s2, size); } char* PlatformSpecificStrStr(const char* s1, const char* s2) { return (char*) strstr(s1, s2); } int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args) { return vsnprintf( str, size, format, args); } char PlatformSpecificToLower(char c) { return (char) tolower((char) c); } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { return fopen(filename, flag); } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { fputs(str, (FILE*)file); } void PlatformSpecificFClose(PlatformSpecificFile file) { fclose((FILE*)file); } void PlatformSpecificFlush() { fflush(stdout); } int PlatformSpecificPutchar(int c) { return putchar(c); } void* PlatformSpecificMalloc(size_t size) { return malloc(size); } void* PlatformSpecificRealloc (void* memory, size_t size) { return realloc(memory, size); } void PlatformSpecificFree(void* memory) { free(memory); } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { return memcpy(s1, s2, size); } void* PlatformSpecificMemset(void* mem, int c, size_t size) { return memset(mem, c, size); } double PlatformSpecificFabs(double d) { return fabs(d); } int PlatformSpecificIsNan(double d) { return isnan((float)d); }
null
431
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/VisualCpp/UtestPlatform.cpp
null
#include "Platform.h" #include <stdlib.h> #include "CppUTest/TestHarness.h" #undef malloc #undef free #undef calloc #undef realloc #include "CppUTest/TestRegistry.h" #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #include <string.h> #include <math.h> #include <float.h> #include "CppUTest/PlatformSpecificFunctions.h" #include <windows.h> #include <mmsystem.h> #if 0 //from GCC static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; bool Utest::executePlatformSpecificSetup() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; setup(); jmp_buf_index--; return true; } return false; } void Utest::executePlatformSpecificTestBody() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; testBody(); jmp_buf_index--; } } void Utest::executePlatformSpecificTeardown() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; teardown(); jmp_buf_index--; } } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin_, TestResult& result_) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; runOneTest(plugin_, result_); jmp_buf_index--; } } void Utest::executePlatformSpecificExitCurrentTest() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } #endif ///////////// Time in millis static long TimeInMillisImplementation() { return timeGetTime()/1000; } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static const char* TimeStringImplementation() { return "Windows time needs work"; } static const char* (*timeStringFp) () = TimeStringImplementation; const char* GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } ////// taken from gcc int PlatformSpecificAtoI(const char*str) { return atoi(str); } size_t PlatformSpecificStrLen(const char* str) { return strlen(str); } char* PlatformSpecificStrCat(char* s1, const char* s2) { return strcat(s1, s2); } char* PlatformSpecificStrCpy(char* s1, const char* s2) { return strcpy(s1, s2); } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { return strncpy(s1, s2, size); } int PlatformSpecificStrCmp(const char* s1, const char* s2) { return strcmp(s1, s2); } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { return strncmp(s1, s2, size); } char* PlatformSpecificStrStr(const char* s1, const char* s2) { return (char*) strstr(s1, s2); } int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args) { char* buf = 0; int sizeGuess = size; int result = _vsnprintf( str, size, format, args); str[size-1] = 0; while (result == -1) { if (buf != 0) free(buf); sizeGuess += 10; buf = (char*)malloc(sizeGuess); result = _vsnprintf( buf, sizeGuess, format, args); } if (buf != 0) free(buf); return result; } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { return fopen(filename, flag); } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { fputs(str, (FILE*)file); } void PlatformSpecificFClose(PlatformSpecificFile file) { fclose((FILE*)file); } void PlatformSpecificFlush() { fflush(stdout); } int PlatformSpecificPutchar(int c) { return putchar(c); } void* PlatformSpecificMalloc(size_t size) { return malloc(size); } void* PlatformSpecificRealloc (void* memory, size_t size) { return realloc(memory, size); } void PlatformSpecificFree(void* memory) { free(memory); } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { return memcpy(s1, s2, size); } void* PlatformSpecificMemset(void* mem, int c, size_t size) { return memset(mem, c, size); } double PlatformSpecificFabs(double d) { return fabs(d); } int PlatformSpecificIsNan(double d) { return _isnan(d); } /////// clean up the rest #if 0 void TestRegistry::platformSpecificRunOneTest(Utest* test, TestResult& result_) { try { runOneTest(test, result_) ; } catch (int) { //exiting test early } } void Utest::executePlatformSpecificTestBody() { testBody(); } void PlatformSpecificExitCurrentTestImpl() { throw(1); } #endif int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, void* args) { return _vsnprintf( str, size, format, (va_list) args); } char PlatformSpecificToLower(char c) { return tolower(c); } //platform specific test running stuff #if 1 #include <setjmp.h> static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; bool Utest::executePlatformSpecificSetup() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; setup(); jmp_buf_index--; return true; } return false; } void Utest::executePlatformSpecificTestBody() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; testBody(); jmp_buf_index--; } } void Utest::executePlatformSpecificTeardown() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; teardown(); jmp_buf_index--; } } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; runOneTest(plugin, result); jmp_buf_index--; } } void Utest::executePlatformSpecificExitCurrentTest() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } /* void PlatformSpecificExitCurrentTestImpl() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } */ #endif //static jmp_buf test_exit_jmp_buf[10]; //static int jmp_buf_index = 0; #if 0 bool Utest::executePlatformSpecificSetup() { try { setup(); } catch (int) { return false; } return true; } void Utest::executePlatformSpecificTestBody() { try { testBody(); } catch (int) { } } void Utest::executePlatformSpecificTeardown() { try { teardown(); } catch (int) { } } void PlatformSpecificExitCurrentTestImpl() { throw(1); } void (*PlatformSpecificExitCurrentTest)() = PlatformSpecificExitCurrentTestImpl; void FakePlatformSpecificExitCurrentTest() { } #endif
null
432
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/GccNoStdC/UtestPlatform.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" #undef malloc #undef free #undef calloc #undef realloc #include "CppUTest/TestRegistry.h" #include "CppUTest/PlatformSpecificFunctions.h" bool Utest::executePlatformSpecificSetup() { /* To be implemented */ setup(); return false; } void Utest::executePlatformSpecificTestBody() { /* To be implemented */ testBody(); } void Utest::executePlatformSpecificTeardown() { /* To be implemented */ teardown(); } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { /* To be implemented */ runOneTest(plugin, result); } void Utest::executePlatformSpecificExitCurrentTest() { /* To be implemented */ } long GetPlatformSpecificTimeInMillis() { /* To be implemented */ return 0; } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { (void) platformSpecific; } ///////////// Time in String const char* GetPlatformSpecificTimeString() { /* To be implemented */ return NULL; } void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) { /* To be implemented */ (void) platformMethod; } int PlatformSpecificAtoI(const char*str) { /* To be implemented */ (void) str; return 0; } size_t PlatformSpecificStrLen(const char* str) { /* To be implemented */ (void) str; return 0; } char* PlatformSpecificStrCat(char* s1, const char* s2) { /* To be implemented */ (void) s1; (void) s2; return NULL; } char* PlatformSpecificStrCpy(char* s1, const char* s2) { /* To be implemented */ (void) s1; (void) s2; return NULL; } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { /* To be implemented */ (void) s1; (void) s2; (void) size; return NULL; } int PlatformSpecificStrCmp(const char* s1, const char* s2) { /* To be implemented */ (void) s1; (void) s2; return 0; } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { /* To be implemented */ (void) s1; (void) s2; (void) size; return 0; } char* PlatformSpecificStrStr(const char* s1, const char* s2) { /* To be implemented */ (void) s1; (void) s2; return NULL; } int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args) { /* To be implemented */ (void) size; (void) args; (void) format; (void) args; (void) str; return 0; } char PlatformSpecificToLower(char c) { /* To be implemented */ (void) c; return 0; } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { /* To be implemented */ (void) filename; (void) flag; return NULL; } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { /* To be implemented */ (void) str; (void) file; } void PlatformSpecificFClose(PlatformSpecificFile file) { /* To be implemented */ (void) file; } void PlatformSpecificFlush() { /* To be implemented */ } int PlatformSpecificPutchar(int c) { /* To be implemented */ (void) c; return 0; } void* PlatformSpecificMalloc(size_t size) { /* To be implemented */ (void) size; return NULL; } void* PlatformSpecificRealloc (void* memory, size_t size) { /* To be implemented */ (void) memory; (void) size; return NULL; } void PlatformSpecificFree(void* memory) { /* To be implemented */ (void) memory; } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { /* To be implemented */ (void) size; (void) s1; (void) s2; return NULL; } void* PlatformSpecificMemset(void* mem, int c, size_t size) { /* To be implemented */ (void) mem; (void) c; (void) size; return NULL; } double PlatformSpecificFabs(double d) { /* To be implemented */ (void) d; return 0.0; } int PlatformSpecificIsNan(double d) { /* To be implemented */ (void) d; return 0; } void* malloc(size_t) { return NULL; } void free(void *) { }
null
433
cpp
blalor-cpputest
StarterMemoryLeakWarning.cpp
src/Platforms/StarterKit/StarterMemoryLeakWarning.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/MemoryLeakWarning.h" #include <stdlib.h> #include <stdio.h> /* Static since we REALLY can have only one of these! */ static int allocatedBlocks = 0; static int allocatedArrays = 0; static int firstInitialBlocks = 0; static int firstInitialArrays = 0; static bool reporterRegistered = false; class MemoryLeakWarningData { public: MemoryLeakWarningData(); int initialBlocksUsed; int initialArraysUsed; int blockUsageCheckPoint; int arrayUsageCheckPoint; int expectCount; char message[100]; }; void MemoryLeakWarning::CreateData() { _impl = (MemoryLeakWarningData*) malloc(sizeof(MemoryLeakWarningData)); _impl->initialBlocksUsed = 0; _impl->initialArraysUsed = 0; _impl->blockUsageCheckPoint = 0; _impl->arrayUsageCheckPoint = 0; _impl->expectCount = 0; _impl->message_[0] = '\0'; } void MemoryLeakWarning::DestroyData() { free(_impl); } extern "C" { void reportMemoryBallance(); } void reportMemoryBallance() { int blockBalance = allocatedBlocks - firstInitialBlocks; int arrayBalance = allocatedArrays - firstInitialArrays; if (blockBalance == 0 && arrayBalance == 0) ; else if (blockBalance + arrayBalance == 0) printf("No leaks but some arrays were deleted without []\n"); else { if (blockBalance > 0) printf("Memory leak! %d blocks not deleted\n", blockBalance); if (arrayBalance > 0) printf("Memory leak! %d arrays not deleted\n", arrayBalance); if (blockBalance < 0) printf("More blocks deleted than newed! %d extra deletes\n", blockBalance); if (arrayBalance < 0) printf("More arrays deleted than newed! %d extra deletes\n", arrayBalance); printf("NOTE - some memory leaks appear to be allocated statics that are not released\n" " - by the standard library\n" " - Use the -r switch on your unit tests to repeat the test sequence\n" " - If no leaks are reported on the second pass, it is likely a static\n" " - that is not released\n"); } } MemoryLeakWarning* MemoryLeakWarning::_latest = NULL; MemoryLeakWarning::MemoryLeakWarning() { _latest = this; CreateData(); } MemoryLeakWarning::~MemoryLeakWarning() { DestroyData(); } MemoryLeakWarning* MemoryLeakWarning::GetLatest() { return _latest; } void MemoryLeakWarning::SetLatest(MemoryLeakWarning* latest) { _latest = latest; } void MemoryLeakWarning::Enable() { _impl->initialBlocksUsed = allocatedBlocks; _impl->initialArraysUsed = allocatedArrays; if (!reporterRegistered) { firstInitialBlocks = allocatedBlocks; firstInitialArrays = allocatedArrays; reporterRegistered = true; } } const char* MemoryLeakWarning::FinalReport(int toBeDeletedLeaks) { if (_impl->initialBlocksUsed != (allocatedBlocks-toBeDeletedLeaks) || _impl->initialArraysUsed != allocatedArrays ) { printf("initial blocks=%d, allocated blocks=%d\ninitial arrays=%d, allocated arrays=%d\n", _impl->initialBlocksUsed, allocatedBlocks, _impl->initialArraysUsed, allocatedArrays); return "Memory new/delete imbalance after running tests\n"; } else return ""; } void MemoryLeakWarning::CheckPointUsage() { _impl->blockUsageCheckPoint = allocatedBlocks; _impl->arrayUsageCheckPoint = allocatedArrays; } bool MemoryLeakWarning::UsageIsNotBalanced() { int arrayBalance = allocatedArrays - _impl->arrayUsageCheckPoint; int blockBalance = allocatedBlocks - _impl->blockUsageCheckPoint; if (_impl->expectCount != 0 && blockBalance + arrayBalance == _impl->expectCount) return false; if (blockBalance == 0 && arrayBalance == 0) return false; else if (blockBalance + arrayBalance == 0) sprintf(_impl->message_, "No leaks but some arrays were deleted without []\n"); else { int nchars = 0; if (_impl->blockUsageCheckPoint != allocatedBlocks) nchars = sprintf(_impl->message_, "this test leaks %d blocks", allocatedBlocks - _impl->blockUsageCheckPoint); if (_impl->arrayUsageCheckPoint != allocatedArrays) sprintf(_impl->message_ + nchars, "this test leaks %d arrays", allocatedArrays - _impl->arrayUsageCheckPoint); } return true; } const char* MemoryLeakWarning::Message() { return _impl->message_; } void MemoryLeakWarning::ExpectLeaks(int n) { _impl->expectCount = n; } /* Global overloaded operators */ void* operator new(size_t size) { allocatedBlocks++; return malloc(size); } void operator delete(void* mem) { allocatedBlocks--; free(mem); } void* operator new[](size_t size) { allocatedArrays++; return malloc(size); } void operator delete[](void* mem) { allocatedArrays--; free(mem); } void* operator new(size_t size, const char* file, int line) { allocatedBlocks++; return malloc(size); }
null
434
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/StarterKit/UtestPlatform.cpp
null
#include "CppUTest/TestHarness.h" #include "CppUTest/TestResult.h" #include <time.h> #include <sys/time.h> void Utest::executePlatformSpecificTestBody() { testBody(); } ///////////// Time in millis static long TimeInMillisImplementation() { struct timeval tv; struct timezone tz; ::gettimeofday(&tv, &tz); return (tv.tv_sec * 1000) + (long)(tv.tv_usec * 0.001); } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static SimpleString TimeStringImplementation() { time_t tm = time(NULL); return ctime(&tm); } static SimpleString (*timeStringFp) () = TimeStringImplementation; SimpleString GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(SimpleString (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } ///////////// Run one test with exit on first error, using setjmp/longjmp #include <setjmp.h> static jmp_buf test_exit_jmp_buf; void TestRegistry::platformSpecificRunOneTest(Utest* test, TestResult& result) { if (0 == setjmp(test_exit_jmp_buf)) runOneTest(test, result) ; } void PlatformSpecificExitCurrentTestImpl() { longjmp(test_exit_jmp_buf, 1); } void FakePlatformSpecificExitCurrentTest() { } void (*PlatformSpecificExitCurrentTest)() = PlatformSpecificExitCurrentTestImpl;
null
435
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/Iar/UtestPlatform.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 <time.h> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <setjmp.h> #include <string.h> #include <math.h> #include "CppUTest/TestHarness.h" #undef malloc #undef calloc #undef realloc #undef free #include "CppUTest/TestRegistry.h" #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; bool Utest::executePlatformSpecificSetup() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; setup(); jmp_buf_index--; return true; } return false; } void Utest::executePlatformSpecificTestBody() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; testBody(); jmp_buf_index--; } } void Utest::executePlatformSpecificTeardown() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; teardown(); jmp_buf_index--; } } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; runOneTest(plugin, result); jmp_buf_index--; } } void Utest::executePlatformSpecificExitCurrentTest() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } ///////////// Time in millis static long TimeInMillisImplementation() { clock_t t = clock(); t = t * 10; return 1; } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static const char* TimeStringImplementation() { time_t tm = time(NULL); return ctime(&tm); } static const char* (*timeStringFp) () = TimeStringImplementation; const char* GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } int PlatformSpecificAtoI(const char*str) { return atoi(str); } size_t PlatformSpecificStrLen(const char* str) { return strlen(str); } char* PlatformSpecificStrCat(char* s1, const char* s2) { return strcat(s1, s2); } char* PlatformSpecificStrCpy(char* s1, const char* s2) { return strcpy(s1, s2); } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { return strncpy(s1, s2, size); } int PlatformSpecificStrCmp(const char* s1, const char* s2) { return strcmp(s1, s2); } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { return strncmp(s1, s2, size); } char* PlatformSpecificStrStr(const char* s1, const char* s2) { return strstr((char*)s1, (char*)s2); } int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args) { return vsnprintf( str, size, format, args); } char PlatformSpecificToLower(char c) { return tolower(c); } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { return 0; } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { } void PlatformSpecificFClose(PlatformSpecificFile file) { } void PlatformSpecificFlush() { } int PlatformSpecificPutchar(int c) { return putchar(c); } void* PlatformSpecificMalloc(size_t size) { return malloc(size); } void* PlatformSpecificRealloc (void* memory, size_t size) { return realloc(memory, size); } void PlatformSpecificFree(void* memory) { free(memory); } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { return memcpy(s1, s2, size); } void* PlatformSpecificMemset(void* mem, int c, size_t size) { return memset(mem, c, size); } double PlatformSpecificFabs(double d) { return fabs(d); } int PlatformSpecificIsNan(double d) { return isnan(d); }
null
436
cpp
cpputest-stm32-keil-demo
UnitTest.cpp
Src/UnitTest.cpp
null
/** ****************************************************************************** * @file UnitTest.cpp * @author Serbay Ozkan * @version V1.0.0 * @date 14-October-2019 * @brief Unit Test Example App. Source File ****************************************************************************** */ #include "CppUTest/TestHarness.h" class addClass { private: int sumTotal; public: addClass(void): sumTotal {0} { } int getTotal(void); void add(int, int); }; void addClass::add(int value1, int value2) { sumTotal = value1 + value2; } int addClass::getTotal(void) { return sumTotal; } TEST_GROUP(myFirstUnitTest) { }; TEST(myFirstUnitTest, API1) { FAIL("I am Failed!"); } TEST(myFirstUnitTest, API2) { STRCMP_EQUAL("Hello", "Hello"); } TEST(myFirstUnitTest, API3) { addClass adder; adder.add(100, 200); CHECK_EQUAL (310, adder.getTotal()); }
null
437
cpp
cpputest-stm32-keil-demo
main.cpp
Src/main.cpp
null
/** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** ** This notice applies to any and all portions of this file * that are not between comment pairs USER CODE BEGIN and * USER CODE END. Other portions of this file, whether * inserted by the user or by software development tools * are owned by their respective copyright owners. * * COPYRIGHT(c) 2019 STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f7xx_hal.h" #include "gpio.h" /* USER CODE BEGIN Includes */ #include "CommandLineTestRunner.h" /* USER CODE END Includes */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* Private variables ---------------------------------------------------------*/ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE END PFP */ /* USER CODE BEGIN 0 */ #include "stdio.h" /* USER CODE END 0 */ /** * @brief The application entry point. * * @retval None */ int main(int ac, char** av) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration----------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); /* USER CODE BEGIN 2 */ //turn on verbose mode const char * av_override[] = { "exe", "-v" }; CommandLineTestRunner::RunAllTests(2, av_override); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct; RCC_ClkInitTypeDef RCC_ClkInitStruct; /**Configure the main internal regulator output voltage */ __HAL_RCC_PWR_CLK_ENABLE(); __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); /**Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = 16; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; RCC_OscInitStruct.PLL.PLLM = 8; RCC_OscInitStruct.PLL.PLLN = 216; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 2; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { } /**Activate the Over-Drive mode */ if (HAL_PWREx_EnableOverDrive() != HAL_OK) { } /**Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7) != HAL_OK) { } /**Configure the Systick interrupt time */ HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); /**Configure the Systick */ HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @param file: The file name as string. * @param line: The line in file as a number. * @retval None */ void _Error_Handler(char *file, int line) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ while(1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
null
438
cpp
cpputest-stm32-keil-demo
PlatformSpecificFunctions_c.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/PlatformSpecificFunctions_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. */ /****************************************************************************** * * PlatformSpecificFunctions_c.H * * Provides an interface for when working with pure C * *******************************************************************************/ #ifndef PLATFORMSPECIFICFUNCTIONS_C_H_ #define PLATFORMSPECIFICFUNCTIONS_C_H_ #ifdef __cplusplus extern "C" { #endif /* Jumping operations. They manage their own jump buffers */ extern int (*PlatformSpecificSetJmp)(void (*function) (void*), void* data); extern void (*PlatformSpecificLongJmp)(void); extern void (*PlatformSpecificRestoreJumpBuffer)(void); /* Time operations */ extern long (*GetPlatformSpecificTimeInMillis)(void); extern const char* (*GetPlatformSpecificTimeString)(void); /* String operations */ extern int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list); /* Misc */ extern double (*PlatformSpecificFabs)(double d); extern int (*PlatformSpecificIsNan)(double d); extern int (*PlatformSpecificIsInf)(double d); extern int (*PlatformSpecificAtExit)(void(*func)(void)); /* IO operations */ typedef void* PlatformSpecificFile; extern PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag); extern void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file); extern void (*PlatformSpecificFClose)(PlatformSpecificFile file); extern int (*PlatformSpecificPutchar)(int c); extern void (*PlatformSpecificFlush)(void); /* Dynamic Memory operations */ extern void* (*PlatformSpecificMalloc)(size_t size); extern void* (*PlatformSpecificRealloc)(void* memory, size_t size); extern void (*PlatformSpecificFree)(void* memory); extern void* (*PlatformSpecificMemCpy)(void* s1, const void* s2, size_t size); extern void* (*PlatformSpecificMemset)(void* mem, int c, size_t size); typedef void* PlatformSpecificMutex; extern PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void); extern void (*PlatformSpecificMutexLock)(PlatformSpecificMutex mtx); extern void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex mtx); extern void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex mtx); #ifdef __cplusplus } #endif #endif /* PLATFORMSPECIFICFUNCTIONS_C_H_ */
null
439
cpp
cpputest-stm32-keil-demo
TestPlugin.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/TestPlugin.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_TestPlugin_h #define D_TestPlugin_h class UtestShell; class TestResult; class TestPlugin { public: TestPlugin(const SimpleString& name); virtual ~TestPlugin(); virtual void preTestAction(UtestShell&, TestResult&) { } virtual void postTestAction(UtestShell&, TestResult&) { } virtual bool parseArguments(int /* ac */, const char** /* av */, int /* index */ ) { return false; } virtual void runAllPreTestAction(UtestShell&, TestResult&); virtual void runAllPostTestAction(UtestShell&, TestResult&); virtual bool parseAllArguments(int ac, const char** av, int index); virtual bool parseAllArguments(int ac, char** av, int index); virtual TestPlugin* addPlugin(TestPlugin*); virtual TestPlugin* removePluginByName(const SimpleString& name); virtual TestPlugin* getNext(); virtual void disable(); virtual void enable(); virtual bool isEnabled(); const SimpleString& getName(); TestPlugin* getPluginByName(const SimpleString& name); protected: TestPlugin(TestPlugin* next_); private: TestPlugin* next_; SimpleString name_; bool enabled_; }; /////////////////////////////////////////////////////////////////////////////// // // SetPointerPlugin // // This is a very small plugin_ that resets pointers to their original value. // /////////////////////////////////////////////////////////////////////////////// extern void CppUTestStore(void **location); class SetPointerPlugin: public TestPlugin { public: SetPointerPlugin(const SimpleString& name); virtual void postTestAction(UtestShell&, TestResult&) _override; enum { MAX_SET = 32 }; }; #define UT_PTR_SET(a, b) { CppUTestStore( (void**)&a ); a = b; } ///////////// Null Plugin class NullTestPlugin: public TestPlugin { public: NullTestPlugin(); virtual void runAllPreTestAction(UtestShell& test, TestResult& result) _override; virtual void runAllPostTestAction(UtestShell& test, TestResult& result) _override; static NullTestPlugin* instance(); }; #endif
null
440
cpp
cpputest-stm32-keil-demo
PlatformSpecificFunctions.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/PlatformSpecificFunctions.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 PLATFORMSPECIFICFUNCTIONS_H_ #define PLATFORMSPECIFICFUNCTIONS_H_ #include "CppUTest/TestOutput.h" TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment(); class TestPlugin; extern void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result); extern int (*PlatformSpecificFork)(void); extern int (*PlatformSpecificWaitPid)(int pid, int* status, int options); /* Platform specific interface we use in order to minimize dependencies with LibC. * This enables porting to different embedded platforms. * */ #include "CppUTest/PlatformSpecificFunctions_c.h" #endif
null
441
cpp
cpputest-stm32-keil-demo
TestResult.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/TestResult.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. */ /////////////////////////////////////////////////////////////////////////////// // // A TestResult is a collection of the history of some test runs. Right now // it just collects failures. Really it just prints the failures. // #ifndef D_TestResult_h #define D_TestResult_h class TestFailure; class TestOutput; class UtestShell; class TestResult { public: TestResult(TestOutput&); DEFAULT_COPY_CONSTRUCTOR(TestResult) virtual ~TestResult(); virtual void testsStarted(); virtual void testsEnded(); virtual void currentGroupStarted(UtestShell* test); virtual void currentGroupEnded(UtestShell* test); virtual void currentTestStarted(UtestShell* test); virtual void currentTestEnded(UtestShell* test); virtual void countTest(); virtual void countRun(); virtual void countCheck(); virtual void countFilteredOut(); virtual void countIgnored(); virtual void addFailure(const TestFailure& failure); virtual void print(const char* text); int getTestCount() const { return testCount_; } int getRunCount() const { return runCount_; } int getCheckCount() const { return checkCount_; } int getFilteredOutCount() const { return filteredOutCount_; } int getIgnoredCount() const { return ignoredCount_; } int getFailureCount() const { return failureCount_; } long getTotalExecutionTime() const; void setTotalExecutionTime(long exTime); long getCurrentTestTotalExecutionTime() const; long getCurrentGroupTotalExecutionTime() const; private: TestOutput& output_; int testCount_; int runCount_; int checkCount_; int failureCount_; int filteredOutCount_; int ignoredCount_; long totalExecutionTime_; long timeStarted_; long currentTestTimeStarted_; long currentTestTotalExecutionTime_; long currentGroupTimeStarted_; long currentGroupTotalExecutionTime_; }; #endif
null
442
cpp
cpputest-stm32-keil-demo
SimpleMutex.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/SimpleMutex.h
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. */ #ifndef D_SimpleMutex_h #define D_SimpleMutex_h #include "CppUTest/PlatformSpecificFunctions.h" class SimpleMutex { public: SimpleMutex(void); ~SimpleMutex(void); void Lock(void); void Unlock(void); private: PlatformSpecificMutex psMtx; }; class ScopedMutexLock { public: ScopedMutexLock(SimpleMutex *); ~ScopedMutexLock(void); private: SimpleMutex * mutex; }; #endif
null
443
cpp
cpputest-stm32-keil-demo
CommandLineArguments.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/CommandLineArguments.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_CommandLineArguments_H #define D_CommandLineArguments_H #include "SimpleString.h" #include "TestOutput.h" #include "TestFilter.h" class TestPlugin; class CommandLineArguments { public: explicit CommandLineArguments(int ac, const char** av); virtual ~CommandLineArguments(); bool parse(TestPlugin* plugin); bool isVerbose() const; bool isColor() const; bool isListingTestGroupNames() const; bool isListingTestGroupAndCaseNames() const; bool isRunIgnored() const; int getRepeatCount() const; const TestFilter* getGroupFilters() const; const TestFilter* getNameFilters() const; bool isJUnitOutput() const; bool isEclipseOutput() const; bool isTeamCityOutput() const; bool runTestsInSeperateProcess() const; const SimpleString& getPackageName() const; const char* usage() const; private: enum OutputType { OUTPUT_ECLIPSE, OUTPUT_JUNIT, OUTPUT_TEAMCITY }; int ac_; const char** av_; bool verbose_; bool color_; bool runTestsAsSeperateProcess_; bool listTestGroupNames_; bool listTestGroupAndCaseNames_; bool runIgnored_; int repeat_; TestFilter* groupFilters_; TestFilter* nameFilters_; OutputType outputType_; SimpleString packageName_; SimpleString getParameterField(int ac, const char** av, int& i, const SimpleString& parameterName); void SetRepeatCount(int ac, const char** av, int& index); void AddGroupFilter(int ac, const char** av, int& index); void AddStrictGroupFilter(int ac, const char** av, int& index); void AddExcludeGroupFilter(int ac, const char** av, int& index); void AddExcludeStrictGroupFilter(int ac, const char** av, int& index); void AddNameFilter(int ac, const char** av, int& index); void AddStrictNameFilter(int ac, const char** av, int& index); void AddExcludeNameFilter(int ac, const char** av, int& index); void AddExcludeStrictNameFilter(int ac, const char** av, int& index); void AddTestToRunBasedOnVerboseOutput(int ac, const char** av, int& index, const char* parameterName); bool SetOutputType(int ac, const char** av, int& index); void SetPackageName(int ac, const char** av, int& index); CommandLineArguments(const CommandLineArguments&); CommandLineArguments& operator=(const CommandLineArguments&); }; #endif
null
444
cpp
cpputest-stm32-keil-demo
TestHarness.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/TestHarness.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_TestHarness_h #define D_TestHarness_h #include "CppUTestConfig.h" /* original value was 9973 which works well with large programs. Now set to smaller since it takes * a lot of memory in embedded apps. Change it if you experience the memory leak detector to be slow. */ #define MEMORY_LEAK_HASH_TABLE_SIZE 73 #include "Utest.h" #include "UtestMacros.h" #include "SimpleString.h" #include "TestResult.h" #include "TestFailure.h" #include "TestPlugin.h" #include "MemoryLeakWarningPlugin.h" #endif
null
445
cpp
cpputest-stm32-keil-demo
JUnitTestOutput.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/JUnitTestOutput.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_JUnitTestOutput_h #define D_JUnitTestOutput_h #include "TestOutput.h" #include "SimpleString.h" struct JUnitTestOutputImpl; struct JUnitTestCaseResultNode; class JUnitTestOutput: public TestOutput { public: JUnitTestOutput(); virtual ~JUnitTestOutput(); virtual void printTestsStarted() _override; virtual void printTestsEnded(const TestResult& result) _override; virtual void printCurrentTestStarted(const UtestShell& test) _override; virtual void printCurrentTestEnded(const TestResult& res) _override; virtual void printCurrentGroupStarted(const UtestShell& test) _override; virtual void printCurrentGroupEnded(const TestResult& res) _override; virtual void printBuffer(const char*) _override; virtual void print(const char*) _override; virtual void print(long) _override; virtual void printFailure(const TestFailure& failure) _override; virtual void flush() _override; virtual SimpleString createFileName(const SimpleString& group); void setPackageName(const SimpleString &package); protected: JUnitTestOutputImpl* impl_; void resetTestGroupResult(); virtual void openFileForWrite(const SimpleString& fileName); virtual void writeTestGroupToFile(); virtual void writeToFile(const SimpleString& buffer); virtual void closeFile(); virtual void writeXmlHeader(); virtual void writeTestSuiteSummary(); virtual void writeProperties(); virtual void writeTestCases(); virtual void writeFailure(JUnitTestCaseResultNode* node); virtual void writeFileEnding(); }; #endif
null
446
cpp
cpputest-stm32-keil-demo
TestTestingFixture.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/TestTestingFixture.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_TestTestingFixture_H #define D_TestTestingFixture_H #include "TestRegistry.h" #include "TestOutput.h" class TestTestingFixture { public: TestTestingFixture() { output_ = new StringBufferTestOutput(); result_ = new TestResult(*output_); genTest_ = new ExecFunctionTestShell(); registry_ = new TestRegistry(); registry_->setCurrentRegistry(registry_); registry_->addTest(genTest_); lineOfCodeExecutedAfterCheck = false; } virtual ~TestTestingFixture() { registry_->setCurrentRegistry(0); delete registry_; delete result_; delete output_; delete genTest_; } void addTest(UtestShell * test) { registry_->addTest(test); } void setTestFunction(void(*testFunction)()) { genTest_->testFunction_ = testFunction; } void setSetup(void(*setupFunction)()) { genTest_->setup_ = setupFunction; } void setTeardown(void(*teardownFunction)()) { genTest_->teardown_ = teardownFunction; } void runTestWithMethod(void(*method)()) { setTestFunction(method); runAllTests(); } void runAllTests() { registry_->runAllTests(*result_); } int getFailureCount() { return result_->getFailureCount(); } int getCheckCount() { return result_->getCheckCount(); } int getIgnoreCount() { return result_->getIgnoredCount(); } bool hasTestFailed() { return genTest_->hasFailed(); } void assertPrintContains(const SimpleString& contains) { assertPrintContains(getOutput(), contains); } const SimpleString& getOutput() { return output_->getOutput(); } static void assertPrintContains(const SimpleString& output, const SimpleString& contains) { STRCMP_CONTAINS(contains.asCharString(), output.asCharString()); } int getRunCount() { return result_->getRunCount(); } void checkTestFailsWithProperTestLocation(const char* text, const char* file, int line); static void lineExecutedAfterCheck(); static bool lineOfCodeExecutedAfterCheck; TestRegistry* registry_; ExecFunctionTestShell* genTest_; StringBufferTestOutput* output_; TestResult * result_; }; class SetBooleanOnDestructorCall { bool& booleanToSet_; public: SetBooleanOnDestructorCall(bool& booleanToSet) : booleanToSet_(booleanToSet) { } virtual ~SetBooleanOnDestructorCall() { booleanToSet_ = true; } }; #endif
null
447
cpp
cpputest-stm32-keil-demo
TestFailure.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/TestFailure.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. */ /////////////////////////////////////////////////////////////////////////////// // // Failure is a class which holds information for a specific // test failure. It can be overriden for more complex failure messages // /////////////////////////////////////////////////////////////////////////////// #ifndef D_TestFailure_H #define D_TestFailure_H #include "SimpleString.h" class UtestShell; class TestOutput; class TestFailure { public: TestFailure(UtestShell*, const char* fileName, int lineNumber, const SimpleString& theMessage); TestFailure(UtestShell*, const SimpleString& theMessage); TestFailure(UtestShell*, const char* fileName, int lineNumber); TestFailure(const TestFailure&); virtual ~TestFailure(); virtual SimpleString getFileName() const; virtual SimpleString getTestName() const; virtual SimpleString getTestNameOnly() const; virtual int getFailureLineNumber() const; virtual SimpleString getMessage() const; virtual SimpleString getTestFileName() const; virtual int getTestLineNumber() const; bool isOutsideTestFile() const; bool isInHelperFunction() const; protected: enum DifferenceFormat { DIFFERENCE_STRING, DIFFERENCE_BINARY }; SimpleString createButWasString(const SimpleString& expected, const SimpleString& actual); SimpleString createDifferenceAtPosString(const SimpleString& actual, size_t position, DifferenceFormat format = DIFFERENCE_STRING); SimpleString createUserText(const SimpleString& text); SimpleString testName_; SimpleString testNameOnly_; SimpleString fileName_; int lineNumber_; SimpleString testFileName_; int testLineNumber_; SimpleString message_; TestFailure& operator=(const TestFailure&); }; class EqualsFailure: public TestFailure { public: EqualsFailure(UtestShell*, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text); EqualsFailure(UtestShell*, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); }; class DoublesEqualFailure: public TestFailure { public: DoublesEqualFailure(UtestShell*, const char* fileName, int lineNumber, double expected, double actual, double threshold, const SimpleString& text); }; class CheckEqualFailure : public TestFailure { public: CheckEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); }; class ContainsFailure: public TestFailure { public: ContainsFailure(UtestShell*, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); }; class CheckFailure : public TestFailure { public: CheckFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& checkString, const SimpleString& conditionString, const SimpleString& textString = ""); }; class FailFailure : public TestFailure { public: FailFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& message); }; class LongsEqualFailure : public TestFailure { public: LongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, long expected, long actual, const SimpleString& text); }; class UnsignedLongsEqualFailure : public TestFailure { public: UnsignedLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, unsigned long expected, unsigned long actual, const SimpleString& text); }; class LongLongsEqualFailure : public TestFailure { public: LongLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, cpputest_longlong expected, cpputest_longlong actual, const SimpleString& text); }; class UnsignedLongLongsEqualFailure : public TestFailure { public: UnsignedLongLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, cpputest_ulonglong expected, cpputest_ulonglong actual, const SimpleString& text); }; class SignedBytesEqualFailure : public TestFailure { public: SignedBytesEqualFailure (UtestShell* test, const char* fileName, int lineNumber, signed char expected, signed char actual, const SimpleString& text); }; class StringEqualFailure : public TestFailure { public: StringEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text); }; class StringEqualNoCaseFailure : public TestFailure { public: StringEqualNoCaseFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text); }; class BinaryEqualFailure : public TestFailure { public: BinaryEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const unsigned char* expected, const unsigned char* actual, size_t size, const SimpleString& text); }; class BitsEqualFailure : public TestFailure { public: BitsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const SimpleString& text); }; class FeatureUnsupportedFailure : public TestFailure { public: FeatureUnsupportedFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& featureName, const SimpleString& text); }; #endif
null
448
cpp
cpputest-stm32-keil-demo
CommandLineTestRunner.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/CommandLineTestRunner.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_CommandLineTestRunner_H #define D_CommandLineTestRunner_H #include "TestHarness.h" #include "TestOutput.h" #include "CommandLineArguments.h" #include "TestFilter.h" class TestRegistry; #define DEF_PLUGIN_MEM_LEAK "MemoryLeakPlugin" #define DEF_PLUGIN_SET_POINTER "SetPointerPlugin" class CommandLineTestRunner { public: static int RunAllTests(int ac, const char** av); static int RunAllTests(int ac, char** av); CommandLineTestRunner(int ac, const char** av, TestRegistry* registry); virtual ~CommandLineTestRunner(); int runAllTestsMain(); protected: virtual TestOutput* createTeamCityOutput(); virtual TestOutput* createJUnitOutput(const SimpleString& packageName); virtual TestOutput* createConsoleOutput(); virtual TestOutput* createCompositeOutput(TestOutput* outputOne, TestOutput* outputTwo); TestOutput* output_; private: CommandLineArguments* arguments_; TestRegistry* registry_; bool parseArguments(TestPlugin*); int runAllTests(); void initializeTestRun(); }; #endif
null
449
cpp
cpputest-stm32-keil-demo
MemoryLeakDetectorMallocMacros.h
Middlewares/Third_Party/CPPUTEST/include/CppUTest/MemoryLeakDetectorMallocMacros.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 malloc. This will pass additional information to the * malloc 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. * */ #include "CppUTestConfig.h" #if CPPUTEST_USE_MEM_LEAK_DETECTION /* This prevents the declaration from done twice and makes sure the file only #defines malloc, so it can be included anywhere */ #ifndef CPPUTEST_USE_MALLOC_MACROS #ifdef __cplusplus extern "C" { #endif extern void* cpputest_malloc_location(size_t size, const char* file, int line); extern void* cpputest_calloc_location(size_t count, size_t size, const char* file, int line); extern void* cpputest_realloc_location(void *, size_t, const char* file, int line); extern void cpputest_free_location(void* buffer, const char* file, int line); #ifdef __cplusplus } #endif extern void crash_on_allocation_number(unsigned number); #endif /* NOTE on strdup! * * strdup was implemented earlier, however it is *not* an Standard C function but a POSIX function. * Because of that, it can lead to portability issues by providing more than is available on the local platform. * For that reason, strdup is *not* implemented as a macro. If you still want to use it, an easy implementation would be: * * size_t length = 1 + strlen(str); * char* result = (char*) cpputest_malloc_location(length, file, line); * memcpy(result, str, length); * return result; * */ #define malloc(a) cpputest_malloc_location(a, __FILE__, __LINE__) #define calloc(a, b) cpputest_calloc_location(a, b, __FILE__, __LINE__) #define realloc(a, b) cpputest_realloc_location(a, b, __FILE__, __LINE__) #define free(a) cpputest_free_location(a, __FILE__, __LINE__) #define CPPUTEST_USE_MALLOC_MACROS 1 #endif
null
450
cpp
cpputest-stm32-keil-demo
StandardCLibrary.h
Middlewares/Third_Party/CPPUTEST/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> #endif #endif /* Needed for malloc */ #include <stdlib.h> /* Needed for ... */ #include <stdarg.h> /* Needed for some detection of long long and 64 bit */ #include <limits.h> #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 typedef char* va_list; #define NULL (0) extern void* malloc(size_t); extern void free(void *); #define _bnd(X, bnd) (((sizeof (X)) + (bnd)) & (~(bnd))) #define va_start(ap, A) (void) ((ap) = (((char *) &(A)) + (_bnd (A,sizeof(int)-1)))) #define va_end(ap) (void) 0 #endif #endif #endif
null
451
cpp
cpputest-stm32-keil-demo
MemoryLeakWarningPlugin.h
Middlewares/Third_Party/CPPUTEST/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() MemoryLeakWarningPlugin::getFirstPlugin()->ignoreAllLeaksInTest(); #define EXPECT_N_LEAKS(n) 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 = 0); virtual ~MemoryLeakWarningPlugin(); virtual void preTestAction(UtestShell& test, TestResult& result) _override; virtual void postTestAction(UtestShell& test, TestResult& result) _override; virtual const char* FinalReport(int toBeDeletedLeaks = 0); void ignoreAllLeaksInTest(); void expectLeaksInTest(int 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 turnOnNewDeleteOverloads(); static void turnOnThreadSafeNewDeleteOverloads(); static bool areNewDeleteOverloaded(); private: MemoryLeakDetector* memLeakDetector_; bool ignoreAllWarnings_; bool destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_; int expectedLeaks_; int failureCount_; static MemoryLeakWarningPlugin* firstPlugin_; }; extern void* cpputest_malloc_location_with_leak_detection(size_t size, const char* file, int line); extern void* cpputest_realloc_location_with_leak_detection(void* memory, size_t size, const char* file, int line); extern void cpputest_free_location_with_leak_detection(void* buffer, const char* file, int line); #endif
null
452
cpp
cpputest-stm32-keil-demo
UtestMacros.h
Middlewares/Third_Party/CPPUTEST/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() #define TEST_TEARDOWN() \ virtual void teardown() #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(); }; \ class TEST_##testGroup##_##testName##_TestShell : public UtestShell { \ virtual Utest* createTest() _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 (); }; \ class IGNORE##testGroup##_##testName##_TestShell : public IgnoredUtestShell { \ virtual Utest* createTest() _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, NULL, __FILE__, __LINE__) #define CHECK_TEXT(condition, text) \ CHECK_TRUE_LOCATION(condition, "CHECK", #condition, text, __FILE__, __LINE__) #define CHECK_TRUE(condition)\ CHECK_TRUE_LOCATION(condition, "CHECK_TRUE", #condition, NULL, __FILE__, __LINE__) #define CHECK_TRUE_TEXT(condition, text)\ CHECK_TRUE_LOCATION(condition, "CHECK_TRUE", #condition, text, __FILE__, __LINE__) #define CHECK_FALSE(condition)\ CHECK_FALSE_LOCATION(condition, "CHECK_FALSE", #condition, NULL, __FILE__, __LINE__) #define CHECK_FALSE_TEXT(condition, text)\ CHECK_FALSE_LOCATION(condition, "CHECK_FALSE", #condition, text, __FILE__, __LINE__) #define CHECK_TRUE_LOCATION(condition, checkString, conditionString, text, file, line)\ { UtestShell::getCurrent()->assertTrue((condition) != 0, checkString, conditionString, text, file, line); } #define CHECK_FALSE_LOCATION(condition, checkString, conditionString, text, file, line)\ { UtestShell::getCurrent()->assertTrue((condition) == 0, checkString, conditionString, text, file, line); } //This check needs the operator!=(), and a StringFrom(YourType) function #define CHECK_EQUAL(expected, actual)\ CHECK_EQUAL_LOCATION(expected, actual, NULL, __FILE__, __LINE__) #define CHECK_EQUAL_TEXT(expected, actual, text)\ CHECK_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define CHECK_EQUAL_LOCATION(expected, actual, text, file, line)\ { if ((expected) != (actual)) { \ 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, NULL, file, line); \ } } //This check checks for char* string equality using strcmp. //This makes up for the fact that CHECK_EQUAL only compares the pointers to char*'s #define STRCMP_EQUAL(expected, actual)\ STRCMP_EQUAL_LOCATION(expected, actual, NULL, __FILE__, __LINE__) #define STRCMP_EQUAL_TEXT(expected, actual, text)\ STRCMP_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_EQUAL_LOCATION(expected, actual, text, file, line)\ { UtestShell::getCurrent()->assertCstrEqual(expected, actual, text, file, line); } #define STRNCMP_EQUAL(expected, actual, length)\ STRNCMP_EQUAL_LOCATION(expected, actual, length, NULL, __FILE__, __LINE__) #define STRNCMP_EQUAL_TEXT(expected, actual, length, text)\ STRNCMP_EQUAL_LOCATION(expected, actual, length, text, __FILE__, __LINE__) #define STRNCMP_EQUAL_LOCATION(expected, actual, length, text, file, line)\ { UtestShell::getCurrent()->assertCstrNEqual(expected, actual, length, text, file, line); } #define STRCMP_NOCASE_EQUAL(expected, actual)\ STRCMP_NOCASE_EQUAL_LOCATION(expected, actual, NULL, __FILE__, __LINE__) #define STRCMP_NOCASE_EQUAL_TEXT(expected, actual, text)\ STRCMP_NOCASE_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_NOCASE_EQUAL_LOCATION(expected, actual, text, file, line)\ { UtestShell::getCurrent()->assertCstrNoCaseEqual(expected, actual, text, file, line); } #define STRCMP_CONTAINS(expected, actual)\ STRCMP_CONTAINS_LOCATION(expected, actual, NULL, __FILE__, __LINE__) #define STRCMP_CONTAINS_TEXT(expected, actual, text)\ STRCMP_CONTAINS_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_CONTAINS_LOCATION(expected, actual, text, file, line)\ { UtestShell::getCurrent()->assertCstrContains(expected, actual, text, file, line); } #define STRCMP_NOCASE_CONTAINS(expected, actual)\ STRCMP_NOCASE_CONTAINS_LOCATION(expected, actual, NULL, __FILE__, __LINE__) #define STRCMP_NOCASE_CONTAINS_TEXT(expected, actual, text)\ STRCMP_NOCASE_CONTAINS_LOCATION(expected, actual, text, __FILE__, __LINE__) #define STRCMP_NOCASE_CONTAINS_LOCATION(expected, actual, text, file, line)\ { UtestShell::getCurrent()->assertCstrNoCaseContains(expected, actual, text, file, line); } //Check two long integers for equality #define LONGS_EQUAL(expected, actual)\ LONGS_EQUAL_LOCATION((expected), (actual), NULL, __FILE__, __LINE__) #define LONGS_EQUAL_TEXT(expected, actual, text)\ LONGS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define UNSIGNED_LONGS_EQUAL(expected, actual)\ UNSIGNED_LONGS_EQUAL_LOCATION((expected), (actual), NULL, __FILE__, __LINE__) #define UNSIGNED_LONGS_EQUAL_TEXT(expected, actual, text)\ UNSIGNED_LONGS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define LONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ { UtestShell::getCurrent()->assertLongsEqual((long)expected, (long)actual, text, file, line); } #define UNSIGNED_LONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ { UtestShell::getCurrent()->assertUnsignedLongsEqual((unsigned long)expected, (unsigned long)actual, text, file, line); } #define LONGLONGS_EQUAL(expected, actual)\ LONGLONGS_EQUAL_LOCATION(expected, actual, NULL, __FILE__, __LINE__) #define LONGLONGS_EQUAL_TEXT(expected, actual, text)\ LONGLONGS_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define UNSIGNED_LONGLONGS_EQUAL(expected, actual)\ UNSIGNED_LONGLONGS_EQUAL_LOCATION(expected, actual, NULL, __FILE__, __LINE__) #define UNSIGNED_LONGLONGS_EQUAL_TEXT(expected, actual, text)\ UNSIGNED_LONGLONGS_EQUAL_LOCATION(expected, actual, text, __FILE__, __LINE__) #define LONGLONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ { UtestShell::getCurrent()->assertLongLongsEqual(expected, actual, text, file, line); } #define UNSIGNED_LONGLONGS_EQUAL_LOCATION(expected, actual, text, file, line)\ { UtestShell::getCurrent()->assertUnsignedLongLongsEqual(expected, actual, text, file, line); } #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) \ { UtestShell::getCurrent()->assertSignedBytesEqual(expected, actual, NULL, file, line); } #define SIGNED_BYTES_EQUAL_TEXT(expected, actual, text)\ SIGNED_BYTES_EQUAL_TEXT_LOCATION(expected, actual, text, __FILE__, __LINE__) #define SIGNED_BYTES_EQUAL_TEXT_LOCATION(expected, actual, text, file, line) \ { UtestShell::getCurrent()->assertSignedBytesEqual(expected, actual, text, file, line); } #define POINTERS_EQUAL(expected, actual)\ POINTERS_EQUAL_LOCATION((expected), (actual), NULL, __FILE__, __LINE__) #define POINTERS_EQUAL_TEXT(expected, actual, text)\ POINTERS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define POINTERS_EQUAL_LOCATION(expected, actual, text, file, line)\ { UtestShell::getCurrent()->assertPointersEqual((void *)expected, (void *)actual, text, file, line); } #define FUNCTIONPOINTERS_EQUAL(expected, actual)\ FUNCTIONPOINTERS_EQUAL_LOCATION((expected), (actual), NULL, __FILE__, __LINE__) #define FUNCTIONPOINTERS_EQUAL_TEXT(expected, actual, text)\ FUNCTIONPOINTERS_EQUAL_LOCATION((expected), (actual), text, __FILE__, __LINE__) #define FUNCTIONPOINTERS_EQUAL_LOCATION(expected, actual, text, file, line)\ { UtestShell::getCurrent()->assertFunctionPointersEqual((void (*)())expected, (void (*)())actual, text, file, line); } //Check two doubles for equality within a tolerance threshold #define DOUBLES_EQUAL(expected, actual, threshold)\ DOUBLES_EQUAL_LOCATION(expected, actual, threshold, NULL, __FILE__, __LINE__) #define DOUBLES_EQUAL_TEXT(expected, actual, threshold, text)\ DOUBLES_EQUAL_LOCATION(expected, actual, threshold, text, __FILE__, __LINE__) #define DOUBLES_EQUAL_LOCATION(expected, actual, threshold, text, file, line)\ { UtestShell::getCurrent()->assertDoublesEqual(expected, actual, threshold, text, file, line); } #define MEMCMP_EQUAL(expected, actual, size)\ MEMCMP_EQUAL_LOCATION(expected, actual, size, NULL, __FILE__, __LINE__) #define MEMCMP_EQUAL_TEXT(expected, actual, size, text)\ MEMCMP_EQUAL_LOCATION(expected, actual, size, text, __FILE__, __LINE__) #define MEMCMP_EQUAL_LOCATION(expected, actual, size, text, file, line)\ { UtestShell::getCurrent()->assertBinaryEqual(expected, actual, size, text, file, line); } #define BITS_EQUAL(expected, actual, mask)\ BITS_LOCATION(expected, actual, mask, NULL, __FILE__, __LINE__) #define BITS_EQUAL_TEXT(expected, actual, mask, text)\ BITS_LOCATION(expected, actual, mask, text, __FILE__, __LINE__) #define BITS_LOCATION(expected, actual, mask, text, file, line)\ { UtestShell::getCurrent()->assertBitsEqual(expected, actual, mask, sizeof(actual), text, file, line); } //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)\ { UtestShell::getCurrent()->fail(text, file, line); } #endif #define FAIL_TEST(text)\ FAIL_TEST_LOCATION(text, __FILE__,__LINE__) #define FAIL_TEST_LOCATION(text, file,line)\ { UtestShell::getCurrent()->fail(text, file, line); } #define TEST_EXIT\ { UtestShell::getCurrent()->exitTest(); } #define UT_PRINT_LOCATION(text, file, line) \ { UtestShell::getCurrent()->print(text, file, line); } #define UT_PRINT(text) \ UT_PRINT_LOCATION(text, __FILE__, __LINE__) #if CPPUTEST_USE_STD_CPP_LIB #define CHECK_THROWS(expected, expression) \ { \ 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(); \ } \ } #endif /* CPPUTEST_USE_STD_CPP_LIB */ #define UT_CRASH() { UtestShell::crash(); } #define RUN_ALL_TESTS(ac, av) CommandLineTestRunner::RunAllTests(ac, av) #endif /*D_UTestMacros_h*/
null
453
cpp
cpputest-stm32-keil-demo
MemoryLeakDetectorNewMacros.h
Middlewares/Third_Party/CPPUTEST/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 #include <new> #include <memory> #include <string> #endif void* operator new(size_t size, const char* file, int line) UT_THROW (std::bad_alloc); void* operator new[](size_t size, const char* file, int line) UT_THROW (std::bad_alloc); void* operator new(size_t size) UT_THROW(std::bad_alloc); void* operator new[](size_t size) UT_THROW(std::bad_alloc); void operator delete(void* mem, const char* file, int line) UT_NOTHROW; void operator delete[](void* mem, const char* file, int line) UT_NOTHROW; void operator delete(void* mem) UT_NOTHROW; void operator delete[](void* mem) UT_NOTHROW; void operator delete (void* mem, size_t size) UT_NOTHROW; void operator delete[] (void* mem, size_t size) UT_NOTHROW; #endif #ifdef __clang__ #pragma clang diagnostic push #if __clang_major__ >= 3 && __clang_minor__ >= 6 #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
null
454
cpp
cpputest-stm32-keil-demo
Utest.h
Middlewares/Third_Party/CPPUTEST/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 _override; virtual ~NormalTestTerminator(); }; class TestTerminatorWithoutExceptions : public TestTerminator { public: virtual void exitCurrentTest() const _override; virtual ~TestTerminatorWithoutExceptions(); }; //////////////////// UtestShell class UtestShell { public: static UtestShell *getCurrent(); public: UtestShell(const char* groupName, const char* testName, const char* fileName, int lineNumber); virtual ~UtestShell(); virtual UtestShell* addTest(UtestShell* test); virtual UtestShell *getNext() const; virtual int countTests(); bool shouldRun(const TestFilter* groupFilters, const TestFilter* nameFilters) const; const SimpleString getName() const; const SimpleString getGroup() const; virtual SimpleString getFormattedName() const; const SimpleString getFile() const; int getLineNumber() const; virtual bool willRun() const; virtual bool hasFailed() const; void countCheck(); virtual void assertTrue(bool condition, const char *checkString, const char *conditionString, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertCstrEqual(const char *expected, const char *actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertCstrNEqual(const char *expected, const char *actual, size_t length, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertCstrNoCaseEqual(const char *expected, const char *actual, const char* text, const char *fileName, int lineNumber); virtual void assertCstrContains(const char *expected, const char *actual, const char* text, const char *fileName, int lineNumber); virtual void assertCstrNoCaseContains(const char *expected, const char *actual, const char* text, const char *fileName, int lineNumber); virtual void assertLongsEqual(long expected, long actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertUnsignedLongsEqual(unsigned long expected, unsigned long actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertLongLongsEqual(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertUnsignedLongLongsEqual(cpputest_ulonglong expected, cpputest_ulonglong actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertSignedBytesEqual(signed char expected, signed char actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertPointersEqual(const void *expected, const void *actual, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertFunctionPointersEqual(void (*expected)(), void (*actual)(), const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertDoublesEqual(double expected, double actual, double threshold, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertEquals(bool failed, const char* expected, const char* actual, const char* text, const char* file, int line, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertBinaryEqual(const void *expected, const void *actual, size_t length, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void assertBitsEqual(unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void fail(const char *text, const char *fileName, int lineNumber, const TestTerminator& testTerminator = NormalTestTerminator()); virtual void exitTest(const TestTerminator& testTerminator = NormalTestTerminator()); virtual void print(const char *text, const char *fileName, int lineNumber); virtual void print(const SimpleString & text, const char *fileName, int lineNumber); void setFileName(const char *fileName); void setLineNumber(int 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); protected: UtestShell(); UtestShell(const char *groupName, const char *testName, const char *fileName, int lineNumber, UtestShell *nextTest); virtual SimpleString getMacroName() const; TestResult *getTestResult(); private: const char *group_; const char *name_; const char *file_; int 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_; }; //////////////////// ExecFunctionTest class ExecFunctionTestShell; class ExecFunctionTest : public Utest { public: ExecFunctionTest(ExecFunctionTestShell* shell); void testBody() _override; virtual void setup() _override; virtual void teardown() _override; private: ExecFunctionTestShell* shell_; }; //////////////////// ExecFunctionTestShell class ExecFunctionTestShell: public UtestShell { public: void (*setup_)(); void (*teardown_)(); void (*testFunction_)(); ExecFunctionTestShell(void(*set)() = 0, void(*tear)() = 0) : UtestShell("Generic", "Generic", "Generic", 1), setup_(set), teardown_( tear), testFunction_(0) { } Utest* createTest() { return new ExecFunctionTest(this); } virtual ~ExecFunctionTestShell(); }; //////////////////// CppUTestFailedException class CppUTestFailedException { public: int dummy_; }; //////////////////// IgnoredTest class IgnoredUtestShell : public UtestShell { public: IgnoredUtestShell(); virtual ~IgnoredUtestShell(); explicit IgnoredUtestShell(const char* groupName, const char* testName, const char* fileName, int lineNumber); virtual bool willRun() const _override; virtual void setRunIgnored() _override; protected: virtual SimpleString getMacroName() const _override; virtual void runOneTest(TestPlugin* plugin, TestResult& result) _override; private: IgnoredUtestShell(const IgnoredUtestShell&); IgnoredUtestShell& operator=(const IgnoredUtestShell&); bool runIgnored_; }; //////////////////// TestInstaller class TestInstaller { public: explicit TestInstaller(UtestShell& shell, const char* groupName, const char* testName, const char* fileName, int lineNumber); virtual ~TestInstaller(); void unDo(); private: TestInstaller(const TestInstaller&); TestInstaller& operator=(const TestInstaller&); }; #endif
null
455
cpp
cpputest-stm32-keil-demo
TestMemoryAllocator.h
Middlewares/Third_Party/CPPUTEST/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 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, int line); virtual void free_memory(char* memory, const char* file, int line); virtual const char* name(); virtual const char* alloc_name(); virtual const char* free_name(); virtual bool isOfEqualType(TestMemoryAllocator* allocator); virtual char* allocMemoryLeakNode(size_t size); virtual void freeMemoryLeakNode(char* memory); protected: const char* name_; const char* alloc_name_; const char* free_name_; bool hasBeenDestroyed_; }; class CrashOnAllocationAllocator : public TestMemoryAllocator { unsigned allocationToCrashOn_; public: CrashOnAllocationAllocator(); virtual void setNumberToCrashOn(unsigned allocationToCrashOn); virtual char* alloc_memory(size_t size, const char* file, int line) _override; }; class NullUnknownAllocator: public TestMemoryAllocator { public: NullUnknownAllocator(); virtual char* alloc_memory(size_t size, const char* file, int line) _override; virtual void free_memory(char* memory, const char* file, int line) _override; 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 char* alloc_memory(size_t size, const char* file, int line); virtual char* allocMemoryLeakNode(size_t size); virtual void failAllocNumber(int number); virtual void failNthAllocAt(int allocationNumber, const char* file, int line); virtual void checkAllFailedAllocsWereDone(); virtual void clearFailedAllocs(); protected: LocationToFailAllocNode* head_; int currentAllocNumber_; }; #endif
null
456
cpp
cpputest-stm32-keil-demo
TestFilter.h
Middlewares/Third_Party/CPPUTEST/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
457
cpp
cpputest-stm32-keil-demo
CppUTestConfig.h
Middlewares/Third_Party/CPPUTEST/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 #include "CppUTestGeneratedConfig.h" #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. * */ #ifdef __clang__ #pragma clang diagnostic push #if __clang_major__ >= 3 && __clang_minor__ >= 6 #pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #endif /* * Lib C dependencies that are currently still left: * * 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 __no_return__ macro, which is used to flag a function as not returning. * Used for functions that always throws for instance. * * This is needed for compiling with clang, without breaking other compilers. */ #ifndef __has_attribute #define __has_attribute(x) 0 #endif #if __has_attribute(noreturn) #define __no_return__ __attribute__((noreturn)) #else #define __no_return__ #endif #if __has_attribute(format) #define __check_format__(type, format_parameter, other_parameters) __attribute__ ((format (type, format_parameter, other_parameters))) #else #define __check_format__(type, format_parameter, other_parameters) /* type, format_parameter, other_parameters */ #endif /* * When we don't link Standard C++, then we won't throw exceptions as we assume the compiler might not support that! */ #if CPPUTEST_USE_STD_CPP_LIB #if defined(__cplusplus) && __cplusplus >= 201103L #define UT_THROW(exception) #define UT_NOTHROW noexcept #else #define UT_THROW(exception) throw (exception) #define UT_NOTHROW throw() #endif #else #define UT_THROW(exception) #ifdef __clang__ #define UT_NOTHROW throw() #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 #if defined(__cplusplus) && __cplusplus >= 201103L #define DEFAULT_COPY_CONSTRUCTOR(classname) classname(const classname &) = default; #else #define DEFAULT_COPY_CONSTRUCTOR(classname) #endif /* * g++-4.7 with stdc++11 enabled On MacOSX! will have a different exception specifier for operator new (and thank you!) * I assume they'll fix this in the future, but for now, we'll change that here. * (This should perhaps also be done in the configure.ac) */ #ifdef __GXX_EXPERIMENTAL_CXX0X__ #ifdef __APPLE__ #ifdef _GLIBCXX_THROW #undef UT_THROW #define UT_THROW(exception) _GLIBCXX_THROW(exception) #endif #endif #endif /* * Handling of IEEE754 floating point exceptions via fenv.h * Works on non-Visual C++ compilers and Visual C++ 2008 and newer */ #if CPPUTEST_USE_STD_C_LIB && (!defined(_MSC_VER) || (_MSC_VER >= 1800)) #define CPPUTEST_HAVE_FENV #if defined(__WATCOMC__) #define CPPUTEST_FENV_IS_WORKING_PROPERLY 0 #else #define CPPUTEST_FENV_IS_WORKING_PROPERLY 1 #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), use default of 8 when building without Std C library. */ #if CPPUTEST_USE_STD_C_LIB #define CPPUTEST_CHAR_BIT CHAR_BIT #else #define CPPUTEST_CHAR_BIT 8 #endif /* * Support for "long long" type. * * Not supported when CPUTEST_LONG_LONG_DISABLED is set. * Can be overridden by using CPPUTEST_USE_LONG_LONG * * CPPUTEST_HAVE_LONG_LONG_INT is set by configure * LLONG_MAX is set in limits.h. This is a crude attempt to detect long long support when no configure is used * */ #if !defined(CPPUTEST_LONG_LONG_DISABLED) && !defined(CPPUTEST_USE_LONG_LONG) #if defined(CPPUTEST_HAVE_LONG_LONG_INT) || defined(LLONG_MAX) #define CPPUTEST_USE_LONG_LONG 1 #endif #endif #ifdef 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 struct cpputest_longlong { #if defined(__cplusplus) cpputest_longlong() {} cpputest_longlong(int) {} #endif char dummy[CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE]; }; struct cpputest_ulonglong { #if defined(__cplusplus) cpputest_ulonglong() {} cpputest_ulonglong(int) {} #endif char dummy[CPPUTEST_SIZE_OF_FAKE_LONG_LONG_TYPE]; }; #endif /* Visual C++ 10.0+ (2010+) supports the override keyword, but doesn't define the C++ version as C++11 */ #if defined(__cplusplus) && ((__cplusplus >= 201103L) || (defined(_MSC_VER) && (_MSC_VER >= 1600))) #define CPPUTEST_COMPILER_FULLY_SUPPORTS_CXX11 #define _override override #else #define _override #endif /* MinGW-w64 prefers to act like Visual C++, but we want the ANSI behaviors instead */ #undef __USE_MINGW_ANSI_STDIO #define __USE_MINGW_ANSI_STDIO 1 #ifdef __clang__ #pragma clang diagnostic pop #endif #endif
null
458
cpp
cpputest-stm32-keil-demo
TestHarness_c.h
Middlewares/Third_Party/CPPUTEST/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_INT(expected,actual) \ CHECK_EQUAL_C_INT_LOCATION(expected,actual,__FILE__,__LINE__) #define CHECK_EQUAL_C_REAL(expected,actual,threshold) \ CHECK_EQUAL_C_REAL_LOCATION(expected,actual,threshold,__FILE__,__LINE__) #define CHECK_EQUAL_C_CHAR(expected,actual) \ CHECK_EQUAL_C_CHAR_LOCATION(expected,actual,__FILE__,__LINE__) #define CHECK_EQUAL_C_UBYTE(expected,actual) \ CHECK_EQUAL_C_UBYTE_LOCATION(expected,actual,__FILE__,__LINE__) #define CHECK_EQUAL_C_SBYTE(expected,actual) \ CHECK_EQUAL_C_SBYTE_LOCATION(expected,actual,__FILE__,__LINE__) #define CHECK_EQUAL_C_STRING(expected,actual) \ CHECK_EQUAL_C_STRING_LOCATION(expected,actual,__FILE__,__LINE__) #define CHECK_EQUAL_C_POINTER(expected,actual) \ CHECK_EQUAL_C_POINTER_LOCATION(expected,actual,__FILE__,__LINE__) #define CHECK_EQUAL_C_BITS(expected, actual, mask)\ CHECK_EQUAL_C_BITS_LOCATION(expected, actual, mask, sizeof(actual), __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, __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() #define TEST_GROUP_C_TEARDOWN(group_name) \ extern void group_##group_name##_teardown_wrapper_c(void); \ void group_##group_name##_teardown_wrapper_c() #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() /* 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() { \ group_##group_name##_setup_wrapper_c(); \ } #define TEST_GROUP_C_TEARDOWN_WRAPPER(group_name) \ void teardown() { \ 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(); \ } #ifdef __cplusplus extern "C" { #endif /* CHECKS that can be used from C code */ extern void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, const char* fileName, int lineNumber); extern void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* fileName, int lineNumber); extern void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* fileName, int lineNumber); extern void CHECK_EQUAL_C_UBYTE_LOCATION(unsigned char expected, unsigned char actual, const char* fileName, int lineNumber); extern void CHECK_EQUAL_C_SBYTE_LOCATION(signed char expected, signed char actual, const char* fileName, int lineNumber); extern void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* fileName, int lineNumber); extern void CHECK_EQUAL_C_POINTER_LOCATION(const void* expected, const void* actual, const char* fileName, int lineNumber); extern void CHECK_EQUAL_C_BITS_LOCATION(unsigned int expected, unsigned int actual, unsigned int mask, size_t size, const char* fileName, int lineNumber); extern void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, int lineNumber); extern void FAIL_C_LOCATION(const char* fileName, int lineNumber); extern void CHECK_C_LOCATION(int condition, const char* conditionString, const char* fileName, int lineNumber); extern void* cpputest_malloc(size_t size); extern void* cpputest_calloc(size_t num, size_t size); extern void* cpputest_realloc(void* ptr, size_t size); extern void cpputest_free(void* buffer); extern void* cpputest_malloc_location(size_t size, const char* file, int line); extern void* cpputest_calloc_location(size_t num, size_t size, const char* file, int line); extern void* cpputest_realloc_location(void* memory, size_t size, const char* file, int line); extern void cpputest_free_location(void* buffer, const char* file, int line); 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__) # define PUNUSED(x) PUNUSED_ ##x __attribute__((unused)) #else # define PUNUSED(x) x #endif #endif #endif
null
459
cpp
cpputest-stm32-keil-demo
TestOutput.h
Middlewares/Third_Party/CPPUTEST/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: 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(); virtual void color(); virtual void printBuffer(const char*)=0; virtual void print(const char*); virtual void print(long); virtual void printDouble(double); virtual void printFailure(const TestFailure& failure); virtual void printTestRun(int number, int total); virtual void setProgressIndicator(const char*); virtual void flush()=0; enum WorkingEnvironment {visualStudio, eclipse, detectEnvironment}; static void setWorkingEnvironment(WorkingEnvironment workEnvironment); static WorkingEnvironment getWorkingEnvironment(); protected: virtual void printEclipseErrorInFileOnLine(SimpleString file, int lineNumber); virtual void printVisualStudioErrorInFileOnLine(SimpleString file, int lineNumber); virtual void printProgressIndicator(); void printFileAndLineForTestAndFailure(const TestFailure& failure); void printFileAndLineForFailure(const TestFailure& failure); void printFailureInTest(SimpleString testName); void printFailureMessage(SimpleString reason); void printErrorInFileOnLineFormattedForWorkingEnvironment(SimpleString testFile, int lineNumber); TestOutput(const TestOutput&); TestOutput& operator=(const TestOutput&); int dotCount_; bool 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() { } virtual void printBuffer(const char* s) _override; virtual void flush() _override; private: ConsoleTestOutput(const ConsoleTestOutput&); ConsoleTestOutput& operator=(const ConsoleTestOutput&); }; /////////////////////////////////////////////////////////////////////////////// // // StringBufferTestOutput.h // // TestOutput for test purposes // /////////////////////////////////////////////////////////////////////////////// class StringBufferTestOutput: public TestOutput { public: explicit StringBufferTestOutput() { } virtual ~StringBufferTestOutput(); void printBuffer(const char* s) _override { output += s; } void flush() _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(); 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(); virtual void color(); virtual void printBuffer(const char*); virtual void print(const char*); virtual void print(long); virtual void printDouble(double); virtual void printFailure(const TestFailure& failure); virtual void setProgressIndicator(const char*); virtual void flush(); protected: CompositeTestOutput(const TestOutput&); CompositeTestOutput& operator=(const TestOutput&); private: TestOutput* outputOne_; TestOutput* outputTwo_; }; #endif
null
460
cpp
cpputest-stm32-keil-demo
TestRegistry.h
Middlewares/Third_Party/CPPUTEST/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 "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 int countTests(); virtual void runAllTests(TestResult& result); virtual void listTestGroupNames(TestResult& result); virtual void listTestGroupAndCaseNames(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
461
cpp
cpputest-stm32-keil-demo
TeamCityTestOutput.h
Middlewares/Third_Party/CPPUTEST/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); virtual void printCurrentTestStarted(const UtestShell& test) _override; virtual void printCurrentTestEnded(const TestResult& res) _override; virtual void printCurrentGroupStarted(const UtestShell& test) _override; virtual void printCurrentGroupEnded(const TestResult& res) _override; virtual void printFailure(const TestFailure& failure) _override; protected: private: void printEscaped(const char* s); const UtestShell *currtest_; SimpleString currGroup_; }; #endif
null
462
cpp
cpputest-stm32-keil-demo
SimpleString.h
Middlewares/Third_Party/CPPUTEST/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; 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 int StrCmp(const char* s1, const char* s2); static size_t StrLen(const char*); static int StrNCmp(const char* s1, const char* s2, size_t n); static char* StrNCpy(char* s1, const char* s2, size_t n); static char* StrStr(const char* s1, const char* s2); static char ToLower(char ch); static int MemCmp(const void* s1, const void *s2, size_t n); static char* allocStringBuffer(size_t size, const char* file, int line); static void deallocStringBuffer(char* str, const char* file, int line); private: char *buffer_; static TestMemoryAllocator* stringAllocator_; char* getEmptyString() const; static char* copyToNewBuffer(const char* bufferToCopy, size_t bufferSize=0); static bool isDigit(char ch); static bool isSpace(char ch); static bool isUpper(char ch); }; 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&); }; 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(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, ...) __check_format__(printf, 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); #if CPPUTEST_USE_STD_CPP_LIB #include <string> SimpleString StringFrom(const std::string& other); #endif #endif
null
463
cpp
cpputest-stm32-keil-demo
MemoryLeakDetector.h
Middlewares/Third_Party/CPPUTEST/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, ...) __check_format__(printf, 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, int freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); void reportMemoryCorruptionFailure(MemoryLeakDetectorNode* node, const char* freeFile, int freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); void reportAllocationDeallocationMismatchFailure(MemoryLeakDetectorNode* node, const char* freeFile, int freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); char* toString(); private: void addAllocationLocation(const char* allocationFile, int allocationLineNumber, size_t allocationSize, TestMemoryAllocator* allocator); void addDeallocationLocation(const char* freeFile, int freeLineNumber, TestMemoryAllocator* allocator); void addMemoryLeakHeader(); void addMemoryLeakFooter(int totalAmountOfLeaks); void addWarningForUsingMalloc(); void addNoMemoryLeaksMessage(); void addErrorMessageForTooMuchLeaks(); private: int total_leaks_; bool giveWarningOnUsingMalloc_; void reportFailure(const char* message, const char* allocFile, int allocLine, size_t allocSize, TestMemoryAllocator* allocAllocator, const char* freeFile, int freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter); SimpleStringBuffer outputBuffer_; }; struct MemoryLeakDetectorNode { MemoryLeakDetectorNode() : size_(0), number_(0), memory_(0), file_(0), line_(0), allocator_(0), period_(mem_leak_period_enabled), next_(0) { } void init(char* memory, unsigned number, size_t size, TestMemoryAllocator* allocator, MemLeakPeriod period, const char* file, int line); size_t size_; unsigned number_; char* memory_; const char* file_; int line_; TestMemoryAllocator* allocator_; MemLeakPeriod period_; private: friend struct MemoryLeakDetectorList; MemoryLeakDetectorNode* next_; }; struct MemoryLeakDetectorList { MemoryLeakDetectorList() : head_(0) {} void addNewNode(MemoryLeakDetectorNode* node); MemoryLeakDetectorNode* retrieveNode(char* memory); MemoryLeakDetectorNode* removeNode(char* memory); MemoryLeakDetectorNode* getFirstLeak(MemLeakPeriod period); MemoryLeakDetectorNode* getNextLeak(MemoryLeakDetectorNode* node, MemLeakPeriod period); MemoryLeakDetectorNode* getLeakFrom(MemoryLeakDetectorNode* node, MemLeakPeriod period); int getTotalLeaks(MemLeakPeriod period); void clearAllAccounting(MemLeakPeriod period); bool isInPeriod(MemoryLeakDetectorNode* node, MemLeakPeriod period); private: MemoryLeakDetectorNode* head_; }; struct MemoryLeakDetectorTable { void clearAllAccounting(MemLeakPeriod period); void addNewNode(MemoryLeakDetectorNode* node); MemoryLeakDetectorNode* retrieveNode(char* memory); MemoryLeakDetectorNode* removeNode(char* memory); int getTotalLeaks(MemLeakPeriod period); MemoryLeakDetectorNode* getFirstLeak(MemLeakPeriod period); MemoryLeakDetectorNode* getNextLeak(MemoryLeakDetectorNode* leak, MemLeakPeriod period); 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(); const char* report(MemLeakPeriod period); void markCheckingPeriodLeaksAsNonCheckingPeriod(); int totalMemoryLeaks(MemLeakPeriod period); void clearAllAccounting(MemLeakPeriod period); char* allocMemory(TestMemoryAllocator* allocator, size_t size, bool allocatNodesSeperately = false); char* allocMemory(TestMemoryAllocator* allocator, size_t size, const char* file, int line, bool allocatNodesSeperately = false); void deallocMemory(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately = false); void deallocMemory(TestMemoryAllocator* allocator, void* memory, const char* file, int line, bool allocatNodesSeperately = false); char* reallocMemory(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately = false); void invalidateMemory(char* memory); void removeMemoryLeakInformationWithoutCheckingOrDeallocatingTheMemoryButDeallocatingTheAccountInformation(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately); enum { memory_corruption_buffer_size = 3 }; unsigned getCurrentAllocationNumber(); SimpleMutex* getMutex(void); private: MemoryLeakFailure* reporter_; MemLeakPeriod current_period_; MemoryLeakOutputStringBuffer outputBuffer_; MemoryLeakDetectorTable memoryTable_; bool doAllocationTypeChecking_; unsigned allocationSequenceNumber_; SimpleMutex* mutex_; char* allocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, size_t size, const char* file, int line, bool allocatNodesSeperately); char* reallocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately); MemoryLeakDetectorNode* createMemoryLeakAccountingInformation(TestMemoryAllocator* allocator, size_t size, char* memory, bool allocatNodesSeperately); bool validMemoryCorruptionInformation(char* memory); bool matchingAllocation(TestMemoryAllocator *alloc_allocator, TestMemoryAllocator *free_allocator); void storeLeakInformation(MemoryLeakDetectorNode * node, char *new_memory, size_t size, TestMemoryAllocator *allocator, const char *file, int line); void ConstructMemoryLeakReport(MemLeakPeriod period); size_t sizeOfMemoryWithCorruptionInfo(size_t size); MemoryLeakDetectorNode* getNodeFromMemoryPointer(char* memory, size_t size); char* reallocateMemoryAndLeakInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately); void addMemoryCorruptionInformation(char* memory); void checkForCorruption(MemoryLeakDetectorNode* node, const char* file, int line, TestMemoryAllocator* allocator, bool allocateNodesSeperately); }; #endif
null
464
cpp
cpputest-stm32-keil-demo
CppUTestGeneratedConfig.h
Middlewares/Third_Party/CPPUTEST/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
465
cpp
cpputest-stm32-keil-demo
GTestConvertor.h
Middlewares/Third_Party/CPPUTEST/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() _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 fromt he 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
466
cpp
cpputest-stm32-keil-demo
IEEE754ExceptionsPlugin.h
Middlewares/Third_Party/CPPUTEST/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) _override; virtual void postTestAction(UtestShell& test, TestResult& result) _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
467
cpp
cpputest-stm32-keil-demo
MockCheckedExpectedCall.h
Middlewares/Third_Party/CPPUTEST/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(); virtual ~MockCheckedExpectedCall(); virtual MockExpectedCall& withName(const SimpleString& name) _override; virtual MockExpectedCall& withCallOrder(int callOrder) _override; virtual MockExpectedCall& withBoolParameter(const SimpleString& name, bool value) _override; virtual MockExpectedCall& withIntParameter(const SimpleString& name, int value) _override; virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) _override; virtual MockExpectedCall& withLongIntParameter(const SimpleString& name, long int value) _override; virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) _override; virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value) _override; virtual MockExpectedCall& withStringParameter(const SimpleString& name, const char* value) _override; virtual MockExpectedCall& withPointerParameter(const SimpleString& name, void* value) _override; virtual MockExpectedCall& withConstPointerParameter(const SimpleString& name, const void* value) _override; virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) _override; virtual MockExpectedCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) _override; virtual MockExpectedCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value) _override; virtual MockExpectedCall& withOutputParameterReturning(const SimpleString& name, const void* value, size_t size) _override; virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString& typeName, const SimpleString& name, const void* value) _override; virtual MockExpectedCall& ignoreOtherParameters() _override; virtual MockExpectedCall& andReturnValue(bool value) _override; virtual MockExpectedCall& andReturnValue(int value) _override; virtual MockExpectedCall& andReturnValue(unsigned int value) _override; virtual MockExpectedCall& andReturnValue(long int value) _override; virtual MockExpectedCall& andReturnValue(unsigned long int value) _override; virtual MockExpectedCall& andReturnValue(double value) _override; virtual MockExpectedCall& andReturnValue(const char* value) _override; virtual MockExpectedCall& andReturnValue(void* value) _override; virtual MockExpectedCall& andReturnValue(const void* value) _override; virtual MockExpectedCall& andReturnValue(void (*value)()) _override; virtual MockNamedValue returnValue(); virtual MockExpectedCall& onObject(void* objectPtr) _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 isFulfilledWithoutIgnoredParameters(); virtual bool areParametersFulfilled(); virtual bool areIgnoredParametersFulfilled(); virtual bool isOutOfOrder() const; virtual void callWasMade(int callOrder); virtual void inputParameterWasPassed(const SimpleString& name); virtual void outputParameterWasPassed(const SimpleString& name); virtual void parametersWereIgnored(); virtual void wasPassedToObject(); virtual void resetExpectation(); virtual SimpleString callToString(); virtual SimpleString missingParametersToString(); enum { NOT_CALLED_YET = -1, NO_EXPECTED_CALL_ORDER = -1}; virtual int getCallOrder() const; protected: void setName(const SimpleString& name); SimpleString getName() const; private: SimpleString functionName_; class MockExpectedFunctionParameter : public MockNamedValue { public: MockExpectedFunctionParameter(const SimpleString& name); void setFulfilled(bool b); bool isFulfilled() const; private: bool fulfilled_; }; MockExpectedFunctionParameter* item(MockNamedValueListNode* node); bool ignoreOtherParameters_; bool parametersWereIgnored_; int callOrder_; int expectedCallOrder_; bool outOfOrder_; MockNamedValueList* inputParameters_; MockNamedValueList* outputParameters_; MockNamedValue returnValue_; void* objectPtr_; bool wasPassedToObject_; }; struct MockExpectedCallCompositeNode; class MockExpectedCallComposite : public MockExpectedCall { public: MockExpectedCallComposite(); virtual ~MockExpectedCallComposite(); virtual MockExpectedCall& withName(const SimpleString& name) _override; virtual MockExpectedCall& withCallOrder(int callOrder) _override; virtual MockExpectedCall& withBoolParameter(const SimpleString& name, bool value) _override; virtual MockExpectedCall& withIntParameter(const SimpleString& name, int value) _override; virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) _override; virtual MockExpectedCall& withLongIntParameter(const SimpleString& name, long int value) _override; virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) _override; virtual MockExpectedCall& withDoubleParameter(const SimpleString& name, double value) _override; virtual MockExpectedCall& withStringParameter(const SimpleString& name, const char* value) _override; virtual MockExpectedCall& withConstPointerParameter(const SimpleString& name, const void* value) _override; virtual MockExpectedCall& withPointerParameter(const SimpleString& name, void* value) _override; virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) _override; virtual MockExpectedCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) _override; virtual MockExpectedCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value) _override; virtual MockExpectedCall& withOutputParameterReturning(const SimpleString& name, const void* value, size_t size) _override; virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString& typeName, const SimpleString& name, const void* value) _override; virtual MockExpectedCall& ignoreOtherParameters() _override; virtual MockExpectedCall& andReturnValue(bool value) _override; virtual MockExpectedCall& andReturnValue(int value) _override; virtual MockExpectedCall& andReturnValue(unsigned int value) _override; virtual MockExpectedCall& andReturnValue(long int value) _override; virtual MockExpectedCall& andReturnValue(unsigned long int value) _override; virtual MockExpectedCall& andReturnValue(double value) _override; virtual MockExpectedCall& andReturnValue(const char* value) _override; virtual MockExpectedCall& andReturnValue(void* value) _override; virtual MockExpectedCall& andReturnValue(const void* value) _override; virtual MockExpectedCall& andReturnValue(void (*value)()) _override; virtual MockExpectedCall& onObject(void* objectPtr) _override; virtual void add(MockExpectedCall& call); virtual void clear(); private: MockExpectedCallCompositeNode* head_; }; class MockIgnoredExpectedCall: public MockExpectedCall { public: virtual MockExpectedCall& withName(const SimpleString&) _override { return *this;} virtual MockExpectedCall& withCallOrder(int) _override { return *this; } virtual MockExpectedCall& withBoolParameter(const SimpleString&, bool) _override { return *this; } virtual MockExpectedCall& withIntParameter(const SimpleString&, int) _override { return *this; } virtual MockExpectedCall& withUnsignedIntParameter(const SimpleString&, unsigned int) _override{ return *this; } virtual MockExpectedCall& withLongIntParameter(const SimpleString&, long int) _override { return *this; } virtual MockExpectedCall& withUnsignedLongIntParameter(const SimpleString&, unsigned long int) _override { return *this; } virtual MockExpectedCall& withDoubleParameter(const SimpleString&, double) _override { return *this; } virtual MockExpectedCall& withStringParameter(const SimpleString&, const char*) _override { return *this; } virtual MockExpectedCall& withPointerParameter(const SimpleString& , void*) _override { return *this; } virtual MockExpectedCall& withConstPointerParameter(const SimpleString& , const void*) _override { return *this; } virtual MockExpectedCall& withFunctionPointerParameter(const SimpleString& , void(*)()) _override { return *this; } virtual MockExpectedCall& withMemoryBufferParameter(const SimpleString&, const unsigned char*, size_t) _override { return *this; } virtual MockExpectedCall& withParameterOfType(const SimpleString&, const SimpleString&, const void*) _override { return *this; } virtual MockExpectedCall& withOutputParameterReturning(const SimpleString&, const void*, size_t) _override { return *this; } virtual MockExpectedCall& withOutputParameterOfTypeReturning(const SimpleString&, const SimpleString&, const void*) _override { return *this; } virtual MockExpectedCall& ignoreOtherParameters() _override { return *this;} virtual MockExpectedCall& andReturnValue(bool) _override { return *this; } virtual MockExpectedCall& andReturnValue(int) _override { return *this; } virtual MockExpectedCall& andReturnValue(unsigned int) _override { return *this; } virtual MockExpectedCall& andReturnValue(long int) _override { return *this; } virtual MockExpectedCall& andReturnValue(unsigned long int) _override { return *this; } virtual MockExpectedCall& andReturnValue(double) _override { return *this;} virtual MockExpectedCall& andReturnValue(const char*) _override { return *this; } virtual MockExpectedCall& andReturnValue(void*) _override { return *this; } virtual MockExpectedCall& andReturnValue(const void*) _override { return *this; } virtual MockExpectedCall& andReturnValue(void (*)()) _override { return *this; } virtual MockExpectedCall& onObject(void*) _override { return *this; } static MockExpectedCall& instance(); }; #endif
null
468
cpp
cpputest-stm32-keil-demo
MockSupport_c.h
Middlewares/Third_Party/CPPUTEST/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/StandardCLibrary.h" typedef enum { MOCKVALUETYPE_BOOL, MOCKVALUETYPE_UNSIGNED_INTEGER, MOCKVALUETYPE_INTEGER, MOCKVALUETYPE_LONG_INTEGER, MOCKVALUETYPE_UNSIGNED_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; double doubleValue; const char* stringValue; void* pointerValue; const void* constPointerValue; void (*functionPointerValue)(void); const unsigned char* memoryBufferValue; const void* objectValue; } 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* (*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); 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* (*withDoubleParameters)(const char* name, double value); 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* (*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* (*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)(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); 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); 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
469
cpp
cpputest-stm32-keil-demo
MemoryReportFormatter.h
Middlewares/Third_Party/CPPUTEST/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, int line)=0; virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, int line)=0; }; class NormalMemoryReportFormatter : public MemoryReportFormatter { public: NormalMemoryReportFormatter(); virtual ~NormalMemoryReportFormatter(); virtual void report_testgroup_start(TestResult* /*result*/, UtestShell& /*test*/) _override; virtual void report_testgroup_end(TestResult* /*result*/, UtestShell& /*test*/) _override {} // LCOV_EXCL_LINE virtual void report_test_start(TestResult* result, UtestShell& test) _override; virtual void report_test_end(TestResult* result, UtestShell& test) _override; virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, int line) _override; virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, int line) _override; }; #endif
null
470
cpp
cpputest-stm32-keil-demo
GTest.h
Middlewares/Third_Party/CPPUTEST/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 RUN_ALL_TESTS #include "gtest/gtest.h" #ifdef CPPUTEST_USE_NEW_MACROS #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif #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
471
cpp
cpputest-stm32-keil-demo
GMock.h
Middlewares/Third_Party/CPPUTEST/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 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 #endif
null
472
cpp
cpputest-stm32-keil-demo
MockActualCall.h
Middlewares/Third_Party/CPPUTEST/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/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(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, 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& 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 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
473
cpp
cpputest-stm32-keil-demo
MemoryReportAllocator.h
Middlewares/Third_Party/CPPUTEST/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(); 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, int line) _override; virtual void free_memory(char* memory, const char* file, int line) _override; virtual const char* name() _override; virtual const char* alloc_name() _override; virtual const char* free_name() _override; }; #endif
null
474
cpp
cpputest-stm32-keil-demo
MockNamedValue.h
Middlewares/Third_Party/CPPUTEST/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 /* * 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) _override { return equal_(object1, object2); } virtual SimpleString valueToString(const void* object) _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) _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(double value); virtual void setValue(void* value); virtual void setValue(const void* value); virtual void setValue(void (*value)()); virtual void setValue(const char* value); virtual void setMemoryBuffer(const unsigned char* value, size_t size); virtual void setObjectPointer(const SimpleString& type, const void* objectPtr); virtual void 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 double getDoubleValue() const; virtual const char* getStringValue() const; virtual void* getPointerValue() const; virtual const void* getConstPointerValue() const; virtual void (*getFunctionPointerValue() const)(); virtual const unsigned char* getMemoryBuffer() const; virtual const void* getObjectPointer() const; virtual size_t getSize() const; virtual MockNamedValueComparator* getComparator() const; virtual MockNamedValueCopier* getCopier() const; static void setDefaultComparatorsAndCopiersRepository(MockNamedValueComparatorsAndCopiersRepository* repository); private: SimpleString name_; SimpleString type_; union { bool boolValue_; int intValue_; unsigned int unsignedIntValue_; long int longIntValue_; unsigned long int unsignedLongIntValue_; double doubleValue_; const char* stringValue_; void* pointerValue_; const void* constPointerValue_; void (*functionPointerValue_)(); const unsigned char* memoryBufferValue_; const 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
475
cpp
cpputest-stm32-keil-demo
OrderedTest.h
Middlewares/Third_Party/CPPUTEST/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(); virtual OrderedTestShell* addOrderedTest(OrderedTestShell* test); virtual OrderedTestShell* getNextOrderedTest(); int getLevel(); void setLevel(int level); static void addOrderedTestToHead(OrderedTestShell* test); static OrderedTestShell* getOrderedTestHead(); static bool firstOrderedTest(); static void setOrderedTestHead(OrderedTestShell* test); private: static OrderedTestShell* _orderedTestsHead; OrderedTestShell* _nextOrderedTest; int _level; }; class OrderedTestInstaller { public: explicit OrderedTestInstaller(OrderedTestShell& test, const char* groupName, const char* testName, const char* fileName, int lineNumber, int level); virtual ~OrderedTestInstaller(); private: void addOrderedTestInOrder(OrderedTestShell* test); void addOrderedTestInOrderNotAtHeadPosition(OrderedTestShell* test); }; #define TEST_ORDERED(testGroup, testName, testLevel) \ /* declarations for compilers */ \ class TEST_##testGroup##_##testName##_TestShell; \ extern TEST_##testGroup##_##testName##_TestShell TEST_##testGroup##_##testName##_Instance; \ class TEST_##testGroup##_##testName##_Test : public TEST_GROUP_##CppUTestGroup##testGroup \ { public: TEST_##testGroup##_##testName##_Test () : TEST_GROUP_##CppUTestGroup##testGroup () {} \ void testBody(); }; \ class TEST_##testGroup##_##testName##_TestShell : public OrderedTestShell { \ virtual Utest* createTest() _override { return new TEST_##testGroup##_##testName##_Test; } \ } TEST_##testGroup##_##testName##_Instance; \ static OrderedTestInstaller TEST_##testGroup##_##testName##_Installer(TEST_##testGroup##_##testName##_Instance, #testGroup, #testName, __FILE__,__LINE__, testLevel); \ void TEST_##testGroup##_##testName##_Test::testBody() #endif
null
476
cpp
cpputest-stm32-keil-demo
CodeMemoryReportFormatter.h
Middlewares/Third_Party/CPPUTEST/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(); virtual void report_testgroup_start(TestResult* result, UtestShell& test) _override; virtual void report_testgroup_end(TestResult* /*result*/, UtestShell& /*test*/) _override {} // LCOV_EXCL_LINE virtual void report_test_start(TestResult* result, UtestShell& test) _override; virtual void report_test_end(TestResult* result, UtestShell& test) _override; virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, int line) _override; virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, int line) _override; 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, int line); SimpleString getAllocationString(TestMemoryAllocator* allocator, const SimpleString& variableName, size_t size); SimpleString getDeallocationString(TestMemoryAllocator* allocator, const SimpleString& variableName, const char* file, int line); }; #endif
null
477
cpp
cpputest-stm32-keil-demo
MockCheckedActualCall.h
Middlewares/Third_Party/CPPUTEST/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(int callOrder, MockFailureReporter* reporter, const MockExpectedCallsList& expectations); virtual ~MockCheckedActualCall(); virtual MockActualCall& withName(const SimpleString& name) _override; virtual MockActualCall& withCallOrder(int) _override; virtual MockActualCall& withBoolParameter(const SimpleString& name, bool value) _override; virtual MockActualCall& withIntParameter(const SimpleString& name, int value) _override; virtual MockActualCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) _override; virtual MockActualCall& withLongIntParameter(const SimpleString& name, long int value) _override; virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) _override; virtual MockActualCall& withDoubleParameter(const SimpleString& name, double value) _override; virtual MockActualCall& withStringParameter(const SimpleString& name, const char* value) _override; virtual MockActualCall& withPointerParameter(const SimpleString& name, void* value) _override; virtual MockActualCall& withConstPointerParameter(const SimpleString& name, const void* value) _override; virtual MockActualCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) _override; virtual MockActualCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) _override; virtual MockActualCall& withParameterOfType(const SimpleString& type, const SimpleString& name, const void* value) _override; virtual MockActualCall& withOutputParameter(const SimpleString& name, void* output) _override; virtual MockActualCall& withOutputParameterOfType(const SimpleString& type, const SimpleString& name, void* output) _override; virtual bool hasReturnValue() _override; virtual MockNamedValue returnValue() _override; virtual bool returnBoolValueOrDefault(bool default_value) _override; virtual bool returnBoolValue() _override; virtual int returnIntValueOrDefault(int default_value) _override; virtual int returnIntValue() _override; virtual unsigned long int returnUnsignedLongIntValue() _override; virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int) _override; virtual long int returnLongIntValue() _override; virtual long int returnLongIntValueOrDefault(long int default_value) _override; virtual unsigned int returnUnsignedIntValue() _override; virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int default_value) _override; virtual const char * returnStringValueOrDefault(const char * default_value) _override; virtual const char * returnStringValue() _override; virtual double returnDoubleValue() _override; virtual double returnDoubleValueOrDefault(double default_value) _override; virtual const void * returnConstPointerValue() _override; virtual const void * returnConstPointerValueOrDefault(const void * default_value) _override; virtual void * returnPointerValue() _override; virtual void * returnPointerValueOrDefault(void *) _override; virtual void (*returnFunctionPointerValue())() _override; virtual void (*returnFunctionPointerValueOrDefault(void (*)()))() _override; virtual MockActualCall& onObject(const void* objectPtr) _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 finalizeOutputParameters(MockCheckedExpectedCall* call); virtual void finalizeCallWhenFulfilled(); virtual void failTest(const MockFailure& failure); virtual void checkInputParameter(const MockNamedValue& actualParameter); virtual void checkOutputParameter(const MockNamedValue& outputParameter); virtual void callIsInProgress(); enum ActualCallState { CALL_IN_PROGRESS, CALL_FAILED, CALL_SUCCEED }; virtual void setState(ActualCallState state); private: SimpleString functionName_; int callOrder_; MockFailureReporter* reporter_; ActualCallState state_; MockCheckedExpectedCall* fulfilledExpectation_; MockExpectedCallsList unfulfilledExpectations_; 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_(NULL) {} }; MockOutputParametersListNode* outputParameterExpectations_; virtual void addOutputParameter(const SimpleString& name, const SimpleString& type, void* ptr); virtual void cleanUpOutputParameterList(); }; class MockActualCallTrace : public MockActualCall { public: MockActualCallTrace(); virtual ~MockActualCallTrace(); virtual MockActualCall& withName(const SimpleString& name) _override; virtual MockActualCall& withCallOrder(int) _override; virtual MockActualCall& withBoolParameter(const SimpleString& name, bool value) _override; virtual MockActualCall& withIntParameter(const SimpleString& name, int value) _override; virtual MockActualCall& withUnsignedIntParameter(const SimpleString& name, unsigned int value) _override; virtual MockActualCall& withLongIntParameter(const SimpleString& name, long int value) _override; virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value) _override; virtual MockActualCall& withDoubleParameter(const SimpleString& name, double value) _override; virtual MockActualCall& withStringParameter(const SimpleString& name, const char* value) _override; virtual MockActualCall& withPointerParameter(const SimpleString& name, void* value) _override; virtual MockActualCall& withConstPointerParameter(const SimpleString& name, const void* value) _override; virtual MockActualCall& withFunctionPointerParameter(const SimpleString& name, void (*value)()) _override; virtual MockActualCall& withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size) _override; virtual MockActualCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value) _override; virtual MockActualCall& withOutputParameter(const SimpleString& name, void* output) _override; virtual MockActualCall& withOutputParameterOfType(const SimpleString& typeName, const SimpleString& name, void* output) _override; virtual bool hasReturnValue() _override; virtual MockNamedValue returnValue() _override; virtual bool returnBoolValueOrDefault(bool default_value) _override; virtual bool returnBoolValue() _override; virtual int returnIntValueOrDefault(int default_value) _override; virtual int returnIntValue() _override; virtual unsigned long int returnUnsignedLongIntValue() _override; virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int) _override; virtual long int returnLongIntValue() _override; virtual long int returnLongIntValueOrDefault(long int default_value) _override; virtual unsigned int returnUnsignedIntValue() _override; virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int default_value) _override; virtual const char * returnStringValueOrDefault(const char * default_value) _override; virtual const char * returnStringValue() _override; virtual double returnDoubleValue() _override; virtual double returnDoubleValueOrDefault(double default_value) _override; virtual void * returnPointerValue() _override; virtual void * returnPointerValueOrDefault(void *) _override; virtual const void * returnConstPointerValue() _override; virtual const void * returnConstPointerValueOrDefault(const void * default_value) _override; virtual void (*returnFunctionPointerValue())() _override; virtual void (*returnFunctionPointerValueOrDefault(void (*)()))() _override; virtual MockActualCall& onObject(const void* objectPtr) _override; const char* getTraceOutput(); void clear(); static MockActualCallTrace& instance(); private: SimpleString traceBuffer_; void addParameterName(const SimpleString& name); }; class MockIgnoredActualCall: public MockActualCall { public: virtual MockActualCall& withName(const SimpleString&) _override { return *this;} virtual MockActualCall& withCallOrder(int) _override { return *this; } virtual MockActualCall& withBoolParameter(const SimpleString&, bool) _override { return *this; } virtual MockActualCall& withIntParameter(const SimpleString&, int) _override { return *this; } virtual MockActualCall& withUnsignedIntParameter(const SimpleString&, unsigned int) _override { return *this; } virtual MockActualCall& withLongIntParameter(const SimpleString&, long int) _override { return *this; } virtual MockActualCall& withUnsignedLongIntParameter(const SimpleString&, unsigned long int) _override { return *this; } virtual MockActualCall& withDoubleParameter(const SimpleString&, double) _override { return *this; } virtual MockActualCall& withStringParameter(const SimpleString&, const char*) _override { return *this; } virtual MockActualCall& withPointerParameter(const SimpleString& , void*) _override { return *this; } virtual MockActualCall& withConstPointerParameter(const SimpleString& , const void*) _override { return *this; } virtual MockActualCall& withFunctionPointerParameter(const SimpleString& , void (*)()) _override { return *this; } virtual MockActualCall& withMemoryBufferParameter(const SimpleString&, const unsigned char*, size_t) _override { return *this; } virtual MockActualCall& withParameterOfType(const SimpleString&, const SimpleString&, const void*) _override { return *this; } virtual MockActualCall& withOutputParameter(const SimpleString&, void*) _override { return *this; } virtual MockActualCall& withOutputParameterOfType(const SimpleString&, const SimpleString&, void*) _override { return *this; } virtual bool hasReturnValue() _override { return false; } virtual MockNamedValue returnValue() _override { return MockNamedValue(""); } virtual bool returnBoolValueOrDefault(bool) _override { return false; } virtual bool returnBoolValue() _override { return false; } virtual int returnIntValue() _override { return 0; } virtual int returnIntValueOrDefault(int value) _override { return value; } virtual unsigned long int returnUnsignedLongIntValue() _override { return 0; } virtual unsigned long int returnUnsignedLongIntValueOrDefault(unsigned long int value) _override { return value; } virtual long int returnLongIntValue() _override { return 0; } virtual long int returnLongIntValueOrDefault(long int value) _override { return value; } virtual unsigned int returnUnsignedIntValue() _override { return 0; } virtual unsigned int returnUnsignedIntValueOrDefault(unsigned int value) _override { return value; } virtual double returnDoubleValue() _override { return 0.0; } virtual double returnDoubleValueOrDefault(double value) _override { return value; } virtual const char * returnStringValue() _override { return ""; } virtual const char * returnStringValueOrDefault(const char * value) _override { return value; } virtual void * returnPointerValue() _override { return NULL; } virtual void * returnPointerValueOrDefault(void * value) _override { return value; } virtual const void * returnConstPointerValue() _override { return NULL; } virtual const void * returnConstPointerValueOrDefault(const void * value) _override { return value; } virtual void (*returnFunctionPointerValue())() _override { return NULL; } virtual void (*returnFunctionPointerValueOrDefault(void (*value)()))() _override { return value; } virtual MockActualCall& onObject(const void* ) _override { return *this; } static MockIgnoredActualCall& instance(); }; #endif
null
478
cpp
cpputest-stm32-keil-demo
MockExpectedCall.h
Middlewares/Third_Party/CPPUTEST/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 class MockNamedValue; extern SimpleString StringFrom(const MockNamedValue& parameter); class MockExpectedCall { public: MockExpectedCall(); virtual ~MockExpectedCall(); virtual MockExpectedCall& withName(const SimpleString& name)=0; virtual MockExpectedCall& withCallOrder(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, double value) { return withDoubleParameter(name, value); } 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& 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& withDoubleParameter(const SimpleString& name, double value)=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(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
479
cpp
cpputest-stm32-keil-demo
MockFailure.h
Middlewares/Third_Party/CPPUTEST/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(){} 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& expectations); }; 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
480
cpp
cpputest-stm32-keil-demo
MemoryReporterPlugin.h
Middlewares/Third_Party/CPPUTEST/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(); virtual void preTestAction(UtestShell & test, TestResult & result) _override; virtual void postTestAction(UtestShell & test, TestResult & result) _override; virtual bool parseArguments(int, const char**, int) _override; protected: virtual MemoryReportFormatter* createMemoryFormatter(const SimpleString& type); private: void destroyMemoryFormatter(MemoryReportFormatter* formatter); void setGlobalMemoryReportAllocators(); void removeGlobalMemoryReportAllocators(); void initializeAllocator(MemoryReportAllocator* allocator, TestResult & result); }; #endif
null
481
cpp
cpputest-stm32-keil-demo
MockSupport.h
Middlewares/Third_Party/CPPUTEST/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 = NULL); 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(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 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); 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 *createActualFunctionCall(); virtual void failTest(MockFailure& failure); void countCheck(); private: int callOrder_; int expectedCallOrder_; bool strictOrdering_; MockFailureReporter *activeReporter_; MockFailureReporter *standardReporter_; MockFailureReporter defaultReporter_; MockExpectedCallsList expectations_; MockExpectedCallsList unExpectations_; bool ignoreOtherCalls_; bool enabled_; MockCheckedActualCall *lastActualFunctionCall_; MockExpectedCallComposite compositeCalls_; MockNamedValueComparatorsAndCopiersRepository comparatorsAndCopiersRepository_; MockNamedValueList data_; const SimpleString mockName_; bool tracing_; void checkExpectationsOfLastCall(); bool wasLastCallFulfilled(); void failTestWithUnexpectedCalls(); void failTestWithOutOfOrderCalls(); MockNamedValue* retrieveDataFromStore(const SimpleString& name); MockSupport* getMockSupport(MockNamedValueListNode* node); bool hasntExpectationWithName(const SimpleString& functionName); bool hasntUnexpectationWithName(const SimpleString& functionName); bool hasCallsOutOfOrder(); SimpleString appendScopeToName(const SimpleString& functionName); }; #endif
null
482
cpp
cpputest-stm32-keil-demo
MockExpectedCallsList.h
Middlewares/Third_Party/CPPUTEST/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 int size() const; virtual int amountOfExpectationsFor(const SimpleString& name) const; virtual int amountOfUnfulfilledExpectations() const; virtual bool hasUnfulfilledExpectations() const; virtual bool hasFulfilledExpectations() const; virtual bool hasFulfilledExpectationsWithoutIgnoredParameters() const; virtual bool hasUnfulfilledExpectationsBecauseOfMissingParameters() 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 addUnfulfilledExpectations(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 onlyKeepUnfulfilledExpectations(); virtual MockCheckedExpectedCall* removeOneFulfilledExpectation(); virtual MockCheckedExpectedCall* removeOneFulfilledExpectationWithIgnoredParameters(); virtual MockCheckedExpectedCall* getOneFulfilledExpectationWithIgnoredParameters(); virtual void resetExpectations(); virtual void callWasMade(int callOrder); virtual void wasPassedToObject(); virtual void parameterWasPassed(const SimpleString& parameterName); virtual void outputParameterWasPassed(const SimpleString& parameterName); virtual SimpleString unfulfilledCallsToString(const SimpleString& linePrefix = "") const; virtual SimpleString fulfilledCallsToString(const SimpleString& linePrefix = "") const; virtual SimpleString missingParametersToString() const; protected: virtual void pruneEmptyNodeFromList(); class MockExpectedCallsListNode { public: MockCheckedExpectedCall* expectedCall_; MockExpectedCallsListNode* next_; MockExpectedCallsListNode(MockCheckedExpectedCall* expectedCall) : expectedCall_(expectedCall), next_(NULL) {} }; virtual MockExpectedCallsListNode* findNodeWithCallOrderOf(int callOrder) const; private: MockExpectedCallsListNode* head_; MockExpectedCallsList(const MockExpectedCallsList&); }; #endif
null
483
cpp
cpputest-stm32-keil-demo
MockSupportPlugin.h
Middlewares/Third_Party/CPPUTEST/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(); virtual void preTestAction(UtestShell&, TestResult&) _override; virtual void postTestAction(UtestShell&, TestResult&) _override; virtual void installComparator(const SimpleString& name, MockNamedValueComparator& comparator); virtual void installCopier(const SimpleString& name, MockNamedValueCopier& copier); private: MockNamedValueComparatorsAndCopiersRepository repository_; }; #endif
null
484
cpp
cpputest-stm32-keil-demo
CommandLineTestRunner.cpp
Middlewares/Third_Party/CPPUTEST/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**) av); } int CommandLineTestRunner::RunAllTests(int ac, const char** 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** av, TestRegistry* registry) : output_(NULL), arguments_(NULL), registry_(registry) { arguments_ = new CommandLineArguments(ac, av); } CommandLineTestRunner::~CommandLineTestRunner() { delete arguments_; delete output_; } int CommandLineTestRunner::runAllTestsMain() { int testResult = 0; SetPointerPlugin pPlugin(DEF_PLUGIN_SET_POINTER); registry_->installPlugin(&pPlugin); if (parseArguments(registry_->getFirstPlugin())) testResult = runAllTests(); registry_->removePluginByName(DEF_PLUGIN_SET_POINTER); return testResult; } void CommandLineTestRunner::initializeTestRun() { registry_->setGroupFilters(arguments_->getGroupFilters()); registry_->setNameFilters(arguments_->getNameFilters()); if (arguments_->isVerbose()) output_->verbose(); if (arguments_->isColor()) output_->color(); if (arguments_->runTestsInSeperateProcess()) registry_->setRunTestsInSeperateProcess(); if (arguments_->isRunIgnored()) registry_->setRunIgnored(); } int CommandLineTestRunner::runAllTests() { initializeTestRun(); int loopCount = 0; int failureCount = 0; int repeat_ = arguments_->getRepeatCount(); if (arguments_->isListingTestGroupNames()) { TestResult tr(*output_); registry_->listTestGroupNames(tr); return 0; } if (arguments_->isListingTestGroupAndCaseNames()) { TestResult tr(*output_); registry_->listTestGroupAndCaseNames(tr); return 0; } while (loopCount++ < repeat_) { output_->printTestRun(loopCount, repeat_); TestResult tr(*output_); registry_->runAllTests(tr); failureCount += tr.getFailureCount(); } return failureCount; } TestOutput* CommandLineTestRunner::createTeamCityOutput() { return new TeamCityTestOutput; } TestOutput* CommandLineTestRunner::createJUnitOutput(const SimpleString& packageName) { JUnitTestOutput* junitOutput = new JUnitTestOutput; if (junitOutput != NULL) { 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_->usage()); return false; } if (arguments_->isJUnitOutput()) { output_= createJUnitOutput(arguments_->getPackageName()); if (arguments_->isVerbose()) output_ = createCompositeOutput(output_, createConsoleOutput()); } else if (arguments_->isTeamCityOutput()) { output_ = createTeamCityOutput(); } else output_ = createConsoleOutput(); return true; }
null
485
cpp
cpputest-stm32-keil-demo
TestPlugin.cpp
Middlewares/Third_Party/CPPUTEST/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**> (av), index); } bool TestPlugin::parseAllArguments(int ac, const char** av, int index) { if (parseArguments(ac, av, index)) return true; if (next_) return next_->parseAllArguments(ac, av, index); return false; } const SimpleString& TestPlugin::getName() { return name_; } TestPlugin* TestPlugin::getPluginByName(const SimpleString& name) { if (name == name_) return this; if (next_) return next_->getPluginByName(name); return (next_); } TestPlugin* TestPlugin::getNext() { return next_; } TestPlugin* TestPlugin::removePluginByName(const SimpleString& name) { TestPlugin* removed = 0; if (next_ && next_->getName() == name) { removed = next_; next_ = next_->next_; } return removed; } void TestPlugin::disable() { enabled_ = false; } void TestPlugin::enable() { enabled_ = true; } bool TestPlugin::isEnabled() { return enabled_; } struct cpputest_pair { void **orig; void *orig_value; }; //////// SetPlugin static int pointerTableIndex; static cpputest_pair setlist[SetPointerPlugin::MAX_SET]; SetPointerPlugin::SetPointerPlugin(const SimpleString& name) : TestPlugin(name) { pointerTableIndex = 0; } void CppUTestStore(void**function) { if (pointerTableIndex >= SetPointerPlugin::MAX_SET) { FAIL("Maximum number of function pointers installed!"); } setlist[pointerTableIndex].orig_value = *function; setlist[pointerTableIndex].orig = function; pointerTableIndex++; } void SetPointerPlugin::postTestAction(UtestShell& /*test*/, TestResult& /*result*/) { for (int i = pointerTableIndex - 1; i >= 0; i--) *((void**) setlist[i].orig) = setlist[i].orig_value; pointerTableIndex = 0; } //////// NullPlugin NullTestPlugin::NullTestPlugin() : TestPlugin(0) { } NullTestPlugin* NullTestPlugin::instance() { static NullTestPlugin _instance; return &_instance; } void NullTestPlugin::runAllPreTestAction(UtestShell&, TestResult&) { } void NullTestPlugin::runAllPostTestAction(UtestShell&, TestResult&) { }
null
486
cpp
cpputest-stm32-keil-demo
SimpleMutex.cpp
Middlewares/Third_Party/CPPUTEST/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
487
cpp
cpputest-stm32-keil-demo
TestFailure.cpp
Middlewares/Third_Party/CPPUTEST/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" static SimpleString removeAllPrintableCharactersFrom(const SimpleString& str) { size_t bufferSize = str.size()+1; char* buffer = (char*) PlatformSpecificMalloc(bufferSize); str.copyToBuffer(buffer, bufferSize); for (size_t i = 0; i < bufferSize-1; i++) if (buffer[i] != '\t' && buffer[i] != '\n') buffer[i] = ' '; SimpleString result(buffer); PlatformSpecificFree(buffer); return result; } static SimpleString addMarkerToString(const SimpleString& str, int markerPos) { size_t bufferSize = str.size()+1; char* buffer = (char*) PlatformSpecificMalloc(bufferSize); str.copyToBuffer(buffer, bufferSize); buffer[markerPos] = '^'; SimpleString result(buffer); PlatformSpecificFree(buffer); return result; } TestFailure::TestFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& theMessage) : testName_(test->getFormattedName()), 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, int 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_; } int TestFailure::getFailureLineNumber() const { return lineNumber_; } int TestFailure::getTestLineNumber() const { return testLineNumber_; } SimpleString TestFailure::getMessage() const { return message_; } bool TestFailure::isOutsideTestFile() const { return testFileName_ != fileName_; } bool TestFailure::isInHelperFunction() const { return lineNumber_ < testLineNumber_; } SimpleString TestFailure::createButWasString(const SimpleString& expected, const SimpleString& actual) { return StringFromFormat("expected <%s>\n\tbut was <%s>", expected.asCharString(), actual.asCharString()); } SimpleString TestFailure::createDifferenceAtPosString(const SimpleString& actual, size_t position, DifferenceFormat format) { SimpleString result; const size_t extraCharactersWindow = 20; const size_t halfOfExtraCharactersWindow = extraCharactersWindow / 2; const size_t actualOffset = (format == DIFFERENCE_STRING) ? position : (position * 3 + 1); SimpleString paddingForPreventingOutOfBounds (" ", halfOfExtraCharactersWindow); SimpleString actualString = paddingForPreventingOutOfBounds + actual + paddingForPreventingOutOfBounds; SimpleString differentString = StringFromFormat("difference starts at position %lu at: <", (unsigned long) position); result += "\n"; result += StringFromFormat("\t%s%s>\n", differentString.asCharString(), actualString.subString(actualOffset, extraCharactersWindow).asCharString()); SimpleString markString = actualString.subString(actualOffset, halfOfExtraCharactersWindow+1); markString = removeAllPrintableCharactersFrom(markString); markString = addMarkerToString(markString, halfOfExtraCharactersWindow); result += StringFromFormat("\t%s%s", SimpleString(" ", differentString.size()).asCharString(), markString.asCharString()); return result; } SimpleString TestFailure::createUserText(const SimpleString& text) { SimpleString userMessage = ""; if (!text.isEmpty()) { userMessage += "Message: "; userMessage += text; userMessage += "\n\t"; } return userMessage; } EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += createButWasString(StringFromOrNull(expected), StringFromOrNull(actual)); } EqualsFailure::EqualsFailure(UtestShell* test, const char* fileName, int 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, int 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, int lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); size_t failStart; for (failStart = 0; actual.asCharString()[failStart] == expected.asCharString()[failStart]; failStart++) ; message_ += createButWasString(expected, actual); message_ += createDifferenceAtPosString(actual, failStart); } ContainsFailure::ContainsFailure(UtestShell* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual, 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, int 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, int lineNumber, const SimpleString& message) : TestFailure(test, fileName, lineNumber) { message_ = message; } LongsEqualFailure::LongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, long expected, long actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom(expected); SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString::padStringsToSameLength(aHex, eHex, '0'); SimpleString actualReported = aDecimal + " 0x" + aHex; SimpleString expectedReported = eDecimal + " 0x" + eHex; message_ += createButWasString(expectedReported, actualReported); } UnsignedLongsEqualFailure::UnsignedLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, unsigned long expected, unsigned long actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom(expected); SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString::padStringsToSameLength(aHex, eHex, '0'); SimpleString actualReported = aDecimal + " 0x" + aHex; SimpleString expectedReported = eDecimal + " 0x" + eHex; message_ += createButWasString(expectedReported, actualReported); } LongLongsEqualFailure::LongLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, cpputest_longlong expected, cpputest_longlong actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom(expected); SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString::padStringsToSameLength(aHex, eHex, '0'); SimpleString actualReported = aDecimal + " 0x" + aHex; SimpleString expectedReported = eDecimal + " 0x" + eHex; message_ += createButWasString(expectedReported, actualReported); } UnsignedLongLongsEqualFailure::UnsignedLongLongsEqualFailure(UtestShell* test, const char* fileName, int lineNumber, cpputest_ulonglong expected, cpputest_ulonglong actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom(actual); SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom(expected); SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString::padStringsToSameLength(aHex, eHex, '0'); SimpleString actualReported = aDecimal + " 0x" + aHex; SimpleString expectedReported = eDecimal + " 0x" + eHex; message_ += createButWasString(expectedReported, actualReported); } SignedBytesEqualFailure::SignedBytesEqualFailure (UtestShell* test, const char* fileName, int lineNumber, signed char expected, signed char actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); SimpleString aDecimal = StringFrom((int)actual); SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom((int)expected); SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString::padStringsToSameLength(aHex, eHex, '0'); SimpleString actualReported = aDecimal + " 0x" + aHex; SimpleString expectedReported = eDecimal + " 0x" + eHex; message_ += createButWasString(expectedReported, actualReported); } StringEqualFailure::StringEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += createButWasString(StringFromOrNull(expected), StringFromOrNull(actual)); if((expected) && (actual)) { size_t failStart; for (failStart = 0; actual[failStart] == expected[failStart]; failStart++) ; message_ += createDifferenceAtPosString(actual, failStart); } } StringEqualNoCaseFailure::StringEqualNoCaseFailure(UtestShell* test, const char* fileName, int lineNumber, const char* expected, const char* actual, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += createButWasString(StringFromOrNull(expected), StringFromOrNull(actual)); if((expected) && (actual)) { size_t failStart; for (failStart = 0; SimpleString::ToLower(actual[failStart]) == SimpleString::ToLower(expected[failStart]); failStart++) ; message_ += createDifferenceAtPosString(actual, failStart); } } BinaryEqualFailure::BinaryEqualFailure(UtestShell* test, const char* fileName, int lineNumber, const unsigned char* expected, const unsigned char* actual, size_t size, const SimpleString& text) : TestFailure(test, fileName, lineNumber) { message_ = createUserText(text); message_ += createButWasString(StringFromBinaryOrNull(expected, size), StringFromBinaryOrNull(actual, size)); if ((expected) && (actual)) { size_t failStart; for (failStart = 0; actual[failStart] == expected[failStart]; failStart++) ; message_ += createDifferenceAtPosString(StringFromBinary(actual, size), failStart, DIFFERENCE_BINARY); } } BitsEqualFailure::BitsEqualFailure(UtestShell* test, const char* fileName, int 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, int 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());; }
null
488
cpp
cpputest-stm32-keil-demo
MemoryLeakWarningPlugin.cpp
Middlewares/Third_Party/CPPUTEST/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, int line) { MemLeakScopedMutex lock; return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentMallocAllocator(), size, file, line, true); } static void threadsafe_mem_leak_free(void* buffer, const char* file, int line) { MemLeakScopedMutex lock; MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) buffer); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentMallocAllocator(), (char*) buffer, file, line, true); } static void* threadsafe_mem_leak_realloc(void* memory, size_t size, const char* file, int line) { MemLeakScopedMutex lock; return MemoryLeakWarningPlugin::getGlobalDetector()->reallocMemory(getCurrentMallocAllocator(), (char*) memory, size, file, line, true); } static void* mem_leak_malloc(size_t size, const char* file, int line) { return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentMallocAllocator(), size, file, line, true); } static void mem_leak_free(void* buffer, const char* file, int line) { MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) buffer); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentMallocAllocator(), (char*) buffer, file, line, true); } static void* mem_leak_realloc(void* memory, size_t size, const char* file, int line) { return MemoryLeakWarningPlugin::getGlobalDetector()->reallocMemory(getCurrentMallocAllocator(), (char*) memory, size, file, line, true); } #endif static void* normal_malloc(size_t size, const char*, int) { return PlatformSpecificMalloc(size); } static void* normal_realloc(void* memory, size_t size, const char*, int) { return PlatformSpecificRealloc(memory, size); } static void normal_free(void* buffer, const char*, int) { PlatformSpecificFree(buffer); } #if CPPUTEST_USE_MEM_LEAK_DETECTION static void *(*malloc_fptr)(size_t size, const char* file, int line) = mem_leak_malloc; static void (*free_fptr)(void* mem, const char* file, int line) = mem_leak_free; static void*(*realloc_fptr)(void* memory, size_t size, const char* file, int line) = mem_leak_realloc; #else static void *(*malloc_fptr)(size_t size, const char* file, int line) = normal_malloc; static void (*free_fptr)(void* mem, const char* file, int line) = normal_free; static void*(*realloc_fptr)(void* memory, size_t size, const char* file, int line) = normal_realloc; #endif void* cpputest_malloc_location_with_leak_detection(size_t size, const char* file, int line) { return malloc_fptr(size, file, line); } void* cpputest_realloc_location_with_leak_detection(void* memory, size_t size, const char* file, int line) { return realloc_fptr(memory, size, file, line); } void cpputest_free_location_with_leak_detection(void* buffer, const char* file, int line) { free_fptr(buffer, file, line); } /********** C++ *************/ #if CPPUTEST_USE_MEM_LEAK_DETECTION #undef new #if CPPUTEST_USE_STD_CPP_LIB #define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) if (memory == NULL) throw std::bad_alloc(); #else #define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) #endif static void* threadsafe_mem_leak_operator_new (size_t size) UT_THROW(std::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, int line) UT_THROW(std::bad_alloc) { MemLeakScopedMutex lock; void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size, (char*) file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* threadsafe_mem_leak_operator_new_array (size_t size) UT_THROW(std::bad_alloc) { 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, int line) UT_THROW(std::bad_alloc) { MemLeakScopedMutex lock; void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, (char*) 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(std::bad_alloc) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* mem_leak_operator_new_nothrow (size_t size) UT_NOTHROW { return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size); } static void* mem_leak_operator_new_debug (size_t size, const char* file, int line) UT_THROW(std::bad_alloc) { void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewAllocator(), size, (char*) file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* mem_leak_operator_new_array (size_t size) UT_THROW(std::bad_alloc) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* mem_leak_operator_new_array_nothrow (size_t size) UT_NOTHROW { return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size); } static void* mem_leak_operator_new_array_debug (size_t size, const char* file, int line) UT_THROW(std::bad_alloc) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, (char*) file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void mem_leak_operator_delete (void* mem) UT_NOTHROW { MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewAllocator(), (char*) mem); } static void mem_leak_operator_delete_array (void* mem) UT_NOTHROW { MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewArrayAllocator(), (char*) mem); } static void* normal_operator_new (size_t size) UT_THROW(std::bad_alloc) { void* memory = PlatformSpecificMalloc(size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* normal_operator_new_nothrow (size_t size) UT_NOTHROW { return PlatformSpecificMalloc(size); } static void* normal_operator_new_debug (size_t size, const char* /*file*/, int /*line*/) UT_THROW(std::bad_alloc) { void* memory = PlatformSpecificMalloc(size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* normal_operator_new_array (size_t size) UT_THROW(std::bad_alloc) { void* memory = PlatformSpecificMalloc(size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void* normal_operator_new_array_nothrow (size_t size) UT_NOTHROW { return PlatformSpecificMalloc(size); } static void* normal_operator_new_array_debug (size_t size, const char* /*file*/, int /*line*/) UT_THROW(std::bad_alloc) { void* memory = PlatformSpecificMalloc(size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } static void normal_operator_delete (void* mem) UT_NOTHROW { PlatformSpecificFree(mem); } static void normal_operator_delete_array (void* mem) UT_NOTHROW { PlatformSpecificFree(mem); } static void *(*operator_new_fptr)(size_t size) UT_THROW(std::bad_alloc) = mem_leak_operator_new; static void *(*operator_new_nothrow_fptr)(size_t size) UT_NOTHROW = mem_leak_operator_new_nothrow; static void *(*operator_new_debug_fptr)(size_t size, const char* file, int line) UT_THROW(std::bad_alloc) = mem_leak_operator_new_debug; static void *(*operator_new_array_fptr)(size_t size) UT_THROW(std::bad_alloc) = mem_leak_operator_new_array; static void *(*operator_new_array_nothrow_fptr)(size_t size) UT_NOTHROW = mem_leak_operator_new_array_nothrow; static void *(*operator_new_array_debug_fptr)(size_t size, const char* file, int line) UT_THROW(std::bad_alloc) = mem_leak_operator_new_array_debug; static void (*operator_delete_fptr)(void* mem) UT_NOTHROW = mem_leak_operator_delete; static void (*operator_delete_array_fptr)(void* mem) UT_NOTHROW = mem_leak_operator_delete_array; void* operator new(size_t size) UT_THROW(std::bad_alloc) { return operator_new_fptr(size); } void* operator new(size_t size, const char* file, int line) UT_THROW(std::bad_alloc) { return operator_new_debug_fptr(size, file, line); } void operator delete(void* mem) UT_NOTHROW { operator_delete_fptr(mem); } void operator delete(void* mem, const char*, int) UT_NOTHROW { operator_delete_fptr(mem); } void operator delete (void* mem, size_t) UT_NOTHROW { operator_delete_fptr(mem); } void* operator new[](size_t size) UT_THROW(std::bad_alloc) { return operator_new_array_fptr(size); } void* operator new [](size_t size, const char* file, int line) UT_THROW(std::bad_alloc) { return operator_new_array_debug_fptr(size, file, line); } void operator delete[](void* mem) UT_NOTHROW { operator_delete_array_fptr(mem); } void operator delete[](void* mem, const char*, int) UT_NOTHROW { operator_delete_array_fptr(mem); } void operator delete[] (void* mem, size_t) UT_NOTHROW { operator_delete_array_fptr(mem); } #if CPPUTEST_USE_STD_CPP_LIB void* operator new(size_t size, const std::nothrow_t&) UT_NOTHROW { return operator_new_nothrow_fptr(size); } void* operator new[](size_t size, const std::nothrow_t&) UT_NOTHROW { return operator_new_array_nothrow_fptr(size); } #else /* Have a similar method. This avoid unused operator_new_nothrow_fptr warning */ extern void* operator_new_nothrow(size_t size) UT_NOTHROW; extern void* operator_new_array_nothrow(size_t size) UT_NOTHROW; void* operator_new_nothrow(size_t size) UT_NOTHROW { return operator_new_nothrow_fptr(size); } void* operator_new_array_nothrow(size_t size) UT_NOTHROW { return operator_new_array_nothrow_fptr(size); } #endif #endif void MemoryLeakWarningPlugin::turnOffNewDeleteOverloads() { #if CPPUTEST_USE_MEM_LEAK_DETECTION operator_new_fptr = normal_operator_new; operator_new_nothrow_fptr = normal_operator_new_nothrow; operator_new_debug_fptr = normal_operator_new_debug; operator_new_array_fptr = normal_operator_new_array; operator_new_array_nothrow_fptr = normal_operator_new_array_nothrow; operator_new_array_debug_fptr = normal_operator_new_array_debug; operator_delete_fptr = normal_operator_delete; operator_delete_array_fptr = normal_operator_delete_array; malloc_fptr = normal_malloc; realloc_fptr = normal_realloc; free_fptr = normal_free; #endif } void MemoryLeakWarningPlugin::turnOnNewDeleteOverloads() { #if CPPUTEST_USE_MEM_LEAK_DETECTION operator_new_fptr = mem_leak_operator_new; operator_new_nothrow_fptr = mem_leak_operator_new_nothrow; operator_new_debug_fptr = mem_leak_operator_new_debug; operator_new_array_fptr = mem_leak_operator_new_array; operator_new_array_nothrow_fptr = mem_leak_operator_new_array_nothrow; operator_new_array_debug_fptr = mem_leak_operator_new_array_debug; operator_delete_fptr = mem_leak_operator_delete; operator_delete_array_fptr = mem_leak_operator_delete_array; malloc_fptr = mem_leak_malloc; realloc_fptr = mem_leak_realloc; free_fptr = mem_leak_free; #endif } bool MemoryLeakWarningPlugin::areNewDeleteOverloaded() { #if CPPUTEST_USE_MEM_LEAK_DETECTION return operator_new_fptr == mem_leak_operator_new; #else return false; #endif } void MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads() { #if CPPUTEST_USE_MEM_LEAK_DETECTION 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 } void crash_on_allocation_number(unsigned alloc_number) { static CrashOnAllocationAllocator crashAllocator; crashAllocator.setNumberToCrashOn(alloc_number); setCurrentMallocAllocator(&crashAllocator); setCurrentNewAllocator(&crashAllocator); setCurrentNewArrayAllocator(&crashAllocator); } class MemoryLeakWarningReporter: public MemoryLeakFailure { public: virtual ~MemoryLeakWarningReporter() { } virtual void fail(char* fail_string) { UtestShell* currentTest = UtestShell::getCurrent(); currentTest->failWith(FailFailure(currentTest, currentTest->getName().asCharString(), currentTest->getLineNumber(), fail_string), TestTerminatorWithoutExceptions()); } // LCOV_EXCL_LINE }; static MemoryLeakFailure* globalReporter = 0; static MemoryLeakDetector* globalDetector = 0; MemoryLeakDetector* MemoryLeakWarningPlugin::getGlobalDetector() { if (globalDetector == 0) { bool newDeleteOverloaded = areNewDeleteOverloaded(); turnOffNewDeleteOverloads(); globalReporter = new MemoryLeakWarningReporter; globalDetector = new MemoryLeakDetector(globalReporter); if (newDeleteOverloaded) turnOnNewDeleteOverloads(); } return globalDetector; } MemoryLeakFailure* MemoryLeakWarningPlugin::getGlobalFailureReporter() { return globalReporter; } void MemoryLeakWarningPlugin::destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(bool des) { destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_ = des; } void MemoryLeakWarningPlugin::setGlobalDetector(MemoryLeakDetector* detector, MemoryLeakFailure* reporter) { globalDetector = detector; globalReporter = reporter; } void MemoryLeakWarningPlugin::destroyGlobalDetector() { turnOffNewDeleteOverloads(); delete globalDetector; delete globalReporter; globalDetector = NULL; } MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::firstPlugin_ = 0; MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::getFirstPlugin() { return firstPlugin_; } MemoryLeakDetector* MemoryLeakWarningPlugin::getMemoryLeakDetector() { return memLeakDetector_; } void MemoryLeakWarningPlugin::ignoreAllLeaksInTest() { ignoreAllWarnings_ = true; } void MemoryLeakWarningPlugin::expectLeaksInTest(int n) { expectedLeaks_ = n; } MemoryLeakWarningPlugin::MemoryLeakWarningPlugin(const SimpleString& name, MemoryLeakDetector* localDetector) : TestPlugin(name), ignoreAllWarnings_(false), destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_(false), expectedLeaks_(0) { if (firstPlugin_ == 0) firstPlugin_ = this; if (localDetector) memLeakDetector_ = localDetector; else memLeakDetector_ = getGlobalDetector(); memLeakDetector_->enable(); } MemoryLeakWarningPlugin::~MemoryLeakWarningPlugin() { if (destroyGlobalDetectorAndTurnOfMemoryLeakDetectionInDestructor_) { MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); MemoryLeakWarningPlugin::destroyGlobalDetector(); } } void MemoryLeakWarningPlugin::preTestAction(UtestShell& /*test*/, TestResult& result) { memLeakDetector_->startChecking(); failureCount_ = result.getFailureCount(); } void MemoryLeakWarningPlugin::postTestAction(UtestShell& test, TestResult& result) { memLeakDetector_->stopChecking(); int leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_checking); if (!ignoreAllWarnings_ && expectedLeaks_ != leaks && failureCount_ == result.getFailureCount()) { TestFailure f(&test, memLeakDetector_->report(mem_leak_period_checking)); result.addFailure(f); } memLeakDetector_->markCheckingPeriodLeaksAsNonCheckingPeriod(); ignoreAllWarnings_ = false; expectedLeaks_ = 0; } const char* MemoryLeakWarningPlugin::FinalReport(int toBeDeletedLeaks) { int leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_enabled); if (leaks != toBeDeletedLeaks) return memLeakDetector_->report(mem_leak_period_enabled); return ""; }
null
489
cpp
cpputest-stm32-keil-demo
SimpleString.cpp
Middlewares/Third_Party/CPPUTEST/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" TestMemoryAllocator* SimpleString::stringAllocator_ = NULL; TestMemoryAllocator* SimpleString::getStringAllocator() { if (stringAllocator_ == NULL) return defaultNewArrayAllocator(); return stringAllocator_; } void SimpleString::setStringAllocator(TestMemoryAllocator* allocator) { stringAllocator_ = allocator; } /* Avoid using the memory leak detector INSIDE SimpleString as its used inside the detector */ char* SimpleString::allocStringBuffer(size_t _size, const char* file, int line) { return getStringAllocator()->alloc_memory(_size, file, line); } void SimpleString::deallocStringBuffer(char* str, const char* file, int line) { getStringAllocator()->free_memory(str, file, line); } char* SimpleString::getEmptyString() const { char* empty = allocStringBuffer(1, __FILE__, __LINE__); empty[0] = '\0'; return empty; } 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 *(unsigned char *) s1 - *(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 ? *(unsigned char *) s1 - *(unsigned char *) s2 : 0; } char* SimpleString::StrNCpy(char* s1, const char* s2, size_t n) { char* result = s1; if((NULL == s1) || (0 == n)) return result; while ((*s1++ = *s2++) && --n != 0) ; return result; } char* SimpleString::StrStr(const char* s1, const char* s2) { if(!*s2) return (char*) s1; for (; *s1; s1++) if (StrNCmp(s1, s2, StrLen(s2)) == 0) return (char*) s1; return NULL; } 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; } SimpleString::SimpleString(const char *otherBuffer) { if (otherBuffer == 0) { buffer_ = getEmptyString(); } else { buffer_ = copyToNewBuffer(otherBuffer); } } SimpleString::SimpleString(const char *other, size_t repeatCount) { size_t otherStringLength = StrLen(other); size_t len = otherStringLength * repeatCount + 1; buffer_ = allocStringBuffer(len, __FILE__, __LINE__); 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_ = copyToNewBuffer(other.buffer_); } SimpleString& SimpleString::operator=(const SimpleString& other) { if (this != &other) { deallocStringBuffer(buffer_, __FILE__, __LINE__); buffer_ = copyToNewBuffer(other.buffer_); } return *this; } bool SimpleString::contains(const SimpleString& other) const { return StrStr(buffer_, other.buffer_) != 0; } bool SimpleString::containsNoCase(const SimpleString& other) const { return lowerCase().contains(other.lowerCase()); } bool SimpleString::startsWith(const SimpleString& other) const { if (StrLen(other.buffer_) == 0) return true; else if (size() == 0) return false; else return StrStr(buffer_, other.buffer_) == buffer_; } bool SimpleString::endsWith(const SimpleString& other) const { size_t buffer_length = size(); size_t other_buffer_length = StrLen(other.buffer_); if (other_buffer_length == 0) return true; if (buffer_length == 0) return false; if (buffer_length < other_buffer_length) return false; return StrCmp(buffer_ + buffer_length - other_buffer_length, other.buffer_) == 0; } size_t SimpleString::count(const SimpleString& substr) const { size_t num = 0; char* str = buffer_; while (*str && (str = StrStr(str, substr.buffer_))) { num++; str++; } return num; } void SimpleString::split(const SimpleString& delimiter, SimpleStringCollection& col) const { size_t num = count(delimiter); size_t extraEndToken = (endsWith(delimiter)) ? 0 : 1U; col.allocate(num + extraEndToken); char* str = buffer_; char* prev; for (size_t i = 0; i < num; ++i) { prev = str; str = StrStr(str, delimiter.buffer_) + 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 (buffer_[i] == to) buffer_[i] = with; } } void SimpleString::replace(const char* to, const char* with) { size_t c = count(to); size_t len = size(); size_t tolen = 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(&buffer_[i], to, tolen) == 0) { StrNCpy(&newbuf[j], with, withlen + 1); j += withlen; i += tolen; } else { newbuf[j] = buffer_[i]; j++; i++; } } deallocStringBuffer(buffer_, __FILE__, __LINE__); buffer_ = newbuf; buffer_[newsize - 1] = '\0'; } else { deallocStringBuffer(buffer_, __FILE__, __LINE__); buffer_ = getEmptyString(); } } 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.buffer_[i]); return str; } const char *SimpleString::asCharString() const { return buffer_; } size_t SimpleString::size() const { return StrLen(buffer_); } bool SimpleString::isEmpty() const { return size() == 0; } SimpleString::~SimpleString() { deallocStringBuffer(buffer_, __FILE__, __LINE__); } 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(buffer_); t += rhs.buffer_; return t; } SimpleString& SimpleString::operator+=(const SimpleString& rhs) { return operator+=(rhs.buffer_); } SimpleString& SimpleString::operator+=(const char* rhs) { size_t originalSize = this->size(); size_t additionalStringSize = StrLen(rhs) + 1; size_t sizeOfNewString = originalSize + additionalStringSize; char* tbuffer = copyToNewBuffer(this->buffer_, sizeOfNewString); StrNCpy(tbuffer + originalSize, rhs, additionalStringSize); deallocStringBuffer(this->buffer_, __FILE__, __LINE__); this->buffer_ = tbuffer; return *this; } void SimpleString::padStringsToSameLength(SimpleString& str1, SimpleString& str2, char padCharacter) { if (str1.size() > str2.size()) { padStringsToSameLength(str2, str1, padCharacter); return; } char pad[2]; pad[0] = padCharacter; pad[1] = 0; str1 = SimpleString(pad, str2.size() - str1.size()) + str1; } SimpleString SimpleString::subString(size_t beginPos, size_t amount) const { if (beginPos > size()-1) return ""; SimpleString newString = buffer_ + beginPos; if (newString.size() > amount) newString.buffer_[amount] = '\0'; return newString; } SimpleString SimpleString::subString(size_t beginPos) const { return subString(beginPos, npos); } char SimpleString::at(size_t pos) const { return buffer_[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 (buffer_[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) { if(bufferSize == 0) bufferSize = StrLen(bufferToCopy) + 1; char* newBuffer = allocStringBuffer(bufferSize, __FILE__, __LINE__); StrNCpy(newBuffer, bufferToCopy, bufferSize); newBuffer[bufferSize-1] = '\0'; return newBuffer; } void SimpleString::copyToBuffer(char* bufferToCopy, size_t bufferSize) const { if (bufferToCopy == NULL || bufferSize == 0) return; size_t sizeToCopy = (bufferSize-1 < size()) ? bufferSize : size(); StrNCpy(bufferToCopy, buffer_, 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; } SimpleString StringFrom(bool value) { return SimpleString(StringFromFormat("%s", value ? "true" : "false")); } SimpleString StringFrom(const char *value) { return SimpleString(value); } SimpleString StringFromOrNull(const char * expected) { return (expected) ? StringFrom(expected) : "(null)"; } SimpleString StringFrom(int value) { return StringFromFormat("%d", value); } SimpleString StringFrom(long value) { return StringFromFormat("%ld", value); } SimpleString StringFrom(const void* value) { return SimpleString("0x") + HexStringFrom(value); } SimpleString StringFrom(void (*value)()) { return SimpleString("0x") + HexStringFrom(value); } SimpleString HexStringFrom(long value) { return StringFromFormat("%lx", 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); } #ifdef CPPUTEST_USE_LONG_LONG SimpleString StringFrom(cpputest_longlong value) { return StringFromFormat("%lld", value); } SimpleString StringFrom(cpputest_ulonglong value) { return StringFromFormat("%llu (0x%llx)", value, 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); } #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)); } #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("%10u (0x%08x)", i, 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 (0x%lx)", i, i); } //Kludge to get a va_copy in VC++ V6 #ifndef va_copy #define va_copy(copy, original) copy = original; #endif SimpleString VStringFromFormat(const char* format, va_list args) { va_list argsCopy; 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, __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) : "(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) : "(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) { unsigned int onesDigit = number % 10; const char* suffix; if (number >= 11 && number <= 13) { suffix = "th"; } else if (3 == onesDigit) { suffix = "rd"; } else if (2 == onesDigit) { suffix = "nd"; } else if (1 == onesDigit) { suffix = "st"; } else { suffix = "th"; } return StringFromFormat("%u%s", number, suffix); } SimpleStringCollection::SimpleStringCollection() { collection_ = 0; 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
490
cpp
cpputest-stm32-keil-demo
TestResult.cpp
Middlewares/Third_Party/CPPUTEST/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_ = GetPlatformSpecificTimeInMillis(); } void TestResult::currentGroupEnded(UtestShell* /*test*/) { currentGroupTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentGroupTimeStarted_; output_.printCurrentGroupEnded(*this); } void TestResult::currentTestStarted(UtestShell* test) { output_.printCurrentTestStarted(*test); currentTestTimeStarted_ = GetPlatformSpecificTimeInMillis(); } void TestResult::print(const char* text) { output_.print(text); } void TestResult::currentTestEnded(UtestShell* /*test*/) { currentTestTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentTestTimeStarted_; output_.printCurrentTestEnded(*this); } void TestResult::addFailure(const TestFailure& failure) { output_.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_ = GetPlatformSpecificTimeInMillis(); output_.printTestsStarted(); } void TestResult::testsEnded() { long timeEnded = GetPlatformSpecificTimeInMillis(); totalExecutionTime_ = timeEnded - timeStarted_; output_.printTestsEnded(*this); } long TestResult::getTotalExecutionTime() const { return totalExecutionTime_; } void TestResult::setTotalExecutionTime(long exTime) { totalExecutionTime_ = exTime; } long TestResult::getCurrentTestTotalExecutionTime() const { return currentTestTotalExecutionTime_; } long TestResult::getCurrentGroupTotalExecutionTime() const { return currentGroupTotalExecutionTime_; }
null
491
cpp
cpputest-stm32-keil-demo
UtestPlatform.cpp
Middlewares/Third_Party/CPPUTEST/src/CppUTest/UtestPlatform.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 <stdlib.h> #include "CppUTest/TestHarness.h" #undef malloc #undef free #undef calloc #undef realloc #define far // eliminate "meaningless type qualifier" warning #include <time.h> #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #include <string.h> #include <math.h> #include <ctype.h> #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() { return TestOutput::eclipse; } static void DummyRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) { result->addFailure(TestFailure(shell, "-p doesn't work on this platform, as it is lacking fork.\b")); } static int DummyPlatformSpecificFork(void) { return 0; } static int DummyPlatformSpecificWaitPid(int, int*, int) { return 0; } void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell*, TestPlugin*, TestResult*) = DummyRunTestInASeperateProcess; int (*PlatformSpecificFork)() = DummyPlatformSpecificFork; int (*PlatformSpecificWaitPid)(int, int*, int) = DummyPlatformSpecificWaitPid; extern "C" { static int PlatformSpecificSetJmpImplementation(void (*function) (void* data), void* data) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; function(data); jmp_buf_index--; return 1; } return 0; } static void PlatformSpecificLongJmpImplementation() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } static void PlatformSpecificRestoreJumpBufferImplementation() { jmp_buf_index--; } void (*PlatformSpecificLongJmp)() = PlatformSpecificLongJmpImplementation; int (*PlatformSpecificSetJmp)(void (*function)(void*), void*) = PlatformSpecificSetJmpImplementation; void (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferImplementation; ///////////// Time in millis /* * In Keil MDK-ARM, clock() default implementation used semihosting. * Resolutions is user adjustable (1 ms for now) */ static long TimeInMillisImplementation() { clock_t t = clock(); t = t * 10; return t; } long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; static const char* TimeStringImplementation() { time_t tm = 0;//time(NULL); // todo return ctime(&tm); } const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation; int PlatformSpecificAtoI(const char* str) { return atoi(str); } /* The ARMCC compiler will compile this function with C++ linkage, unless * we specifically tell it to use C linkage again, in the function definiton. */ extern int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list args) = vsnprintf; static PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag) { return 0; } static void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file) { printf("%s", str); } static void PlatformSpecificFCloseImplementation(PlatformSpecificFile file) { } static void PlatformSpecificFlushImplementation() { } PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation; void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation; void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation; int (*PlatformSpecificPutchar)(int) = putchar; void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation; void* (*PlatformSpecificMalloc)(size_t) = malloc; void* (*PlatformSpecificRealloc) (void*, size_t) = realloc; void (*PlatformSpecificFree)(void*) = free; void* (*PlatformSpecificMemCpy)(void* s1, const void* s2, size_t size) = memcpy; void* (*PlatformSpecificMemset)(void*, int, size_t) = memset; static int IsNanImplementation(double d) { # ifdef __MICROLIB return 0; # else return isnan(d); # endif } static int IsInfImplementation(double d) { # ifdef __MICROLIB return 0; # else return isinf(d); # endif } int DummyAtExit(void(*)(void)) { return 0; } double (*PlatformSpecificFabs)(double) = abs; int (*PlatformSpecificIsNan)(double) = IsNanImplementation; int (*PlatformSpecificIsInf)(double) = IsInfImplementation; int (*PlatformSpecificAtExit)(void(*func)(void)) = DummyAtExit; static PlatformSpecificMutex DummyMutexCreate(void) { return 0; } static void DummyMutexLock(PlatformSpecificMutex mtx) { } static void DummyMutexUnlock(PlatformSpecificMutex mtx) { } static void DummyMutexDestroy(PlatformSpecificMutex mtx) { } PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = DummyMutexCreate; void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy; }
null
492
cpp
cpputest-stm32-keil-demo
TestRegistry.cpp
Middlewares/Third_Party/CPPUTEST/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" TestRegistry::TestRegistry() : tests_(NULL), nameFilters_(NULL), groupFilters_(NULL), 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 != NULL; 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 != NULL; 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 != NULL; 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()); } bool TestRegistry::endOfGroup(UtestShell* test) { return (!test || !test->getNext() || test->getGroup() != test->getNext()->getGroup()); } int TestRegistry::countTests() { return tests_ ? tests_->countTests() : 0; } TestRegistry* TestRegistry::currentRegistry_ = 0; TestRegistry* TestRegistry::getCurrentRegistry() { static TestRegistry registry; return (currentRegistry_ == 0) ? &registry : currentRegistry_; } void TestRegistry::setCurrentRegistry(TestRegistry* registry) { currentRegistry_ = registry; } void TestRegistry::unDoLastAddTest() { tests_ = tests_ ? tests_->getNext() : NULL; } 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_; } 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 NULL; } UtestShell* TestRegistry::findTestWithGroup(const SimpleString& group) { UtestShell* current = tests_; while (current) { if (current->getGroup() == group) return current; current = current->getNext(); } return NULL; }
null
493
cpp
cpputest-stm32-keil-demo
TestOutput.cpp
Middlewares/Third_Party/CPPUTEST/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_(false), color_(false), progressIndication_(".") { } TestOutput::~TestOutput() { } void TestOutput::verbose() { verbose_ = true; } void TestOutput::color() { color_ = true; } void TestOutput::print(const char* str) { printBuffer(str); } void TestOutput::print(long n) { print(StringFrom(n).asCharString()); } void TestOutput::printDouble(double d) { print(StringFrom(d).asCharString()); } TestOutput& operator<<(TestOutput& p, const char* s) { p.print(s); return p; } TestOutput& operator<<(TestOutput& p, long int i) { p.print(i); return p; } void TestOutput::printCurrentTestStarted(const UtestShell& test) { if (verbose_) print(test.getFormattedName().asCharString()); if (test.willRun()) { setProgressIndicator("."); } else { setProgressIndicator("!"); } } void TestOutput::printCurrentTestEnded(const TestResult& res) { if (verbose_) { print(" - "); print(res.getCurrentTestTotalExecutionTime()); print(" ms\n"); } else { printProgressIndicator(); } } void TestOutput::printProgressIndicator() { print(progressIndication_); if (++dotCount_ % 50 == 0) print("\n"); } void TestOutput::setProgressIndicator(const char* indicator) { progressIndication_ = indicator; } void TestOutput::printTestsStarted() { } void TestOutput::printCurrentGroupStarted(const UtestShell& /*test*/) { } void TestOutput::printCurrentGroupEnded(const TestResult& /*res*/) { } void TestOutput::printTestsEnded(const TestResult& result) { print("\n"); if (result.getFailureCount() > 0) { if (color_) { print("\033[31;1m"); } print("Errors ("); print(result.getFailureCount()); print(" failures, "); } 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"); } print("\n\n"); } void TestOutput::printTestRun(int number, int total) { if (total > 1) { print("Test run "); print(number); print(" of "); print(total); print("\n"); } } void TestOutput::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, int lineNumber) { if (TestOutput::getWorkingEnvironment() == TestOutput::visualStudio) printVisualStudioErrorInFileOnLine(file, lineNumber); else printEclipseErrorInFileOnLine(file, lineNumber); } void TestOutput::printEclipseErrorInFileOnLine(SimpleString file, int lineNumber) { print("\n"); print(file.asCharString()); print(":"); print(lineNumber); print(":"); print(" error:"); } void TestOutput::printVisualStudioErrorInFileOnLine(SimpleString file, int lineNumber) { print("\n"); print(file.asCharString()); print("("); print(lineNumber); print("):"); print(" error:"); } void ConsoleTestOutput::printBuffer(const char* s) { while (*s) { PlatformSpecificPutchar(*s); s++; } flush(); } void ConsoleTestOutput::flush() { PlatformSpecificFlush(); } StringBufferTestOutput::~StringBufferTestOutput() { } CompositeTestOutput::CompositeTestOutput() : outputOne_(NULL), outputTwo_(NULL) { } 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() { if (outputOne_) outputOne_->verbose(); if (outputTwo_) outputTwo_->verbose(); } 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::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::flush() { if (outputOne_) outputOne_->flush(); if (outputTwo_) outputTwo_->flush(); }
null
494
cpp
cpputest-stm32-keil-demo
TestMemoryAllocator.cpp
Middlewares/Third_Party/CPPUTEST/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 == 0) FAIL("malloc returned null pointer"); return mem; } static TestMemoryAllocator* currentNewAllocator = 0; static TestMemoryAllocator* currentNewArrayAllocator = 0; static TestMemoryAllocator* currentMallocAllocator = 0; void setCurrentNewAllocator(TestMemoryAllocator* allocator) { currentNewAllocator = allocator; } TestMemoryAllocator* getCurrentNewAllocator() { if (currentNewAllocator == 0) setCurrentNewAllocatorToDefault(); return currentNewAllocator; } void setCurrentNewAllocatorToDefault() { currentNewAllocator = defaultNewAllocator(); } TestMemoryAllocator* defaultNewAllocator() { static TestMemoryAllocator allocator("Standard New Allocator", "new", "delete"); return &allocator; } void setCurrentNewArrayAllocator(TestMemoryAllocator* allocator) { currentNewArrayAllocator = allocator; } TestMemoryAllocator* getCurrentNewArrayAllocator() { if (currentNewArrayAllocator == 0) setCurrentNewArrayAllocatorToDefault(); return currentNewArrayAllocator; } void setCurrentNewArrayAllocatorToDefault() { currentNewArrayAllocator = defaultNewArrayAllocator(); } TestMemoryAllocator* defaultNewArrayAllocator() { static TestMemoryAllocator allocator("Standard New [] Allocator", "new []", "delete []"); return &allocator; } void setCurrentMallocAllocator(TestMemoryAllocator* allocator) { currentMallocAllocator = allocator; } TestMemoryAllocator* getCurrentMallocAllocator() { if (currentMallocAllocator == 0) setCurrentMallocAllocatorToDefault(); return currentMallocAllocator; } void setCurrentMallocAllocatorToDefault() { currentMallocAllocator = defaultMallocAllocator(); } TestMemoryAllocator* defaultMallocAllocator() { static TestMemoryAllocator allocator("Standard Malloc Allocator", "malloc", "free"); return &allocator; } ///////////////////////////////////////////// TestMemoryAllocator::TestMemoryAllocator(const char* name_str, const char* alloc_name_str, const char* free_name_str) : name_(name_str), alloc_name_(alloc_name_str), free_name_(free_name_str), hasBeenDestroyed_(false) { } TestMemoryAllocator::~TestMemoryAllocator() { hasBeenDestroyed_ = true; } bool TestMemoryAllocator::hasBeenDestroyed() { return hasBeenDestroyed_; } bool TestMemoryAllocator::isOfEqualType(TestMemoryAllocator* allocator) { return 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, "MemoryLeakNode", 1); } char* TestMemoryAllocator::alloc_memory(size_t size, const char*, int) { return checkedMalloc(size); } void TestMemoryAllocator::free_memory(char* memory, const char*, int) { PlatformSpecificFree(memory); } const char* TestMemoryAllocator::name() { return name_; } const char* TestMemoryAllocator::alloc_name() { return alloc_name_; } const char* TestMemoryAllocator::free_name() { return free_name_; } CrashOnAllocationAllocator::CrashOnAllocationAllocator() : allocationToCrashOn_(0) { } void CrashOnAllocationAllocator::setNumberToCrashOn(unsigned allocationToCrashOn) { allocationToCrashOn_ = allocationToCrashOn; } char* CrashOnAllocationAllocator::alloc_memory(size_t size, const char* file, int line) { if (MemoryLeakWarningPlugin::getGlobalDetector()->getCurrentAllocationNumber() == allocationToCrashOn_) UT_CRASH(); return TestMemoryAllocator::alloc_memory(size, file, line); } char* NullUnknownAllocator::alloc_memory(size_t /*size*/, const char*, int) { return 0; } void NullUnknownAllocator::free_memory(char* /*memory*/, const char*, int) { } NullUnknownAllocator::NullUnknownAllocator() : TestMemoryAllocator("Null Allocator", "unknown", "unknown") { } TestMemoryAllocator* NullUnknownAllocator::defaultAllocator() { static NullUnknownAllocator allocator; return &allocator; } class LocationToFailAllocNode { public: int allocNumberToFail_; int actualAllocNumber_; const char* file_; int line_; LocationToFailAllocNode* next_; void failAtAllocNumber(int number, LocationToFailAllocNode* next) { init(next); allocNumberToFail_ = number; } void failNthAllocAt(int allocationNumber, const char* file, int line, LocationToFailAllocNode* next) { init(next); allocNumberToFail_ = allocationNumber; file_ = file; line_ = line; } bool shouldFail(int allocationNumber, const char* file, int 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 = NULL) { allocNumberToFail_ = 0; actualAllocNumber_ = 0; file_ = NULL; line_ = 0; next_ = next; } }; FailableMemoryAllocator::FailableMemoryAllocator(const char* name_str, const char* alloc_name_str, const char* free_name_str) : TestMemoryAllocator(name_str, alloc_name_str, free_name_str), head_(NULL), currentAllocNumber_(0) { } 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, int line) { LocationToFailAllocNode* newNode = (LocationToFailAllocNode*) (void*) allocMemoryLeakNode(sizeof(LocationToFailAllocNode)); newNode->failNthAllocAt(allocationNumber, file, line, head_); head_ = newNode; } char* FailableMemoryAllocator::alloc_memory(size_t size, const char* file, int line) { currentAllocNumber_++; LocationToFailAllocNode* current = head_; LocationToFailAllocNode* previous = NULL; while (current) { if (current->shouldFail(currentAllocNumber_, file, line)) { if (previous) previous->next_ = current->next_; else head_ = current->next_; free_memory((char*) current, __FILE__, __LINE__); return NULL; } 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_, head_->line_); else failText = StringFromFormat("Expected allocation number %d was never done", head_->allocNumberToFail_); currentTest->failWith(FailFailure(currentTest, currentTest->getName().asCharString(), currentTest->getLineNumber(), failText), TestTerminatorWithoutExceptions()); } } void FailableMemoryAllocator::clearFailedAllocs() { LocationToFailAllocNode* current = head_; while (current) { head_ = current->next_; free_memory((char*) current, __FILE__, __LINE__); current = head_; } currentAllocNumber_ = 0; }
null
495
cpp
cpputest-stm32-keil-demo
CommandLineArguments.cpp
Middlewares/Third_Party/CPPUTEST/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** av) : ac_(ac), av_(av), verbose_(false), color_(false), runTestsAsSeperateProcess_(false), listTestGroupNames_(false), listTestGroupAndCaseNames_(false), runIgnored_(false), repeat_(1), groupFilters_(NULL), nameFilters_(NULL), outputType_(OUTPUT_ECLIPSE) { } CommandLineArguments::~CommandLineArguments() { 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 == "-v") verbose_ = true; else if (argument == "-c") color_ = true; else if (argument == "-p") runTestsAsSeperateProcess_ = true; else if (argument == "-lg") listTestGroupNames_ = true; else if (argument == "-ln") listTestGroupAndCaseNames_ = true; else if (argument == "-ri") runIgnored_ = true; else if (argument.startsWith("-r")) SetRepeatCount(ac_, av_, i); else if (argument.startsWith("-g")) AddGroupFilter(ac_, av_, i); else if (argument.startsWith("-sg")) AddStrictGroupFilter(ac_, av_, i); else if (argument.startsWith("-xg")) AddExcludeGroupFilter(ac_, av_, i); else if (argument.startsWith("-xsg")) AddExcludeStrictGroupFilter(ac_, av_, i); else if (argument.startsWith("-n")) AddNameFilter(ac_, av_, i); else if (argument.startsWith("-sn")) AddStrictNameFilter(ac_, av_, i); else if (argument.startsWith("-xn")) AddExcludeNameFilter(ac_, av_, i); else if (argument.startsWith("-xsn")) AddExcludeStrictNameFilter(ac_, av_, i); else if (argument.startsWith("TEST(")) AddTestToRunBasedOnVerboseOutput(ac_, av_, i, "TEST("); else if (argument.startsWith("IGNORE_TEST(")) AddTestToRunBasedOnVerboseOutput(ac_, av_, i, "IGNORE_TEST("); else if (argument.startsWith("-o")) correctParameters = SetOutputType(ac_, av_, i); else if (argument.startsWith("-p")) correctParameters = plugin->parseAllArguments(ac_, av_, i); else if (argument.startsWith("-k")) SetPackageName(ac_, av_, i); else correctParameters = false; if (correctParameters == false) { return false; } } return true; } const char* CommandLineArguments::usage() const { return "usage [-v] [-c] [-p] [-lg] [-ln] [-ri] [-r#] [-g|sg|xg|xsg groupName]... [-n|sn|xn|xsn testName]... [\"TEST(groupName, testName)\"]... [-o{normal, junit, teamcity}] [-k packageName]\n"; } bool CommandLineArguments::isVerbose() const { return verbose_; } bool CommandLineArguments::isColor() const { return color_; } bool CommandLineArguments::isListingTestGroupNames() const { return listTestGroupNames_; } bool CommandLineArguments::isListingTestGroupAndCaseNames() const { return listTestGroupAndCaseNames_; } bool CommandLineArguments::isRunIgnored() const { return runIgnored_; } bool CommandLineArguments::runTestsInSeperateProcess() const { return runTestsAsSeperateProcess_; } int CommandLineArguments::getRepeatCount() const { return repeat_; } const TestFilter* CommandLineArguments::getGroupFilters() const { return groupFilters_; } const TestFilter* CommandLineArguments::getNameFilters() const { return nameFilters_; } void CommandLineArguments::SetRepeatCount(int ac, const char** av, int& i) { repeat_ = 0; SimpleString repeatParameter(av[i]); if (repeatParameter.size() > 2) repeat_ = SimpleString::AtoI(av[i] + 2); else if (i + 1 < ac) { repeat_ = SimpleString::AtoI(av[i + 1]); if (repeat_ != 0) i++; } if (0 == repeat_) repeat_ = 2; } SimpleString CommandLineArguments::getParameterField(int ac, const char** av, int& i, const SimpleString& parameterName) { size_t parameterLength = parameterName.size(); SimpleString parameter(av[i]); if (parameter.size() > parameterLength) return av[i] + parameterLength; else if (i + 1 < ac) return av[++i]; return ""; } void CommandLineArguments::AddGroupFilter(int ac, const char** av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-g")); groupFilters_ = groupFilter->add(groupFilters_); } void CommandLineArguments::AddStrictGroupFilter(int ac, const char** av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-sg")); groupFilter->strictMatching(); groupFilters_ = groupFilter->add(groupFilters_); } void CommandLineArguments::AddExcludeGroupFilter(int ac, const char** av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-xg")); groupFilter->invertMatching(); groupFilters_ = groupFilter->add(groupFilters_); } void CommandLineArguments::AddExcludeStrictGroupFilter(int ac, const char** av, int& i) { TestFilter* groupFilter = new TestFilter(getParameterField(ac, av, i, "-xsg")); groupFilter->strictMatching(); groupFilter->invertMatching(); groupFilters_ = groupFilter->add(groupFilters_); } void CommandLineArguments::AddNameFilter(int ac, const char** av, int& i) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, i, "-n")); nameFilters_ = nameFilter->add(nameFilters_); } void CommandLineArguments::AddStrictNameFilter(int ac, const char** av, int& index) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, index, "-sn")); nameFilter->strictMatching(); nameFilters_= nameFilter->add(nameFilters_); } void CommandLineArguments::AddExcludeNameFilter(int ac, const char** av, int& index) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, index, "-xn")); nameFilter->invertMatching(); nameFilters_= nameFilter->add(nameFilters_); } void CommandLineArguments::AddExcludeStrictNameFilter(int ac, const char** av, int& index) { TestFilter* nameFilter = new TestFilter(getParameterField(ac, av, index, "-xsn")); nameFilter->invertMatching(); nameFilter->strictMatching(); nameFilters_= nameFilter->add(nameFilters_); } void CommandLineArguments::AddTestToRunBasedOnVerboseOutput(int ac, const char** av, int& index, const char* parameterName) { SimpleString wholename = getParameterField(ac, av, index, parameterName); SimpleString testname = wholename.subStringFromTill(',', ')'); testname = testname.subString(2, testname.size()); 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** av, int& i) { SimpleString packageName = getParameterField(ac, av, i, "-k"); if (packageName.size() == 0) return; packageName_ = packageName; } bool CommandLineArguments::SetOutputType(int ac, const char** av, int& i) { SimpleString outputType = getParameterField(ac, av, i, "-o"); if (outputType.size() == 0) return false; if (outputType == "normal" || outputType == "eclipse") { outputType_ = OUTPUT_ECLIPSE; return true; } if (outputType == "junit") { outputType_ = OUTPUT_JUNIT; return true; } 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
496
cpp
cpputest-stm32-keil-demo
JUnitTestOutput.cpp
Middlewares/Third_Party/CPPUTEST/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_(0), ignored_(false), next_(0) { } SimpleString name_; long execTime_; TestFailure* failure_; bool ignored_; JUnitTestCaseResultNode* next_; }; struct JUnitTestGroupResult { JUnitTestGroupResult() : testCount_(0), failureCount_(0), startTime_(0), groupExecTime_(0), head_(0), tail_(0) { } int testCount_; int failureCount_; long startTime_; long groupExecTime_; SimpleString group_; JUnitTestCaseResultNode* head_; JUnitTestCaseResultNode* tail_; }; struct JUnitTestOutputImpl { JUnitTestGroupResult results_; PlatformSpecificFile file_; SimpleString package_; }; JUnitTestOutput::JUnitTestOutput() : impl_(new JUnitTestOutputImpl) { } JUnitTestOutput::~JUnitTestOutput() { resetTestGroupResult(); delete impl_; } void JUnitTestOutput::resetTestGroupResult() { impl_->results_.testCount_ = 0; impl_->results_.failureCount_ = 0; impl_->results_.group_ = ""; JUnitTestCaseResultNode* cur = impl_->results_.head_; while (cur) { JUnitTestCaseResultNode* tmp = cur->next_; ; delete cur->failure_; delete cur; cur = tmp; } impl_->results_.head_ = 0; impl_->results_.tail_ = 0; } void JUnitTestOutput::printTestsStarted() { } void JUnitTestOutput::printCurrentGroupStarted(const UtestShell& /*test*/) { } void JUnitTestOutput::printCurrentTestEnded(const TestResult& result) { impl_->results_.tail_->execTime_ = result.getCurrentTestTotalExecutionTime(); } void JUnitTestOutput::printTestsEnded(const TestResult& /*result*/) { } void JUnitTestOutput::printCurrentGroupEnded(const TestResult& result) { impl_->results_.groupExecTime_ = result.getCurrentGroupTotalExecutionTime(); writeTestGroupToFile(); resetTestGroupResult(); } void JUnitTestOutput::printCurrentTestStarted(const UtestShell& test) { impl_->results_.testCount_++; impl_->results_.group_ = test.getGroup(); impl_->results_.startTime_ = GetPlatformSpecificTimeInMillis(); if (impl_->results_.tail_ == 0) { impl_->results_.head_ = impl_->results_.tail_ = new JUnitTestCaseResultNode; } else { impl_->results_.tail_->next_ = new JUnitTestCaseResultNode; impl_->results_.tail_ = impl_->results_.tail_->next_; } impl_->results_.tail_->name_ = test.getName(); if (!test.willRun()) { impl_->results_.tail_->ignored_ = true; } } SimpleString JUnitTestOutput::createFileName(const SimpleString& group) { SimpleString fileName = "cpputest_"; fileName += group; fileName.replace('/', '_'); fileName += ".xml"; return fileName; } void JUnitTestOutput::setPackageName(const SimpleString& package) { if (impl_ != NULL) { impl_->package_ = package; } } void JUnitTestOutput::writeXmlHeader() { writeToFile("<?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", impl_->results_.failureCount_, impl_->results_.group_.asCharString(), impl_->results_.testCount_, (int) (impl_->results_.groupExecTime_ / 1000), (int) (impl_->results_.groupExecTime_ % 1000), GetPlatformSpecificTimeString()); writeToFile(buf.asCharString()); } void JUnitTestOutput::writeProperties() { writeToFile("<properties>\n"); writeToFile("</properties>\n"); } void JUnitTestOutput::writeTestCases() { JUnitTestCaseResultNode* cur = impl_->results_.head_; while (cur) { SimpleString buf = StringFromFormat( "<testcase classname=\"%s%s%s\" name=\"%s\" time=\"%d.%03d\">\n", impl_->package_.asCharString(), impl_->package_.isEmpty() == true ? "" : ".", impl_->results_.group_.asCharString(), cur->name_.asCharString(), (int) (cur->execTime_ / 1000), (int)(cur->execTime_ % 1000)); writeToFile(buf.asCharString()); if (cur->failure_) { writeFailure(cur); } else if (cur->ignored_) { writeToFile("<skipped />\n"); } writeToFile("</testcase>\n"); cur = cur->next_; } } void JUnitTestOutput::writeFailure(JUnitTestCaseResultNode* node) { SimpleString message = node->failure_->getMessage().asCharString(); message.replace('"', '\''); message.replace('<', '['); message.replace('>', ']'); message.replace("&", "&amp;"); message.replace("\n", "{newline}"); SimpleString buf = StringFromFormat( "<failure message=\"%s:%d: %s\" type=\"AssertionFailedError\">\n", node->failure_->getFileName().asCharString(), node->failure_->getFailureLineNumber(), message.asCharString()); writeToFile(buf.asCharString()); writeToFile("</failure>\n"); } void JUnitTestOutput::writeFileEnding() { writeToFile("<system-out></system-out>\n"); writeToFile("<system-err></system-err>\n"); writeToFile("</testsuite>"); } 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*) { } void JUnitTestOutput::print(long) { } void JUnitTestOutput::flush() { } // LCOV_EXCL_STOP void JUnitTestOutput::printFailure(const TestFailure& failure) { if (impl_->results_.tail_->failure_ == 0) { 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
497
cpp
cpputest-stm32-keil-demo
Utest.cpp
Middlewares/Third_Party/CPPUTEST/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" 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() { } 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); } } /******************************** */ UtestShell::UtestShell() : group_("UndefinedTestGroup"), name_("UndefinedTest"), file_("UndefinedFile"), lineNumber_(0), next_(NULL), isRunAsSeperateProcess_(false), hasFailed_(false) { } UtestShell::UtestShell(const char* groupName, const char* testName, const char* fileName, int lineNumber) : group_(groupName), name_(testName), file_(fileName), lineNumber_(lineNumber), next_(NULL), isRunAsSeperateProcess_(false), hasFailed_(false) { } UtestShell::UtestShell(const char* groupName, const char* testName, const char* fileName, int lineNumber, UtestShell* nextTest) : group_(groupName), name_(testName), file_(fileName), lineNumber_(lineNumber), next_(nextTest), isRunAsSeperateProcess_(false), hasFailed_(false) { } UtestShell::~UtestShell() { } // LCOV_EXCL_START - actually covered but not in .gcno due to race condition static void defaultCrashMethod() { UtestShell* ptr = (UtestShell*) 0x0; ptr->countTests(); } // LCOV_EXCL_STOP static void (*pleaseCrashMeRightNow) () = defaultCrashMethod; void UtestShell::setCrashMethod(void (*crashme)()) { pleaseCrashMeRightNow = crashme; } void UtestShell::resetCrashMethod() { pleaseCrashMeRightNow = defaultCrashMethod; } void UtestShell::crash() { pleaseCrashMeRightNow(); } void UtestShell::runOneTest(TestPlugin* plugin, TestResult& result) { hasFailed_ = false; 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) { plugin->runAllPreTestAction(*this, result); //save test context, so that test class can be tested UtestShell* savedTest = UtestShell::getCurrent(); TestResult* savedResult = UtestShell::getTestResult(); result.countRun(); UtestShell::setTestResult(&result); UtestShell::setCurrentTest(this); Utest* testToRun = createTest(); testToRun->run(); destroyTest(testToRun); UtestShell::setCurrentTest(savedTest); UtestShell::setTestResult(savedResult); plugin->runAllPostTestAction(*this, result); } UtestShell *UtestShell::getNext() const { return next_; } UtestShell* UtestShell::addTest(UtestShell *test) { next_ = test; return this; } int 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(int 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_); } int UtestShell::getLineNumber() const { return lineNumber_; } bool UtestShell::match(const char* target, const TestFilter* filters) const { if(filters == NULL) return true; for(; filters != NULL; 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, NormalTestTerminator()); } // LCOV_EXCL_LINE void UtestShell::failWith(const TestFailure& failure, const TestTerminator& terminator) { hasFailed_ = true; getTestResult()->addFailure(failure); terminator.exitCurrentTest(); } // LCOV_EXCL_LINE void UtestShell::exitTest(const TestTerminator& terminator) { terminator.exitCurrentTest(); } // LCOV_EXCL_LINE void UtestShell::assertTrue(bool condition, const char *checkString, const char *conditionString, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (!condition) failWith(CheckFailure(this, fileName, lineNumber, checkString, conditionString, text), testTerminator); } void UtestShell::fail(const char *text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); failWith(FailFailure(this, fileName, lineNumber, text), testTerminator); } // LCOV_EXCL_LINE void UtestShell::assertCstrEqual(const char* expected, const char* actual, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if (actual == 0 || expected == 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); if (SimpleString::StrCmp(expected, actual) != 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); } void UtestShell::assertCstrNEqual(const char* expected, const char* actual, size_t length, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if (actual == 0 || expected == 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); if (SimpleString::StrNCmp(expected, actual, length) != 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual, text), testTerminator); } void UtestShell::assertCstrNoCaseEqual(const char* expected, const char* actual, const char* text, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if (actual == 0 || expected == 0) failWith(StringEqualNoCaseFailure(this, fileName, lineNumber, expected, actual, text)); if (!SimpleString(expected).equalsNoCase(actual)) failWith(StringEqualNoCaseFailure(this, fileName, lineNumber, expected, actual, text)); } void UtestShell::assertCstrContains(const char* expected, const char* actual, const char* text, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if(actual == 0 || expected == 0) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); if (!SimpleString(actual).contains(expected)) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); } void UtestShell::assertCstrNoCaseContains(const char* expected, const char* actual, const char* text, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if(actual == 0 || expected == 0) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); if (!SimpleString(actual).containsNoCase(expected)) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual, text)); } void UtestShell::assertLongsEqual(long expected, long actual, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(LongsEqualFailure (this, fileName, lineNumber, expected, actual, text), testTerminator); } void UtestShell::assertUnsignedLongsEqual(unsigned long expected, unsigned long actual, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(UnsignedLongsEqualFailure (this, fileName, lineNumber, expected, actual, text), testTerminator); } void UtestShell::assertLongLongsEqual(cpputest_longlong expected, cpputest_longlong actual, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); #ifdef 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, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); #ifdef 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, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(SignedBytesEqualFailure (this, fileName, lineNumber, expected, actual, text), testTerminator); } void UtestShell::assertPointersEqual(const void* expected, const void* actual, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(EqualsFailure(this, fileName, lineNumber, StringFrom(expected), StringFrom(actual), text), testTerminator); } void UtestShell::assertFunctionPointersEqual(void (*expected)(), void (*actual)(), const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (expected != actual) failWith(EqualsFailure(this, fileName, lineNumber, StringFrom(expected), StringFrom(actual), text), testTerminator); } void UtestShell::assertDoublesEqual(double expected, double actual, double threshold, const char* text, const char* fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (!doubles_equal(expected, actual, threshold)) failWith(DoublesEqualFailure(this, fileName, lineNumber, expected, actual, threshold, text), testTerminator); } void UtestShell::assertBinaryEqual(const void *expected, const void *actual, size_t length, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if (actual == 0 || expected == 0) failWith(BinaryEqualFailure(this, fileName, lineNumber, (const unsigned char *) expected, (const unsigned char *) actual, length, text), testTerminator); if (SimpleString::MemCmp(expected, actual, length) != 0) failWith(BinaryEqualFailure(this, fileName, lineNumber, (const unsigned char *) expected, (const unsigned char *) actual, length, text), testTerminator); } void UtestShell::assertBitsEqual(unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const char* text, const char *fileName, int lineNumber, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if ((expected & mask) != (actual & mask)) failWith(BitsEqualFailure(this, fileName, lineNumber, expected, actual, mask, byteCount, text), testTerminator); } void UtestShell::assertEquals(bool failed, const char* expected, const char* actual, const char* text, const char* file, int line, const TestTerminator& testTerminator) { getTestResult()->countCheck(); if (failed) failWith(CheckEqualFailure(this, file, line, expected, actual, text), testTerminator); } void UtestShell::print(const char *text, const char* fileName, int 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, int lineNumber) { print(text.asCharString(), fileName, lineNumber); } TestResult* UtestShell::testResult_ = NULL; UtestShell* UtestShell::currentTest_ = NULL; void UtestShell::setTestResult(TestResult* result) { testResult_ = result; } void UtestShell::setCurrentTest(UtestShell* test) { currentTest_ = test; } TestResult* UtestShell::getTestResult() { if (testResult_ == NULL) return &OutsideTestRunnerUTest::instance().getTestResult(); return testResult_; } UtestShell* UtestShell::getCurrent() { if (currentTest_ == NULL) return &OutsideTestRunnerUTest::instance(); return currentTest_; } ExecFunctionTestShell::~ExecFunctionTestShell() { } ////////////// Utest //////////// Utest::Utest() { } Utest::~Utest() { } #if CPPUTEST_USE_STD_CPP_LIB void Utest::run() { try { if (PlatformSpecificSetJmp(helperDoTestSetup, this)) { PlatformSpecificSetJmp(helperDoTestBody, this); } } catch (CppUTestFailedException&) { PlatformSpecificRestoreJumpBuffer(); } try { PlatformSpecificSetJmp(helperDoTestTeardown, this); } catch (CppUTestFailedException&) { PlatformSpecificRestoreJumpBuffer(); } } #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_USE_STD_CPP_LIB throw CppUTestFailedException(); #else TestTerminatorWithoutExceptions().exitCurrentTest(); #endif } NormalTestTerminator::~NormalTestTerminator() { } void TestTerminatorWithoutExceptions::exitCurrentTest() const { PlatformSpecificLongJmp(); } // LCOV_EXCL_LINE TestTerminatorWithoutExceptions::~TestTerminatorWithoutExceptions() { } //////////////////// ExecFunctionTest ExecFunctionTest::ExecFunctionTest(ExecFunctionTestShell* shell) : shell_(shell) { } void ExecFunctionTest::testBody() { if (shell_->testFunction_) shell_->testFunction_(); } 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, int 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; } ////////////// TestInstaller //////////// TestInstaller::TestInstaller(UtestShell& shell, const char* groupName, const char* testName, const char* fileName, int 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
498
cpp
cpputest-stm32-keil-demo
TestFilter.cpp
Middlewares/Third_Party/CPPUTEST/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_(NULL) { } TestFilter::TestFilter(const SimpleString& filter) : strictMatching_(false), invertMatching_(false), next_(NULL) { filter_ = filter; } TestFilter::TestFilter(const char* filter) : strictMatching_(false), invertMatching_(false), next_(NULL) { 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
499
cpp
cpputest-stm32-keil-demo
MemoryLeakDetector.cpp
Middlewares/Third_Party/CPPUTEST/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" #define UNKNOWN ((char*)("<unknown>")) 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, ...) { int count = 0; size_t positions_left = write_limit_ - positions_filled_; if (positions_left <= 0) return; va_list arguments; va_start(arguments, format); count = PlatformSpecificVSNprintf(buffer_ + positions_filled_, positions_left+1, format, arguments); if (count > 0) positions_filled_ += (size_t) count; if (positions_filled_ > write_limit_) positions_filled_ = write_limit_; va_end(arguments); } 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, int allocationLineNumber, size_t allocationSize, TestMemoryAllocator* allocator) { outputBuffer_.add(" allocated at file: %s line: %d size: %lu type: %s\n", allocationFile, allocationLineNumber, (unsigned long) allocationSize, allocator->alloc_name()); } void MemoryLeakOutputStringBuffer::addDeallocationLocation(const char* freeFile, int freeLineNumber, TestMemoryAllocator* allocator) { outputBuffer_.add(" deallocated at file: %s line: %d type: %s\n", freeFile, freeLineNumber, allocator->free_name()); } void MemoryLeakOutputStringBuffer::addNoMemoryLeaksMessage() { outputBuffer_.add("No memory leaks were detected."); } void MemoryLeakOutputStringBuffer::startMemoryLeakReporting() { giveWarningOnUsingMalloc_ = false; total_leaks_ = 0; size_t memory_leak_normal_footer_size = sizeof(MEM_LEAK_FOOTER) + 10 + sizeof(MEM_LEAK_TOO_MUCH); /* the number of leaks */ size_t memory_leak_foot_size_with_malloc_warning = memory_leak_normal_footer_size + sizeof(MEM_LEAK_ADDITION_MALLOC_WARNING); outputBuffer_.setWriteLimit(SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN - memory_leak_foot_size_with_malloc_warning); } void MemoryLeakOutputStringBuffer::reportMemoryLeak(MemoryLeakDetectorNode* leak) { if (total_leaks_ == 0) { addMemoryLeakHeader(); } total_leaks_++; outputBuffer_.add("Alloc num (%u) Leak size: %lu Allocated at: %s and line: %d. Type: \"%s\"\n\tMemory: <%p> Content:\n", leak->number_, (unsigned long) leak->size_, leak->file_, 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(int amountOfLeaks) { outputBuffer_.add("%s %d\n", MEM_LEAK_FOOTER, amountOfLeaks); } void MemoryLeakOutputStringBuffer::addWarningForUsingMalloc() { outputBuffer_.add(MEM_LEAK_ADDITION_MALLOC_WARNING); } void MemoryLeakOutputStringBuffer::reportDeallocateNonAllocatedMemoryFailure(const char* freeFile, int freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) { reportFailure("Deallocating non-allocated memory\n", "<unknown>", 0, 0, NullUnknownAllocator::defaultAllocator(), freeFile, freeLine, freeAllocator, reporter); } void MemoryLeakOutputStringBuffer::reportAllocationDeallocationMismatchFailure(MemoryLeakDetectorNode* node, const char* freeFile, int freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) { reportFailure("Allocation/deallocation type mismatch\n", node->file_, node->line_, node->size_, node->allocator_, freeFile, freeLineNumber, freeAllocator, reporter); } void MemoryLeakOutputStringBuffer::reportMemoryCorruptionFailure(MemoryLeakDetectorNode* node, const char* freeFile, int freeLineNumber, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) { reportFailure("Memory corruption (written out of bounds?)\n", node->file_, node->line_, node->size_, node->allocator_, freeFile, freeLineNumber, freeAllocator, reporter); } void MemoryLeakOutputStringBuffer::reportFailure(const char* message, const char* allocFile, int allocLine, size_t allocSize, TestMemoryAllocator* allocAllocator, const char* freeFile, int freeLine, TestMemoryAllocator* freeAllocator, MemoryLeakFailure* reporter) { outputBuffer_.add("%s", message); addAllocationLocation(allocFile, allocLine, allocSize, allocAllocator); addDeallocationLocation(freeFile, freeLine, freeAllocator); reporter->fail(toString()); } char* MemoryLeakOutputStringBuffer::toString() { return outputBuffer_.toString(); } void MemoryLeakOutputStringBuffer::clear() { outputBuffer_.clear(); } //////////////////////// void MemoryLeakDetectorNode::init(char* memory, unsigned number, size_t size, TestMemoryAllocator* allocator, MemLeakPeriod period, const char* file, int line) { number_ = number; memory_ = memory; size_ = size; allocator_ = allocator; period_ = period; file_ = file; line_ = line; } /////////////////////// bool MemoryLeakDetectorList::isInPeriod(MemoryLeakDetectorNode* node, MemLeakPeriod period) { return period == mem_leak_period_all || node->period_ == period || (node->period_ != mem_leak_period_disabled && period == mem_leak_period_enabled); } void MemoryLeakDetectorList::clearAllAccounting(MemLeakPeriod period) { MemoryLeakDetectorNode* cur = head_; MemoryLeakDetectorNode* prev = 0; while (cur) { if (isInPeriod(cur, period)) { if (prev) { prev->next_ = cur->next_; cur = prev; } else { head_ = cur->next_; cur = head_; continue; } } prev = cur; cur = cur->next_; } } void MemoryLeakDetectorList::addNewNode(MemoryLeakDetectorNode* node) { node->next_ = head_; head_ = node; } MemoryLeakDetectorNode* MemoryLeakDetectorList::removeNode(char* memory) { MemoryLeakDetectorNode* cur = head_; MemoryLeakDetectorNode* prev = 0; while (cur) { if (cur->memory_ == memory) { if (prev) { prev->next_ = cur->next_; return cur; } else { head_ = cur->next_; return cur; } } prev = cur; cur = cur->next_; } return 0; } MemoryLeakDetectorNode* MemoryLeakDetectorList::retrieveNode(char* memory) { MemoryLeakDetectorNode* cur = head_; while (cur) { if (cur->memory_ == memory) return cur; cur = cur->next_; } return NULL; } MemoryLeakDetectorNode* MemoryLeakDetectorList::getLeakFrom(MemoryLeakDetectorNode* node, MemLeakPeriod period) { for (MemoryLeakDetectorNode* cur = node; cur; cur = cur->next_) if (isInPeriod(cur, period)) return cur; return 0; } MemoryLeakDetectorNode* MemoryLeakDetectorList::getFirstLeak(MemLeakPeriod period) { return getLeakFrom(head_, period); } MemoryLeakDetectorNode* MemoryLeakDetectorList::getNextLeak(MemoryLeakDetectorNode* node, MemLeakPeriod period) { return getLeakFrom(node->next_, period); } int MemoryLeakDetectorList::getTotalLeaks(MemLeakPeriod period) { int total_leaks = 0; for (MemoryLeakDetectorNode* node = head_; node; node = node->next_) { if (isInPeriod(node, period)) total_leaks++; } return total_leaks; } ///////////////////////////////////////////////////////////// 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); } int MemoryLeakDetectorTable::getTotalLeaks(MemLeakPeriod period) { int total_leaks = 0; for (int i = 0; i < hash_prime; i++) total_leaks += table_[i].getTotalLeaks(period); return total_leaks; } MemoryLeakDetectorNode* MemoryLeakDetectorTable::getFirstLeak(MemLeakPeriod period) { for (int i = 0; i < hash_prime; i++) { MemoryLeakDetectorNode* node = table_[i].getFirstLeak(period); if (node) return node; } return 0; } MemoryLeakDetectorNode* MemoryLeakDetectorTable::getNextLeak(MemoryLeakDetectorNode* leak, MemLeakPeriod period) { unsigned long i = hash(leak->memory_); MemoryLeakDetectorNode* node = table_[i].getNextLeak(leak, period); if (node) return node; for (++i; i < hash_prime; i++) { node = table_[i].getFirstLeak(period); if (node) return node; } return 0; } ///////////////////////////////////////////////////////////// MemoryLeakDetector::MemoryLeakDetector(MemoryLeakFailure* reporter) { doAllocationTypeChecking_ = true; allocationSequenceNumber_ = 1; current_period_ = mem_leak_period_disabled; reporter_ = reporter; 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; } 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_; } SimpleMutex *MemoryLeakDetector::getMutex() { return mutex_; } static size_t calculateVoidPointerAlignedSize(size_t size) { return (sizeof(void*) - (size % sizeof(void*))) + size; } size_t MemoryLeakDetector::sizeOfMemoryWithCorruptionInfo(size_t size) { return calculateVoidPointerAlignedSize(size + memory_corruption_buffer_size); } MemoryLeakDetectorNode* MemoryLeakDetector::getNodeFromMemoryPointer(char* memory, size_t memory_size) { return (MemoryLeakDetectorNode*) (void*) (memory + sizeOfMemoryWithCorruptionInfo(memory_size)); } void MemoryLeakDetector::storeLeakInformation(MemoryLeakDetectorNode * node, char *new_memory, size_t size, TestMemoryAllocator *allocator, const char *file, int line) { node->init(new_memory, allocationSequenceNumber_++, size, allocator, current_period_, file, line); addMemoryCorruptionInformation(node->memory_ + node->size_); memoryTable_.addNewNode(node); } char* MemoryLeakDetector::reallocateMemoryAndLeakInformation(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately) { char* new_memory = reallocateMemoryWithAccountingInformation(allocator, memory, size, file, line, allocatNodesSeperately); if (new_memory == NULL) return NULL; MemoryLeakDetectorNode *node = createMemoryLeakAccountingInformation(allocator, size, new_memory, allocatNodesSeperately); storeLeakInformation(node, new_memory, size, allocator, file, line); return node->memory_; } void MemoryLeakDetector::invalidateMemory(char* memory) { MemoryLeakDetectorNode* node = memoryTable_.retrieveNode(memory); if (node) PlatformSpecificMemset(memory, 0xCD, node->size_); } void MemoryLeakDetector::addMemoryCorruptionInformation(char* memory) { memory[0] = 'B'; memory[1] = 'A'; memory[2] = 'S'; } bool MemoryLeakDetector::validMemoryCorruptionInformation(char* memory) { return memory[0] == 'B' && memory[1] == 'A' && memory[2] == 'S'; } bool MemoryLeakDetector::matchingAllocation(TestMemoryAllocator *alloc_allocator, TestMemoryAllocator *free_allocator) { if (alloc_allocator == free_allocator) return true; if (!doAllocationTypeChecking_) return true; return free_allocator->isOfEqualType(alloc_allocator); } void MemoryLeakDetector::checkForCorruption(MemoryLeakDetectorNode* node, const char* file, int line, TestMemoryAllocator* allocator, bool allocateNodesSeperately) { if (!matchingAllocation(node->allocator_, allocator)) outputBuffer_.reportAllocationDeallocationMismatchFailure(node, file, line, allocator, reporter_); else if (!validMemoryCorruptionInformation(node->memory_ + node->size_)) outputBuffer_.reportMemoryCorruptionFailure(node, file, line, allocator, reporter_); else if (allocateNodesSeperately) allocator->freeMemoryLeakNode((char*) node); } char* MemoryLeakDetector::allocMemory(TestMemoryAllocator* allocator, size_t size, bool allocatNodesSeperately) { return allocMemory(allocator, size, UNKNOWN, 0, allocatNodesSeperately); } char* MemoryLeakDetector::allocateMemoryWithAccountingInformation(TestMemoryAllocator* allocator, size_t size, const char* file, int line, bool allocatNodesSeperately) { if (allocatNodesSeperately) return allocator->alloc_memory(sizeOfMemoryWithCorruptionInfo(size), file, line); else return allocator->alloc_memory(sizeOfMemoryWithCorruptionInfo(size) + sizeof(MemoryLeakDetectorNode), file, line); } char* MemoryLeakDetector::reallocateMemoryWithAccountingInformation(TestMemoryAllocator* /*allocator*/, char* memory, size_t size, const char* /*file*/, int /*line*/, bool allocatNodesSeperately) { if (allocatNodesSeperately) return (char*) PlatformSpecificRealloc(memory, sizeOfMemoryWithCorruptionInfo(size)); else return (char*) PlatformSpecificRealloc(memory, sizeOfMemoryWithCorruptionInfo(size) + sizeof(MemoryLeakDetectorNode)); } MemoryLeakDetectorNode* MemoryLeakDetector::createMemoryLeakAccountingInformation(TestMemoryAllocator* allocator, size_t size, char* memory, bool allocatNodesSeperately) { if (allocatNodesSeperately) return (MemoryLeakDetectorNode*) (void*) allocator->allocMemoryLeakNode(sizeof(MemoryLeakDetectorNode)); else return getNodeFromMemoryPointer(memory, size); } char* MemoryLeakDetector::allocMemory(TestMemoryAllocator* allocator, size_t size, const char* file, int line, bool allocatNodesSeperately) { /* With malloc, it is harder to guarantee that the allocator free is called. * This is because operator new is overloaded via linker symbols, but malloc just via #defines. * If the same allocation is used and the wrong free is called, it will deallocate the memory leak information * without the memory leak detector ever noticing it! * So, for malloc, we'll allocate the memory separately so we can detect this and give a proper error. */ char* memory = allocateMemoryWithAccountingInformation(allocator, size, file, line, allocatNodesSeperately); if (memory == NULL) return NULL; MemoryLeakDetectorNode* node = createMemoryLeakAccountingInformation(allocator, size, memory, allocatNodesSeperately); storeLeakInformation(node, memory, size, allocator, file, line); return node->memory_; } void MemoryLeakDetector::removeMemoryLeakInformationWithoutCheckingOrDeallocatingTheMemoryButDeallocatingTheAccountInformation(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately) { MemoryLeakDetectorNode* node = memoryTable_.removeNode((char*) memory); if (allocatNodesSeperately) allocator->freeMemoryLeakNode( (char*) node); } void MemoryLeakDetector::deallocMemory(TestMemoryAllocator* allocator, void* memory, const char* file, int line, bool allocatNodesSeperately) { if (memory == 0) return; MemoryLeakDetectorNode* node = memoryTable_.removeNode((char*) memory); if (node == NULL) { outputBuffer_.reportDeallocateNonAllocatedMemoryFailure(file, line, allocator, reporter_); return; } if (!allocator->hasBeenDestroyed()) { checkForCorruption(node, file, line, allocator, allocatNodesSeperately); allocator->free_memory((char*) memory, file, line); } } void MemoryLeakDetector::deallocMemory(TestMemoryAllocator* allocator, void* memory, bool allocatNodesSeperately) { deallocMemory(allocator, (char*) memory, UNKNOWN, 0, allocatNodesSeperately); } char* MemoryLeakDetector::reallocMemory(TestMemoryAllocator* allocator, char* memory, size_t size, const char* file, int line, bool allocatNodesSeperately) { if (memory) { MemoryLeakDetectorNode* node = memoryTable_.removeNode(memory); if (node == NULL) { outputBuffer_.reportDeallocateNonAllocatedMemoryFailure(file, line, allocator, reporter_); return NULL; } checkForCorruption(node, file, line, allocator, allocatNodesSeperately); } return reallocateMemoryAndLeakInformation(allocator, memory, size, file, line, allocatNodesSeperately); } void MemoryLeakDetector::ConstructMemoryLeakReport(MemLeakPeriod period) { MemoryLeakDetectorNode* leak = memoryTable_.getFirstLeak(period); outputBuffer_.startMemoryLeakReporting(); while (leak) { outputBuffer_.reportMemoryLeak(leak); leak = memoryTable_.getNextLeak(leak, period); } outputBuffer_.stopMemoryLeakReporting(); } const char* MemoryLeakDetector::report(MemLeakPeriod period) { ConstructMemoryLeakReport(period); return outputBuffer_.toString(); } void MemoryLeakDetector::markCheckingPeriodLeaksAsNonCheckingPeriod() { MemoryLeakDetectorNode* leak = memoryTable_.getFirstLeak(mem_leak_period_checking); while (leak) { if (leak->period_ == mem_leak_period_checking) leak->period_ = mem_leak_period_enabled; leak = memoryTable_.getNextLeak(leak, mem_leak_period_checking); } } int MemoryLeakDetector::totalMemoryLeaks(MemLeakPeriod period) { return memoryTable_.getTotalLeaks(period); }
null
500
cpp
cpputest-stm32-keil-demo
TestHarness_c.cpp
Middlewares/Third_Party/CPPUTEST/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_INT_LOCATION(int expected, int actual, const char* fileName, int lineNumber) { UtestShell::getCurrent()->assertLongsEqual((long)expected, (long)actual, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* fileName, int lineNumber) { UtestShell::getCurrent()->assertDoublesEqual(expected, actual, threshold, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* fileName, int lineNumber) { UtestShell::getCurrent()->assertEquals(((expected) != (actual)), StringFrom(expected).asCharString(), StringFrom(actual).asCharString(), NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); } extern void CHECK_EQUAL_C_UBYTE_LOCATION(unsigned char expected, unsigned char actual, const char* fileName, int lineNumber)\ { UtestShell::getCurrent()->assertEquals(((expected) != (actual)),StringFrom((int)expected).asCharString(), StringFrom((int) actual).asCharString(), NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_SBYTE_LOCATION(char signed expected, signed char actual, const char* fileName, int lineNumber) { UtestShell::getCurrent()->assertEquals(((expected) != (actual)),StringFrom((int)expected).asCharString(), StringFrom((int) actual).asCharString(), NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* fileName, int lineNumber) { UtestShell::getCurrent()->assertCstrEqual(expected, actual, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); } void CHECK_EQUAL_C_POINTER_LOCATION(const void* expected, const void* actual, const char* fileName, int lineNumber) { UtestShell::getCurrent()->assertPointersEqual(expected, actual, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); } extern void CHECK_EQUAL_C_BITS_LOCATION(unsigned int expected, unsigned int actual, unsigned int mask, size_t size, const char* fileName, int lineNumber) { UtestShell::getCurrent()->assertBitsEqual(expected, actual, mask, size, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); } void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, int lineNumber) { UtestShell::getCurrent()->fail(text, fileName, lineNumber, TestTerminatorWithoutExceptions()); } // LCOV_EXCL_LINE void FAIL_C_LOCATION(const char* fileName, int lineNumber) { UtestShell::getCurrent()->fail("", fileName, lineNumber, TestTerminatorWithoutExceptions()); } // LCOV_EXCL_LINE void CHECK_C_LOCATION(int condition, const char* conditionString, const char* fileName, int lineNumber) { UtestShell::getCurrent()->assertTrue(condition != 0, "CHECK_C", conditionString, NULL, fileName, lineNumber, TestTerminatorWithoutExceptions()); } enum { NO_COUNTDOWN = -1, OUT_OF_MEMORRY = 0 }; static int malloc_out_of_memory_counter = NO_COUNTDOWN; static int malloc_count = 0; void cpputest_malloc_count_reset(void) { malloc_count = 0; } int cpputest_malloc_get_count() { return malloc_count; } void cpputest_malloc_set_out_of_memory() { setCurrentMallocAllocator(NullUnknownAllocator::defaultAllocator()); } void cpputest_malloc_set_not_out_of_memory() { malloc_out_of_memory_counter = NO_COUNTDOWN; setCurrentMallocAllocatorToDefault(); } void cpputest_malloc_set_out_of_memory_countdown(int count) { malloc_out_of_memory_counter = count; if (malloc_out_of_memory_counter == OUT_OF_MEMORRY) cpputest_malloc_set_out_of_memory(); } void* cpputest_malloc(size_t size) { return cpputest_malloc_location(size, "<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, int line) { countdown(); malloc_count++; return cpputest_malloc_location_with_leak_detection(size, file, line); } void* cpputest_calloc_location(size_t num, size_t size, const char* file, int line) { void* mem = cpputest_malloc_location(num * size, file, line); if (mem) PlatformSpecificMemset(mem, 0, num*size); return mem; } void* cpputest_realloc_location(void* memory, size_t size, const char* file, int line) { return cpputest_realloc_location_with_leak_detection(memory, size, file, line); } void cpputest_free_location(void* buffer, const char* file, int line) { cpputest_free_location_with_leak_detection(buffer, file, line); } }
null