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 |
---|---|---|---|---|---|---|---|
201 | cpp | cpputest | TeamCityTestOutput.cpp | src/CppUTest/TeamCityTestOutput.cpp | null | #include "CppUTest/TestHarness.h"
#include "CppUTest/TeamCityTestOutput.h"
TeamCityTestOutput::TeamCityTestOutput() : currtest_(NULLPTR), currGroup_()
{
}
TeamCityTestOutput::~TeamCityTestOutput()
{
}
void TeamCityTestOutput::printCurrentTestStarted(const UtestShell& test)
{
print("##teamcity[testStarted name='");
printEscaped(test.getName().asCharString());
print("']\n");
if (!test.willRun()) {
print("##teamcity[testIgnored name='");
printEscaped(test.getName().asCharString());
print("']\n");
}
currtest_ = &test;
}
void TeamCityTestOutput::printCurrentTestEnded(const TestResult& res)
{
if (!currtest_)
return;
print("##teamcity[testFinished name='");
printEscaped(currtest_->getName().asCharString());
print("' duration='");
print(res.getCurrentTestTotalExecutionTime());
print("']\n");
}
void TeamCityTestOutput::printCurrentGroupStarted(const UtestShell& test)
{
currGroup_ = test.getGroup();
print("##teamcity[testSuiteStarted name='");
printEscaped(currGroup_.asCharString());
print("']\n");
}
void TeamCityTestOutput::printCurrentGroupEnded(const TestResult& /*res*/)
{
if (currGroup_ == "")
return;
print("##teamcity[testSuiteFinished name='");
printEscaped(currGroup_.asCharString());
print("']\n");
}
void TeamCityTestOutput::printEscaped(const char* s)
{
while (*s) {
char str[3];
if ((*s == '\'') || (*s == '|') || (*s == '[') || (*s == ']')) {
str[0] = '|';
str[1] = *s;
str[2] = 0;
} else if (*s == '\r') {
str[0] = '|';
str[1] = 'r';
str[2] = 0;
} else if (*s == '\n') {
str[0] = '|';
str[1] = 'n';
str[2] = 0;
} else {
str[0] = *s;
str[1] = 0;
}
printBuffer(str);
s++;
}
}
void TeamCityTestOutput::printFailure(const TestFailure& failure)
{
print("##teamcity[testFailed name='");
printEscaped(failure.getTestNameOnly().asCharString());
print("' message='");
if (failure.isOutsideTestFile() || failure.isInHelperFunction()) {
print("TEST failed (");
print(failure.getTestFileName().asCharString());
print(":");
print(failure.getTestLineNumber());
print("): ");
}
printEscaped(failure.getFileName().asCharString());
print(":");
print(failure.getFailureLineNumber());
print("' details='");
printEscaped(failure.getMessage().asCharString());
print("']\n");
}
| null |
202 | cpp | 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"
OrderedTestShell* OrderedTestShell::_orderedTestsHead = NULLPTR;
OrderedTestShell::OrderedTestShell() :
_nextOrderedTest(NULLPTR), _level(0)
{
}
OrderedTestShell::~OrderedTestShell()
{
}
int OrderedTestShell::getLevel()
{
return _level;
}
void OrderedTestShell::setLevel(int level)
{
_level = level;
}
void OrderedTestShell::setOrderedTestHead(OrderedTestShell* test)
{
_orderedTestsHead = test;
}
OrderedTestShell* OrderedTestShell::getOrderedTestHead()
{
return _orderedTestsHead;
}
bool OrderedTestShell::firstOrderedTest()
{
return (getOrderedTestHead() == NULLPTR);
}
OrderedTestShell* OrderedTestShell::addOrderedTest(OrderedTestShell* test)
{
UtestShell::addTest(test);
_nextOrderedTest = test;
return this;
}
void OrderedTestShell::addOrderedTestToHead(OrderedTestShell* test)
{
TestRegistry *reg = TestRegistry::getCurrentRegistry();
UtestShell* head = getOrderedTestHead();
if (NULLPTR == reg->getFirstTest() || head == reg->getFirstTest()) {
reg->addTest(test);
}
else {
reg->getTestWithNext(head)->addTest(test);
test->addTest(head);
}
test->_nextOrderedTest = getOrderedTestHead();
setOrderedTestHead(test);
}
OrderedTestShell* OrderedTestShell::getNextOrderedTest()
{
return _nextOrderedTest;
}
OrderedTestInstaller::OrderedTestInstaller(OrderedTestShell& test,
const char* groupName, const char* testName, const char* fileName,
size_t lineNumber, int level)
{
test.setTestName(testName);
test.setGroupName(groupName);
test.setFileName(fileName);
test.setLineNumber(lineNumber);
test.setLevel(level);
if (OrderedTestShell::firstOrderedTest()) OrderedTestShell::addOrderedTestToHead(&test);
else addOrderedTestInOrder(&test);
}
void OrderedTestInstaller::addOrderedTestInOrder(OrderedTestShell* test)
{
if (test->getLevel() < OrderedTestShell::getOrderedTestHead()->getLevel())
OrderedTestShell::addOrderedTestToHead(test);
else addOrderedTestInOrderNotAtHeadPosition(test);
}
void OrderedTestInstaller::addOrderedTestInOrderNotAtHeadPosition(
OrderedTestShell* test)
{
OrderedTestShell* current = OrderedTestShell::getOrderedTestHead();
while (current->getNextOrderedTest()) {
if (current->getNextOrderedTest()->getLevel() > test->getLevel()) {
test->addOrderedTest(current->getNextOrderedTest());
current->addOrderedTest(test);
return;
}
current = current->getNextOrderedTest();
}
test->addOrderedTest(current->getNextOrderedTest());
current->addOrderedTest(test);
}
OrderedTestInstaller::~OrderedTestInstaller()
{
}
| null |
203 | cpp | 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_(NULLPTR), realAllocator_(NULLPTR), formatter_(NULLPTR)
{
}
MemoryReportAllocator::~MemoryReportAllocator()
{
}
const char* MemoryReportAllocator::name() const
{
return "MemoryReporterAllocator";
}
const char* MemoryReportAllocator::alloc_name() const
{
return realAllocator_->alloc_name();
}
const char* MemoryReportAllocator::free_name() const
{
return realAllocator_->free_name();
}
void MemoryReportAllocator::setRealAllocator(TestMemoryAllocator* allocator)
{
realAllocator_ = allocator;
}
TestMemoryAllocator* MemoryReportAllocator::getRealAllocator()
{
return realAllocator_;
}
TestMemoryAllocator* MemoryReportAllocator::actualAllocator()
{
return realAllocator_->actualAllocator();
}
void MemoryReportAllocator::setTestResult(TestResult* result)
{
result_ = result;
}
void MemoryReportAllocator::setFormatter(MemoryReportFormatter* formatter)
{
formatter_ = formatter;
}
char* MemoryReportAllocator::alloc_memory(size_t size, const char* file, size_t 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, size_t size, const char* file, size_t line)
{
realAllocator_->free_memory(memory, size, file, line);
if (result_ && formatter_)
formatter_->report_free_memory(result_, this, memory, file, line);
}
| null |
204 | cpp | 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/MockExpectedCall.h"
#include "CppUTestExt/MockExpectedCallsList.h"
#include "CppUTestExt/MockNamedValue.h"
class MockFailureReporterTestTerminator : public TestTerminator
{
public:
MockFailureReporterTestTerminator(bool crashOnFailure) : crashOnFailure_(crashOnFailure)
{
}
virtual void exitCurrentTest() const CPPUTEST_OVERRIDE
{
if (crashOnFailure_)
UT_CRASH();
UtestShell::getCurrentTestTerminator().exitCurrentTest();
} // LCOV_EXCL_LINE
virtual ~MockFailureReporterTestTerminator() CPPUTEST_DESTRUCTOR_OVERRIDE
{
}
private:
bool crashOnFailure_;
};
void MockFailureReporter::failTest(const MockFailure& failure)
{
if (!getTestToFail()->hasFailed())
getTestToFail()->failWith(failure, MockFailureReporterTestTerminator(crashOnFailure_));
} // LCOV_EXCL_LINE
UtestShell* MockFailureReporter::getTestToFail()
{
return UtestShell::getCurrent();
}
MockFailure::MockFailure(UtestShell* test) : TestFailure(test, "Test failed with MockFailure without an error! Something went seriously wrong.")
{
}
void MockFailure::addExpectationsAndCallHistory(const MockExpectedCallsList& expectations)
{
message_ += "\tEXPECTED calls that WERE NOT fulfilled:\n";
message_ += expectations.unfulfilledCallsToString("\t\t");
message_ += "\n\tEXPECTED calls that WERE fulfilled:\n";
message_ += expectations.fulfilledCallsToString("\t\t");
}
void MockFailure::addExpectationsAndCallHistoryRelatedTo(const SimpleString& name, const MockExpectedCallsList& expectations)
{
MockExpectedCallsList expectationsForFunction;
expectationsForFunction.addExpectationsRelatedTo(name, expectations);
message_ += "\tEXPECTED calls that WERE NOT fulfilled related to function: ";
message_ += name;
message_ += "\n";
message_ += expectationsForFunction.unfulfilledCallsToString("\t\t");
message_ += "\n\tEXPECTED calls that WERE fulfilled related to function: ";
message_ += name;
message_ += "\n";
message_ += expectationsForFunction.fulfilledCallsToString("\t\t");
}
MockExpectedCallsDidntHappenFailure::MockExpectedCallsDidntHappenFailure(UtestShell* test, const MockExpectedCallsList& expectations) : MockFailure(test)
{
message_ = "Mock Failure: Expected call WAS NOT fulfilled.\n";
addExpectationsAndCallHistory(expectations);
}
MockUnexpectedCallHappenedFailure::MockUnexpectedCallHappenedFailure(UtestShell* test, const SimpleString& name, const MockExpectedCallsList& expectations) : MockFailure(test)
{
unsigned int amountOfActualCalls = expectations.amountOfActualCallsFulfilledFor(name);
if (amountOfActualCalls > 0) {
SimpleString ordinalNumber = StringFromOrdinalNumber(amountOfActualCalls + 1);
message_ = StringFromFormat("Mock Failure: Unexpected additional (%s) call to function: ", ordinalNumber.asCharString());
} else {
message_ = "Mock Failure: Unexpected call to function: ";
}
message_ += name;
message_ += "\n";
addExpectationsAndCallHistory(expectations);
}
MockCallOrderFailure::MockCallOrderFailure(UtestShell* test, const MockExpectedCallsList& expectations) : MockFailure(test)
{
MockExpectedCallsList expectationsForOutOfOrder;
expectationsForOutOfOrder.addExpectations(expectations);
expectationsForOutOfOrder.onlyKeepOutOfOrderExpectations();
message_ = "Mock Failure: Out of order calls";
message_ += "\n";
addExpectationsAndCallHistory(expectationsForOutOfOrder);
}
MockUnexpectedInputParameterFailure::MockUnexpectedInputParameterFailure(UtestShell* test, const SimpleString& functionName, const MockNamedValue& parameter, const MockExpectedCallsList& expectations) : MockFailure(test)
{
MockExpectedCallsList expectationsForFunctionWithParameterName;
expectationsForFunctionWithParameterName.addExpectationsRelatedTo(functionName, expectations);
expectationsForFunctionWithParameterName.onlyKeepExpectationsWithInputParameterName(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_ += ">";
}
MockUnexpectedOutputParameterFailure::MockUnexpectedOutputParameterFailure(UtestShell* test, const SimpleString& functionName, const MockNamedValue& parameter, const MockExpectedCallsList& expectations) : MockFailure(test)
{
MockExpectedCallsList expectationsForFunctionWithParameterName;
expectationsForFunctionWithParameterName.addExpectationsRelatedTo(functionName, expectations);
expectationsForFunctionWithParameterName.onlyKeepExpectationsWithOutputParameterName(parameter.getName());
if (expectationsForFunctionWithParameterName.isEmpty()) {
message_ = "Mock Failure: Unexpected output parameter name to function \"";
message_ += functionName;
message_ += "\": ";
message_ += parameter.getName();
}
else {
message_ = "Mock Failure: Unexpected parameter type \"";
message_ += parameter.getType();
message_ += "\" to output parameter \"";
message_ += parameter.getName();
message_ += "\" to function \"";
message_ += functionName;
message_ += "\"";
}
message_ += "\n";
addExpectationsAndCallHistoryRelatedTo(functionName, expectations);
message_ += "\n\tACTUAL unexpected output parameter passed to function: ";
message_ += functionName;
message_ += "\n";
message_ += "\t\t";
message_ += parameter.getType();
message_ += " ";
message_ += parameter.getName();
}
MockExpectedParameterDidntHappenFailure::MockExpectedParameterDidntHappenFailure(UtestShell* test, const SimpleString& functionName,
const MockExpectedCallsList& allExpectations,
const MockExpectedCallsList& matchingExpectations) : MockFailure(test)
{
message_ = "Mock Failure: Expected parameter for function \"";
message_ += functionName;
message_ += "\" did not happen.\n";
message_ += "\tEXPECTED calls with MISSING parameters related to function: ";
message_ += functionName;
message_ += "\n";
message_ += matchingExpectations.callsWithMissingParametersToString("\t\t", "\tMISSING parameters: ");
message_ += "\n";
addExpectationsAndCallHistoryRelatedTo(functionName, allExpectations);
}
MockNoWayToCompareCustomTypeFailure::MockNoWayToCompareCustomTypeFailure(UtestShell* test, const SimpleString& typeName) : MockFailure(test)
{
message_ = StringFromFormat("MockFailure: No way to compare type <%s>. Please install a MockNamedValueComparator.", typeName.asCharString());
}
MockNoWayToCopyCustomTypeFailure::MockNoWayToCopyCustomTypeFailure(UtestShell* test, const SimpleString& typeName) : MockFailure(test)
{
message_ = StringFromFormat("MockFailure: No way to copy type <%s>. Please install a MockNamedValueCopier.", typeName.asCharString());
}
MockUnexpectedObjectFailure::MockUnexpectedObjectFailure(UtestShell* test, const SimpleString& functionName, const void* actual, const MockExpectedCallsList& expectations) : MockFailure(test)
{
message_ = StringFromFormat ("MockFailure: Function called on an unexpected object: %s\n"
"\tActual object for call has address: <%p>\n", functionName.asCharString(),actual);
addExpectationsAndCallHistoryRelatedTo(functionName, expectations);
}
MockExpectedObjectDidntHappenFailure::MockExpectedObjectDidntHappenFailure(UtestShell* test, const SimpleString& functionName, const MockExpectedCallsList& 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 |
205 | cpp | cpputest | IEEE754ExceptionsPlugin.cpp | src/CppUTestExt/IEEE754ExceptionsPlugin.cpp | null | /*
* Copyright (c) 2015, Michael Feathers, James Grenning, Bas Vodde
* and Arnd R. Strube. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/IEEE754ExceptionsPlugin.h"
#if CPPUTEST_HAVE_FENV
extern "C" {
#include <fenv.h>
}
#define IEEE754_CHECK_CLEAR(test, result, flag) ieee754Check(test, result, flag, #flag)
bool IEEE754ExceptionsPlugin::inexactDisabled_ = true;
IEEE754ExceptionsPlugin::IEEE754ExceptionsPlugin(const SimpleString& name)
: TestPlugin(name)
{
}
void IEEE754ExceptionsPlugin::preTestAction(UtestShell&, TestResult&)
{
CHECK(!feclearexcept(FE_ALL_EXCEPT));
}
void IEEE754ExceptionsPlugin::postTestAction(UtestShell& test, TestResult& result)
{
if(!test.hasFailed()) {
IEEE754_CHECK_CLEAR(test, result, FE_DIVBYZERO);
IEEE754_CHECK_CLEAR(test, result, FE_OVERFLOW);
IEEE754_CHECK_CLEAR(test, result, FE_UNDERFLOW);
IEEE754_CHECK_CLEAR(test, result, FE_INVALID); // LCOV_EXCL_LINE (not all platforms support this)
IEEE754_CHECK_CLEAR(test, result, FE_INEXACT);
}
}
void IEEE754ExceptionsPlugin::disableInexact()
{
inexactDisabled_ = true;
}
void IEEE754ExceptionsPlugin::enableInexact()
{
inexactDisabled_ = false;
}
bool IEEE754ExceptionsPlugin::checkIeee754OverflowExceptionFlag()
{
return fetestexcept(FE_OVERFLOW) != 0;
}
bool IEEE754ExceptionsPlugin::checkIeee754UnderflowExceptionFlag()
{
return fetestexcept(FE_UNDERFLOW) != 0;
}
bool IEEE754ExceptionsPlugin::checkIeee754InexactExceptionFlag()
{
return fetestexcept(FE_INEXACT) != 0;
}
bool IEEE754ExceptionsPlugin::checkIeee754DivByZeroExceptionFlag()
{
return fetestexcept(FE_DIVBYZERO) != 0;
}
void IEEE754ExceptionsPlugin::ieee754Check(UtestShell& test, TestResult& result, int flag, const char* text)
{
result.countCheck();
if(inexactDisabled_) CHECK(!feclearexcept(FE_INEXACT));
if(fetestexcept(flag)) {
CHECK(!feclearexcept(FE_ALL_EXCEPT));
CheckFailure failure(&test, __FILE__, __LINE__, "IEEE754_CHECK_CLEAR", text);
result.addFailure(failure);
}
}
#else
bool IEEE754ExceptionsPlugin::inexactDisabled_ = true;
IEEE754ExceptionsPlugin::IEEE754ExceptionsPlugin(const SimpleString& name)
: TestPlugin(name)
{
}
void IEEE754ExceptionsPlugin::preTestAction(UtestShell&, TestResult&)
{
}
void IEEE754ExceptionsPlugin::postTestAction(UtestShell&, TestResult&)
{
}
void IEEE754ExceptionsPlugin::disableInexact()
{
}
void IEEE754ExceptionsPlugin::enableInexact()
{
}
bool IEEE754ExceptionsPlugin::checkIeee754OverflowExceptionFlag()
{
return false;
}
bool IEEE754ExceptionsPlugin::checkIeee754UnderflowExceptionFlag()
{
return false;
}
bool IEEE754ExceptionsPlugin::checkIeee754InexactExceptionFlag()
{
return false;
}
bool IEEE754ExceptionsPlugin::checkIeee754DivByZeroExceptionFlag()
{
return false;
}
void IEEE754ExceptionsPlugin::ieee754Check(UtestShell&, TestResult&, int, const char*)
{
}
#endif
| null |
206 | cpp | cpputest | MockExpectedCall.cpp | src/CppUTestExt/MockExpectedCall.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/MockCheckedExpectedCall.h"
MockExpectedCall::MockExpectedCall()
{
}
MockExpectedCall::~MockExpectedCall()
{
}
SimpleString StringFrom(const MockNamedValue& parameter)
{
return parameter.toString();
}
void MockCheckedExpectedCall::setName(const SimpleString& name)
{
functionName_ = name;
}
SimpleString MockCheckedExpectedCall::getName() const
{
return functionName_;
}
MockCheckedExpectedCall::MockCheckedExpectedCall()
: ignoreOtherParameters_(false), isActualCallMatchFinalized_(false),
initialExpectedCallOrder_(NO_EXPECTED_CALL_ORDER), finalExpectedCallOrder_(NO_EXPECTED_CALL_ORDER),
outOfOrder_(false), returnValue_(""), objectPtr_(NULLPTR), isSpecificObjectExpected_(false), wasPassedToObject_(true),
actualCalls_(0), expectedCalls_(1)
{
inputParameters_ = new MockNamedValueList();
outputParameters_ = new MockNamedValueList();
}
MockCheckedExpectedCall::MockCheckedExpectedCall(unsigned int numCalls)
: ignoreOtherParameters_(false), isActualCallMatchFinalized_(false),
initialExpectedCallOrder_(NO_EXPECTED_CALL_ORDER), finalExpectedCallOrder_(NO_EXPECTED_CALL_ORDER),
outOfOrder_(false), returnValue_(""), objectPtr_(NULLPTR), isSpecificObjectExpected_(false), wasPassedToObject_(true),
actualCalls_(0), expectedCalls_(numCalls)
{
inputParameters_ = new MockNamedValueList();
outputParameters_ = new MockNamedValueList();
}
MockCheckedExpectedCall::~MockCheckedExpectedCall()
{
inputParameters_->clear();
delete inputParameters_;
outputParameters_->clear();
delete outputParameters_;
}
MockExpectedCall& MockCheckedExpectedCall::withName(const SimpleString& name)
{
setName(name);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withBoolParameter(const SimpleString& name, bool value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withUnsignedIntParameter(const SimpleString& name, unsigned int value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withIntParameter(const SimpleString& name, int value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withLongIntParameter(const SimpleString& name, long int value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
#if CPPUTEST_USE_LONG_LONG
MockExpectedCall& MockCheckedExpectedCall::withLongLongIntParameter(const SimpleString& name, cpputest_longlong value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
#else
MockExpectedCall& MockCheckedExpectedCall::withLongLongIntParameter(const SimpleString&, cpputest_longlong)
{
FAIL("Long Long type is not supported");
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withUnsignedLongLongIntParameter(const SimpleString&, cpputest_ulonglong)
{
FAIL("Unsigned Long Long type is not supported");
return *this;
}
#endif
MockExpectedCall& MockCheckedExpectedCall::withDoubleParameter(const SimpleString& name, double value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withDoubleParameter(const SimpleString& name, double value, double tolerance)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value, tolerance);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withStringParameter(const SimpleString& name, const char* value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withPointerParameter(const SimpleString& name, void* value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withConstPointerParameter(const SimpleString& name, const void* value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withFunctionPointerParameter(const SimpleString& name, void (*value)())
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setMemoryBuffer(value, size);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withParameterOfType(const SimpleString& type, const SimpleString& name, const void* value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
inputParameters_->add(newParameter);
newParameter->setConstObjectPointer(type, value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withOutputParameterReturning(const SimpleString& name, const void* value, size_t size)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
outputParameters_->add(newParameter);
newParameter->setValue(value);
newParameter->setSize(size);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withOutputParameterOfTypeReturning(const SimpleString& type, const SimpleString& name, const void* value)
{
MockNamedValue* newParameter = new MockExpectedFunctionParameter(name);
outputParameters_->add(newParameter);
newParameter->setConstObjectPointer(type, value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::withUnmodifiedOutputParameter(const SimpleString& name)
{
return withOutputParameterReturning(name, NULLPTR, 0);
}
SimpleString MockCheckedExpectedCall::getInputParameterType(const SimpleString& name)
{
MockNamedValue * p = inputParameters_->getValueByName(name);
return (p) ? p->getType() : StringFrom("");
}
bool MockCheckedExpectedCall::hasInputParameterWithName(const SimpleString& name)
{
MockNamedValue * p = inputParameters_->getValueByName(name);
return p != NULLPTR;
}
bool MockCheckedExpectedCall::hasOutputParameterWithName(const SimpleString& name)
{
MockNamedValue * p = outputParameters_->getValueByName(name);
return p != NULLPTR;
}
MockNamedValue MockCheckedExpectedCall::getInputParameter(const SimpleString& name)
{
MockNamedValue * p = inputParameters_->getValueByName(name);
return (p) ? *p : MockNamedValue("");
}
MockNamedValue MockCheckedExpectedCall::getOutputParameter(const SimpleString& name)
{
MockNamedValue * p = outputParameters_->getValueByName(name);
return (p) ? *p : MockNamedValue("");
}
bool MockCheckedExpectedCall::areParametersMatchingActualCall()
{
MockNamedValueListNode* p;
for (p = inputParameters_->begin(); p; p = p->next())
if (! item(p)->isMatchingActualCall())
return false;
for (p = outputParameters_->begin(); p; p = p->next())
if (! item(p)->isMatchingActualCall())
return false;
return true;
}
MockExpectedCall& MockCheckedExpectedCall::ignoreOtherParameters()
{
ignoreOtherParameters_ = true;
return *this;
}
bool MockCheckedExpectedCall::isFulfilled()
{
return (actualCalls_ == expectedCalls_);
}
bool MockCheckedExpectedCall::canMatchActualCalls()
{
return (actualCalls_ < expectedCalls_);
}
bool MockCheckedExpectedCall::isMatchingActualCallAndFinalized()
{
return isMatchingActualCall() && (!ignoreOtherParameters_ || isActualCallMatchFinalized_);
}
bool MockCheckedExpectedCall::isMatchingActualCall()
{
return areParametersMatchingActualCall() && wasPassedToObject_;
}
void MockCheckedExpectedCall::callWasMade(unsigned int callOrder)
{
actualCalls_++;
if ( (initialExpectedCallOrder_ != NO_EXPECTED_CALL_ORDER) &&
((callOrder < initialExpectedCallOrder_) || (callOrder > finalExpectedCallOrder_)) ) {
outOfOrder_ = true;
}
resetActualCallMatchingState();
}
void MockCheckedExpectedCall::finalizeActualCallMatch()
{
isActualCallMatchFinalized_ = true;
}
void MockCheckedExpectedCall::wasPassedToObject()
{
wasPassedToObject_ = true;
}
void MockCheckedExpectedCall::resetActualCallMatchingState()
{
wasPassedToObject_ = !isSpecificObjectExpected_;
isActualCallMatchFinalized_ = false;
MockNamedValueListNode* p;
for (p = inputParameters_->begin(); p; p = p->next())
item(p)->setMatchesActualCall(false);
for (p = outputParameters_->begin(); p; p = p->next())
item(p)->setMatchesActualCall(false);
}
void MockCheckedExpectedCall::inputParameterWasPassed(const SimpleString& name)
{
for (MockNamedValueListNode* p = inputParameters_->begin(); p; p = p->next()) {
if (p->getName() == name)
item(p)->setMatchesActualCall(true);
}
}
void MockCheckedExpectedCall::outputParameterWasPassed(const SimpleString& name)
{
for (MockNamedValueListNode* p = outputParameters_->begin(); p; p = p->next()) {
if (p->getName() == name)
item(p)->setMatchesActualCall(true);
}
}
SimpleString MockCheckedExpectedCall::getInputParameterValueString(const SimpleString& name)
{
MockNamedValue * p = inputParameters_->getValueByName(name);
return (p) ? StringFrom(*p) : StringFrom("failed");
}
bool MockCheckedExpectedCall::hasInputParameter(const MockNamedValue& parameter)
{
MockNamedValue * p = inputParameters_->getValueByName(parameter.getName());
return (p) ? p->equals(parameter) : ignoreOtherParameters_;
}
bool MockCheckedExpectedCall::hasOutputParameter(const MockNamedValue& parameter)
{
MockNamedValue * p = outputParameters_->getValueByName(parameter.getName());
return (p) ? p->compatibleForCopying(parameter) : ignoreOtherParameters_;
}
SimpleString MockCheckedExpectedCall::callToString()
{
SimpleString str;
if (isSpecificObjectExpected_)
str = StringFromFormat("(object address: %p)::", objectPtr_);
str += getName();
str += " -> ";
if (initialExpectedCallOrder_ != NO_EXPECTED_CALL_ORDER) {
if (initialExpectedCallOrder_ == finalExpectedCallOrder_) {
str += StringFromFormat("expected call order: <%u> -> ", initialExpectedCallOrder_);
} else {
str += StringFromFormat("expected calls order: <%u..%u> -> ", initialExpectedCallOrder_, finalExpectedCallOrder_);
}
}
if (inputParameters_->begin() == NULLPTR && outputParameters_->begin() == NULLPTR) {
str += (ignoreOtherParameters_) ? "all parameters ignored" : "no parameters";
} else {
MockNamedValueListNode* p;
for (p = inputParameters_->begin(); p; p = p->next()) {
str += StringFromFormat("%s %s: <%s>", p->getType().asCharString(), p->getName().asCharString(), getInputParameterValueString(p->getName()).asCharString());
if (p->next()) str += ", ";
}
if (inputParameters_->begin() && outputParameters_->begin())
{
str += ", ";
}
for (p = outputParameters_->begin(); p; p = p->next()) {
str += StringFromFormat("%s %s: <output>", p->getType().asCharString(), p->getName().asCharString());
if (p->next()) str += ", ";
}
if (ignoreOtherParameters_)
str += ", other parameters are ignored";
}
str += StringFromFormat(" (expected %d call%s, called %d time%s)",
expectedCalls_, (expectedCalls_ == 1) ? "" : "s", actualCalls_, (actualCalls_ == 1) ? "" : "s" );
return str;
}
SimpleString MockCheckedExpectedCall::missingParametersToString()
{
SimpleString str;
MockNamedValueListNode* p;
for (p = inputParameters_->begin(); p; p = p->next()) {
if (! item(p)->isMatchingActualCall()) {
if (str != "") str += ", ";
str += StringFromFormat("%s %s", p->getType().asCharString(), p->getName().asCharString());
}
}
for (p = outputParameters_->begin(); p; p = p->next()) {
if (! item(p)->isMatchingActualCall()) {
if (str != "") str += ", ";
str += StringFromFormat("%s %s", p->getType().asCharString(), p->getName().asCharString());
}
}
return str;
}
bool MockCheckedExpectedCall::relatesTo(const SimpleString& functionName)
{
return functionName == getName();
}
bool MockCheckedExpectedCall::relatesToObject(const void* objectPtr) const
{
return (!isSpecificObjectExpected_) || (objectPtr_ == objectPtr);
}
MockCheckedExpectedCall::MockExpectedFunctionParameter* MockCheckedExpectedCall::item(MockNamedValueListNode* node)
{
return (MockExpectedFunctionParameter*) node->item();
}
MockCheckedExpectedCall::MockExpectedFunctionParameter::MockExpectedFunctionParameter(const SimpleString& name)
: MockNamedValue(name), matchesActualCall_(false)
{
}
void MockCheckedExpectedCall::MockExpectedFunctionParameter::setMatchesActualCall(bool b)
{
matchesActualCall_ = b;
}
bool MockCheckedExpectedCall::MockExpectedFunctionParameter::isMatchingActualCall() const
{
return matchesActualCall_;
}
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(bool value)
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(unsigned int value)
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(int value)
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(long int value)
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(unsigned long int value)
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
#if CPPUTEST_USE_LONG_LONG
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(cpputest_longlong value)
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(cpputest_ulonglong value)
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
#else
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(cpputest_longlong)
{
FAIL("Long Long type is not supported");
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(cpputest_ulonglong)
{
FAIL("Unsigned Long Long type is not supported");
return *this;
}
#endif
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(const char* value)
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(double value)
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(void* value)
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(const void* value)
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::andReturnValue(void (*value)())
{
returnValue_.setName("returnValue");
returnValue_.setValue(value);
return *this;
}
MockExpectedCall& MockCheckedExpectedCall::onObject(void* objectPtr)
{
isSpecificObjectExpected_ = true;
wasPassedToObject_ = false;
objectPtr_ = objectPtr;
return *this;
}
MockNamedValue MockCheckedExpectedCall::returnValue()
{
return returnValue_;
}
MockExpectedCall& MockCheckedExpectedCall::withCallOrder(unsigned int initialCallOrder, unsigned int finalCallOrder)
{
initialExpectedCallOrder_ = initialCallOrder;
finalExpectedCallOrder_ = finalCallOrder;
return *this;
}
bool MockCheckedExpectedCall::isOutOfOrder() const
{
return outOfOrder_;
}
unsigned int MockCheckedExpectedCall::getActualCallsFulfilled() const
{
return actualCalls_;
}
MockExpectedCall& MockIgnoredExpectedCall::instance()
{
static MockIgnoredExpectedCall call;
return call;
}
| null |
207 | cpp | 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_(NULLPTR)
{
}
MemoryReporterPlugin::~MemoryReporterPlugin()
{
removeGlobalMemoryReportAllocators();
destroyMemoryFormatter(formatter_);
}
bool MemoryReporterPlugin::parseArguments(int /* ac */, const char *const *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(defaultMallocAllocator());
}
return NULLPTR;
}
void MemoryReporterPlugin::destroyMemoryFormatter(MemoryReportFormatter* formatter)
{
delete formatter;
}
void MemoryReporterPlugin::setGlobalMemoryReportAllocators()
{
mallocAllocator.setRealAllocator(getCurrentMallocAllocator());
setCurrentMallocAllocator(&mallocAllocator);
newAllocator.setRealAllocator(getCurrentNewAllocator());
setCurrentNewAllocator(&newAllocator);
newArrayAllocator.setRealAllocator(getCurrentNewArrayAllocator());
setCurrentNewArrayAllocator(&newArrayAllocator);
}
void MemoryReporterPlugin::removeGlobalMemoryReportAllocators()
{
if (getCurrentNewAllocator() == &newAllocator)
setCurrentNewAllocator(newAllocator.getRealAllocator());
if (getCurrentNewArrayAllocator() == &newArrayAllocator)
setCurrentNewArrayAllocator(newArrayAllocator.getRealAllocator());
if (getCurrentMallocAllocator() == &mallocAllocator)
setCurrentMallocAllocator(mallocAllocator.getRealAllocator());
}
MemoryReportAllocator* MemoryReporterPlugin::getMallocAllocator()
{
return &mallocAllocator;
}
MemoryReportAllocator* MemoryReporterPlugin::getNewAllocator()
{
return &newAllocator;
}
MemoryReportAllocator* MemoryReporterPlugin::getNewArrayAllocator()
{
return &newArrayAllocator;
}
void MemoryReporterPlugin::initializeAllocator(MemoryReportAllocator* allocator, TestResult & result)
{
allocator->setFormatter(formatter_);
allocator->setTestResult((&result));
}
void MemoryReporterPlugin::preTestAction(UtestShell& test, TestResult& result)
{
if (formatter_ == NULLPTR) 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(UtestShell& test, TestResult& result)
{
if (formatter_ == NULLPTR) return;
removeGlobalMemoryReportAllocators();
formatter_->report_test_end(&result, test);
if (test.getNext() == NULLPTR || test.getNext()->getGroup() != currentTestGroup_)
formatter_->report_testgroup_end(&result, test);
}
| null |
208 | cpp | 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/MockActualCall.h"
#include "CppUTestExt/MockExpectedCall.h"
#include "CppUTestExt/MockFailure.h"
#define MOCK_SUPPORT_SCOPE_PREFIX "!!!$$$MockingSupportScope$$$!!!"
static MockSupport global_mock;
MockSupport& mock(const SimpleString& mockName, MockFailureReporter* failureReporterForThisCall)
{
MockSupport& mock_support = (mockName != "") ? *global_mock.getMockSupportScope(mockName) : global_mock;
mock_support.setActiveReporter(failureReporterForThisCall);
mock_support.setDefaultComparatorsAndCopiersRepository();
return mock_support;
}
MockSupport::MockSupport(const SimpleString& mockName)
:
actualCallOrder_(0),
expectedCallOrder_(0),
strictOrdering_(false),
activeReporter_(NULLPTR),
standardReporter_(&defaultReporter_),
ignoreOtherCalls_(false),
enabled_(true),
lastActualFunctionCall_(NULLPTR),
mockName_(mockName),
tracing_(false)
{
}
MockSupport::~MockSupport()
{
}
void MockSupport::crashOnFailure(bool shouldCrash)
{
activeReporter_->crashOnFailure(shouldCrash);
}
void MockSupport::setMockFailureStandardReporter(MockFailureReporter* reporter)
{
standardReporter_ = (reporter != NULLPTR) ? reporter : &defaultReporter_;
if (lastActualFunctionCall_)
lastActualFunctionCall_->setMockFailureReporter(standardReporter_);
for (MockNamedValueListNode* p = data_.begin(); p; p = p->next())
if (getMockSupport(p)) getMockSupport(p)->setMockFailureStandardReporter(standardReporter_);
}
void MockSupport::setActiveReporter(MockFailureReporter* reporter)
{
activeReporter_ = (reporter) ? reporter : standardReporter_;
}
void MockSupport::setDefaultComparatorsAndCopiersRepository()
{
MockNamedValue::setDefaultComparatorsAndCopiersRepository(&comparatorsAndCopiersRepository_);
}
void MockSupport::installComparator(const SimpleString& typeName, MockNamedValueComparator& comparator)
{
comparatorsAndCopiersRepository_.installComparator(typeName, comparator);
for (MockNamedValueListNode* p = data_.begin(); p; p = p->next())
if (getMockSupport(p)) getMockSupport(p)->installComparator(typeName, comparator);
}
void MockSupport::installCopier(const SimpleString& typeName, MockNamedValueCopier& copier)
{
comparatorsAndCopiersRepository_.installCopier(typeName, copier);
for (MockNamedValueListNode* p = data_.begin(); p; p = p->next())
if (getMockSupport(p)) getMockSupport(p)->installCopier(typeName, copier);
}
void MockSupport::installComparatorsAndCopiers(const MockNamedValueComparatorsAndCopiersRepository& repository)
{
comparatorsAndCopiersRepository_.installComparatorsAndCopiers(repository);
for (MockNamedValueListNode* p = data_.begin(); p; p = p->next())
if (getMockSupport(p)) getMockSupport(p)->installComparatorsAndCopiers(repository);
}
void MockSupport::removeAllComparatorsAndCopiers()
{
comparatorsAndCopiersRepository_.clear();
for (MockNamedValueListNode* p = data_.begin(); p; p = p->next())
if (getMockSupport(p)) getMockSupport(p)->removeAllComparatorsAndCopiers();
}
void MockSupport::clear()
{
delete lastActualFunctionCall_;
lastActualFunctionCall_ = NULLPTR;
tracing_ = false;
MockActualCallTrace::clearInstance();
expectations_.deleteAllExpectationsAndClearList();
ignoreOtherCalls_ = false;
enabled_ = true;
actualCallOrder_ = 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;
}
SimpleString MockSupport::appendScopeToName(const SimpleString& functionName)
{
if (mockName_.isEmpty()) return functionName;
return mockName_ + "::" + functionName;
}
MockExpectedCall& MockSupport::expectOneCall(const SimpleString& functionName)
{
return expectNCalls(1, functionName);
}
void MockSupport::expectNoCall(const SimpleString& functionName)
{
expectNCalls(0, functionName);
}
MockExpectedCall& MockSupport::expectNCalls(unsigned int amount, const SimpleString& functionName)
{
if (!enabled_) return MockIgnoredExpectedCall::instance();
countCheck();
MockCheckedExpectedCall* call = new MockCheckedExpectedCall(amount);
call->withName(appendScopeToName(functionName));
if (strictOrdering_) {
call->withCallOrder(expectedCallOrder_ + 1, expectedCallOrder_ + amount);
expectedCallOrder_ += amount;
}
expectations_.addExpectedCall(call);
return *call;
}
MockCheckedActualCall* MockSupport::createActualCall()
{
lastActualFunctionCall_ = new MockCheckedActualCall(++actualCallOrder_, activeReporter_, expectations_);
return lastActualFunctionCall_;
}
bool MockSupport::callIsIgnored(const SimpleString& functionName)
{
return ignoreOtherCalls_ && !expectations_.hasExpectationWithName(functionName);
}
MockActualCall& MockSupport::actualCall(const SimpleString& functionName)
{
const SimpleString scopeFunctionName = appendScopeToName(functionName);
if (lastActualFunctionCall_) {
lastActualFunctionCall_->checkExpectations();
delete lastActualFunctionCall_;
lastActualFunctionCall_ = NULLPTR;
}
if (!enabled_) return MockIgnoredActualCall::instance();
if (tracing_) return MockActualCallTrace::instance().withName(scopeFunctionName);
if (callIsIgnored(scopeFunctionName)) {
return MockIgnoredActualCall::instance();
}
MockCheckedActualCall* call = createActualCall();
call->withName(scopeFunctionName);
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 MockActualCallTrace::instance().getTraceOutput();
}
bool MockSupport::expectedCallsLeft()
{
int callsLeft = expectations_.hasUnfulfilledExpectations();
for (MockNamedValueListNode* p = data_.begin(); p; p = p->next())
if (getMockSupport(p)) callsLeft += getMockSupport(p)->expectedCallsLeft();
return callsLeft != 0;
}
bool MockSupport::wasLastActualCallFulfilled()
{
if (lastActualFunctionCall_ && !lastActualFunctionCall_->isFulfilled())
return false;
for (MockNamedValueListNode* p = data_.begin(); p; p = p->next())
if (getMockSupport(p) && !getMockSupport(p)->wasLastActualCallFulfilled())
return false;
return true;
}
void MockSupport::failTestWithExpectedCallsNotFulfilled()
{
MockExpectedCallsList expectationsList;
expectationsList.addExpectations(expectations_);
for(MockNamedValueListNode *p = data_.begin();p;p = p->next())
if(getMockSupport(p))
expectationsList.addExpectations(getMockSupport(p)->expectations_);
MockExpectedCallsDidntHappenFailure failure(activeReporter_->getTestToFail(), expectationsList);
failTest(failure);
}
void MockSupport::failTestWithOutOfOrderCalls()
{
MockExpectedCallsList expectationsList;
expectationsList.addExpectations(expectations_);
for(MockNamedValueListNode *p = data_.begin();p;p = p->next())
if(getMockSupport(p))
expectationsList.addExpectations(getMockSupport(p)->expectations_);
MockCallOrderFailure failure(activeReporter_->getTestToFail(), expectationsList);
failTest(failure);
}
void MockSupport::failTest(MockFailure& failure)
{
clear();
activeReporter_->failTest(failure);
}
void MockSupport::countCheck()
{
UtestShell::getCurrent()->countCheck();
}
void MockSupport::checkExpectationsOfLastActualCall()
{
if(lastActualFunctionCall_)
lastActualFunctionCall_->checkExpectations();
for(MockNamedValueListNode *p = data_.begin();p;p = p->next())
if(getMockSupport(p) && getMockSupport(p)->lastActualFunctionCall_)
getMockSupport(p)->lastActualFunctionCall_->checkExpectations();
}
bool MockSupport::hasCallsOutOfOrder()
{
if (expectations_.hasCallsOutOfOrder())
{
return true;
}
for (MockNamedValueListNode* p = data_.begin(); p; p = p->next())
if (getMockSupport(p) && getMockSupport(p)->hasCallsOutOfOrder())
{
return true;
}
return false;
}
void MockSupport::checkExpectations()
{
checkExpectationsOfLastActualCall();
if (wasLastActualCallFulfilled() && expectedCallsLeft())
failTestWithExpectedCallsNotFulfilled();
if (hasCallsOutOfOrder())
failTestWithOutOfOrderCalls();
}
bool MockSupport::hasData(const SimpleString& name)
{
return data_.getValueByName(name) != NULLPTR;
}
MockNamedValue* MockSupport::retrieveDataFromStore(const SimpleString& name)
{
MockNamedValue* newData = data_.getValueByName(name);
if (newData == NULLPTR) {
newData = new MockNamedValue(name);
data_.add(newData);
}
return newData;
}
void MockSupport::setData(const SimpleString& name, bool value)
{
MockNamedValue* newData = retrieveDataFromStore(name);
newData->setValue(value);
}
void MockSupport::setData(const SimpleString& name, unsigned int value)
{
MockNamedValue* newData = retrieveDataFromStore(name);
newData->setValue(value);
}
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::setData(const SimpleString& name, const void* 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);
}
void MockSupport::setDataConstObject(const SimpleString& name, const SimpleString& type, const void* value)
{
MockNamedValue* newData = retrieveDataFromStore(name);
newData->setConstObjectPointer(type, value);
}
MockNamedValue MockSupport::getData(const SimpleString& name)
{
MockNamedValue* value = data_.getValueByName(name);
if (value == NULLPTR)
return MockNamedValue("");
return *value;
}
MockSupport* MockSupport::clone(const SimpleString& mockName)
{
MockSupport* newMock = new MockSupport(mockName);
newMock->setMockFailureStandardReporter(standardReporter_);
if (ignoreOtherCalls_) newMock->ignoreOtherCalls();
if (!enabled_) newMock->disable();
if (strictOrdering_) newMock->strictOrder();
newMock->tracing(tracing_);
newMock->installComparatorsAndCopiers(comparatorsAndCopiersRepository_);
return newMock;
}
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 = clone(name);
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 NULLPTR;
}
MockNamedValue MockSupport::returnValue()
{
if (lastActualFunctionCall_) return lastActualFunctionCall_->returnValue();
return MockNamedValue("");
}
bool MockSupport::boolReturnValue()
{
return returnValue().getBoolValue();
}
unsigned int MockSupport::unsignedIntReturnValue()
{
return returnValue().getUnsignedIntValue();
}
int MockSupport::intReturnValue()
{
return returnValue().getIntValue();
}
const char * MockSupport::returnStringValueOrDefault(const char * defaultValue)
{
if (hasReturnValue()) {
return stringReturnValue();
}
return defaultValue;
}
double MockSupport::returnDoubleValueOrDefault(double defaultValue)
{
if (hasReturnValue()) {
return doubleReturnValue();
}
return defaultValue;
}
long int MockSupport::returnLongIntValueOrDefault(long int defaultValue)
{
if (hasReturnValue()) {
return longIntReturnValue();
}
return defaultValue;
}
bool MockSupport::returnBoolValueOrDefault(bool defaultValue)
{
if (hasReturnValue()) {
return boolReturnValue();
}
return defaultValue;
}
int MockSupport::returnIntValueOrDefault(int defaultValue)
{
if (hasReturnValue()) {
return intReturnValue();
}
return defaultValue;
}
unsigned int MockSupport::returnUnsignedIntValueOrDefault(unsigned int defaultValue)
{
if (hasReturnValue()) {
return unsignedIntReturnValue();
}
return defaultValue;
}
unsigned long int MockSupport::returnUnsignedLongIntValueOrDefault(unsigned long int defaultValue)
{
if (hasReturnValue()) {
return unsignedLongIntReturnValue();
}
return defaultValue;
}
long int MockSupport::longIntReturnValue()
{
return returnValue().getLongIntValue();
}
unsigned long int MockSupport::unsignedLongIntReturnValue()
{
return returnValue().getUnsignedLongIntValue();
}
#if CPPUTEST_USE_LONG_LONG
cpputest_longlong MockSupport::longLongIntReturnValue()
{
return returnValue().getLongLongIntValue();
}
cpputest_ulonglong MockSupport::unsignedLongLongIntReturnValue()
{
return returnValue().getUnsignedLongLongIntValue();
}
cpputest_longlong MockSupport::returnLongLongIntValueOrDefault(cpputest_longlong defaultValue)
{
if (hasReturnValue()) {
return longLongIntReturnValue();
}
return defaultValue;
}
cpputest_ulonglong MockSupport::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong defaultValue)
{
if (hasReturnValue()) {
return unsignedLongLongIntReturnValue();
}
return defaultValue;
}
#else
cpputest_longlong MockSupport::longLongIntReturnValue()
{
FAIL("Long Long type is not supported");
cpputest_longlong ret = {};
return ret;
}
cpputest_ulonglong MockSupport::unsignedLongLongIntReturnValue()
{
FAIL("Unsigned Long Long type is not supported");
cpputest_ulonglong ret = {};
return ret;
}
cpputest_longlong MockSupport::returnLongLongIntValueOrDefault(cpputest_longlong defaultValue)
{
FAIL("Long Long type is not supported");
return defaultValue;
}
cpputest_ulonglong MockSupport::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong defaultValue)
{
FAIL("Unsigned Long Long type is not supported");
return defaultValue;
}
#endif
const char* MockSupport::stringReturnValue()
{
return returnValue().getStringValue();
}
double MockSupport::doubleReturnValue()
{
return returnValue().getDoubleValue();
}
void * MockSupport::returnPointerValueOrDefault(void * defaultValue)
{
if (hasReturnValue()) {
return pointerReturnValue();
}
return defaultValue;
}
const void* MockSupport::returnConstPointerValueOrDefault(const void * defaultValue)
{
if (hasReturnValue()) {
return constPointerReturnValue();
}
return defaultValue;
}
void (*MockSupport::returnFunctionPointerValueOrDefault(void (*defaultValue)()))()
{
if (hasReturnValue()) {
return functionPointerReturnValue();
}
return defaultValue;
}
void* MockSupport::pointerReturnValue()
{
return returnValue().getPointerValue();
}
const void* MockSupport::constPointerReturnValue()
{
return returnValue().getConstPointerValue();
}
void (*MockSupport::functionPointerReturnValue())()
{
return returnValue().getFunctionPointerValue();
}
bool MockSupport::hasReturnValue()
{
if (lastActualFunctionCall_) return lastActualFunctionCall_->hasReturnValue();
return false;
}
| null |
209 | cpp | 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 "CppUTest/CppUTestConfig.h"
#include "CppUTest/Utest.h"
#include "CppUTest/UtestMacros.h"
#include "CppUTest/PlatformSpecificFunctions_c.h"
#include "CppUTestExt/MockSupport.h"
#include "CppUTestExt/MockSupport_c.h"
typedef void (*cpputest_cpp_function_pointer)(); /* Cl2000 requires cast to C++ function */
class MockFailureReporterTestTerminatorForInCOnlyCode : public TestTerminator
{
public:
MockFailureReporterTestTerminatorForInCOnlyCode(bool crashOnFailure) : crashOnFailure_(crashOnFailure)
{
}
virtual void exitCurrentTest() const CPPUTEST_OVERRIDE
{
if (crashOnFailure_)
UT_CRASH();
UtestShell::getCurrentTestTerminatorWithoutExceptions().exitCurrentTest();
} // LCOV_EXCL_LINE
// LCOV_EXCL_START
virtual ~MockFailureReporterTestTerminatorForInCOnlyCode() CPPUTEST_DESTRUCTOR_OVERRIDE
{
}
// LCOV_EXCL_STOP
private:
bool crashOnFailure_;
};
class MockFailureReporterForInCOnlyCode : public MockFailureReporter
{
public:
void failTest(const MockFailure& failure) CPPUTEST_OVERRIDE
{
if (!getTestToFail()->hasFailed())
getTestToFail()->failWith(failure, MockFailureReporterTestTerminatorForInCOnlyCode(crashOnFailure_));
} // LCOV_EXCL_LINE
};
static MockSupport* currentMockSupport = NULLPTR;
static MockExpectedCall* expectedCall = NULLPTR;
static MockActualCall* actualCall = NULLPTR;
static MockFailureReporterForInCOnlyCode failureReporterForC;
class MockCFunctionComparatorNode : public MockNamedValueComparator
{
public:
MockCFunctionComparatorNode(MockCFunctionComparatorNode* next, MockTypeEqualFunction_c equal, MockTypeValueToStringFunction_c toString)
: next_(next), equal_(equal), toString_(toString) {}
virtual ~MockCFunctionComparatorNode() CPPUTEST_DESTRUCTOR_OVERRIDE {}
virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE
{
return equal_(object1, object2) != 0;
}
virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE
{
return SimpleString(toString_(object));
}
MockCFunctionComparatorNode* next_;
MockTypeEqualFunction_c equal_;
MockTypeValueToStringFunction_c toString_;
};
static MockCFunctionComparatorNode* comparatorList_ = NULLPTR;
class MockCFunctionCopierNode : public MockNamedValueCopier
{
public:
MockCFunctionCopierNode(MockCFunctionCopierNode* next, MockTypeCopyFunction_c copier)
: next_(next), copier_(copier) {}
virtual ~MockCFunctionCopierNode() CPPUTEST_DESTRUCTOR_OVERRIDE {}
virtual void copy(void* dst, const void* src) CPPUTEST_OVERRIDE
{
copier_(dst, src);
}
MockCFunctionCopierNode* next_;
MockTypeCopyFunction_c copier_;
};
static MockCFunctionCopierNode* copierList_ = NULLPTR;
extern "C" {
void strictOrder_c();
MockExpectedCall_c* expectOneCall_c(const char* name);
void expectNoCall_c(const char* name);
MockExpectedCall_c* expectNCalls_c(const unsigned int number, const char* name);
MockActualCall_c* actualCall_c(const char* name);
void disable_c();
void enable_c();
void ignoreOtherCalls_c();
void setBoolData_c(const char* name, int value);
void setIntData_c(const char* name, int value);
void setUnsignedIntData_c(const char* name, unsigned int value);
void setDoubleData_c(const char* name, double value);
void setStringData_c(const char* name, const char* value);
void setPointerData_c(const char* name, void* value);
void setConstPointerData_c(const char* name, const void* value);
void setFunctionPointerData_c(const char* name, void (*value)());
void setDataObject_c(const char* name, const char* type, void* value);
void setDataConstObject_c(const char* name, const char* type, const void* value);
MockValue_c getData_c(const char* name);
int hasReturnValue_c();
void checkExpectations_c();
int expectedCallsLeft_c();
void clear_c();
void crashOnFailure_c(unsigned shouldCrash);
MockExpectedCall_c* withBoolParameters_c(const char* name, int value);
MockExpectedCall_c* withIntParameters_c(const char* name, int value);
MockExpectedCall_c* withUnsignedIntParameters_c(const char* name, unsigned int value);
MockExpectedCall_c* withLongIntParameters_c(const char* name, long int value);
MockExpectedCall_c* withUnsignedLongIntParameters_c(const char* name, unsigned long int value);
MockExpectedCall_c* withLongLongIntParameters_c(const char* name, cpputest_longlong value);
MockExpectedCall_c* withUnsignedLongLongIntParameters_c(const char* name, cpputest_ulonglong value);
MockExpectedCall_c* withDoubleParameters_c(const char* name, double value);
MockExpectedCall_c* withDoubleParametersAndTolerance_c(const char* name, double value, double tolerance);
MockExpectedCall_c* withStringParameters_c(const char* name, const char* value);
MockExpectedCall_c* withPointerParameters_c(const char* name, void* value);
MockExpectedCall_c* withConstPointerParameters_c(const char* name, const void* value);
MockExpectedCall_c* withFunctionPointerParameters_c(const char* name, void (*value)());
MockExpectedCall_c* withMemoryBufferParameters_c(const char* name, const unsigned char* value, size_t size);
MockExpectedCall_c* withParameterOfType_c(const char* type, const char* name, const void* value);
MockExpectedCall_c* withOutputParameterReturning_c(const char* name, const void* value, size_t size);
MockExpectedCall_c* withOutputParameterOfTypeReturning_c(const char* type, const char* name, const void* value);
MockExpectedCall_c* withUnmodifiedOutputParameter_c(const char* name);
MockExpectedCall_c* ignoreOtherParameters_c();
MockExpectedCall_c* andReturnBoolValue_c(int value);
MockExpectedCall_c* andReturnIntValue_c(int value);
MockExpectedCall_c* andReturnUnsignedIntValue_c(unsigned int value);
MockExpectedCall_c* andReturnLongIntValue_c(long int value);
MockExpectedCall_c* andReturnUnsignedLongIntValue_c(unsigned long int value);
MockExpectedCall_c* andReturnLongLongIntValue_c(cpputest_longlong value);
MockExpectedCall_c* andReturnUnsignedLongLongIntValue_c(cpputest_ulonglong value);
MockExpectedCall_c* andReturnDoubleValue_c(double value);
MockExpectedCall_c* andReturnStringValue_c(const char* value);
MockExpectedCall_c* andReturnPointerValue_c(void* value);
MockExpectedCall_c* andReturnConstPointerValue_c(const void* value);
MockExpectedCall_c* andReturnFunctionPointerValue_c(void (*value)());
MockActualCall_c* withActualBoolParameters_c(const char* name, int value);
MockActualCall_c* withActualIntParameters_c(const char* name, int value);
MockActualCall_c* withActualUnsignedIntParameters_c(const char* name, unsigned int value);
MockActualCall_c* withActualLongIntParameters_c(const char* name, long int value);
MockActualCall_c* withActualUnsignedLongIntParameters_c(const char* name, unsigned long int value);
MockActualCall_c* withActualLongLongIntParameters_c(const char* name, cpputest_longlong value);
MockActualCall_c* withActualUnsignedLongLongIntParameters_c(const char* name, cpputest_ulonglong value);
MockActualCall_c* withActualDoubleParameters_c(const char* name, double value);
MockActualCall_c* withActualStringParameters_c(const char* name, const char* value);
MockActualCall_c* withActualPointerParameters_c(const char* name, void* value);
MockActualCall_c* withActualConstPointerParameters_c(const char* name, const void* value);
MockActualCall_c* withActualFunctionPointerParameters_c(const char* name, void (*value)());
MockActualCall_c* withActualMemoryBufferParameters_c(const char* name, const unsigned char* value, size_t size);
MockActualCall_c* withActualParameterOfType_c(const char* type, const char* name, const void* value);
MockActualCall_c* withActualOutputParameter_c(const char* name, void* value);
MockActualCall_c* withActualOutputParameterOfType_c(const char* type, const char* name, void* value);
MockValue_c returnValue_c();
int boolReturnValue_c();
int returnBoolValueOrDefault_c(int defaultValue);
int intReturnValue_c();
int returnIntValueOrDefault_c(int defaultValue);
unsigned int unsignedIntReturnValue_c();
unsigned int returnUnsignedIntValueOrDefault_c(unsigned int defaultValue);
long int longIntReturnValue_c();
long int returnLongIntValueOrDefault_c(long int defaultValue);
unsigned long int unsignedLongIntReturnValue_c();
unsigned long int returnUnsignedLongIntValueOrDefault_c(unsigned long int defaultValue);
cpputest_longlong longLongIntReturnValue_c();
cpputest_longlong returnLongLongIntValueOrDefault_c(cpputest_longlong defaultValue);
cpputest_ulonglong unsignedLongLongIntReturnValue_c();
cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault_c(cpputest_ulonglong defaultValue);
const char* stringReturnValue_c();
const char* returnStringValueOrDefault_c(const char * defaultValue);
double doubleReturnValue_c();
double returnDoubleValueOrDefault_c(double defaultValue);
void* pointerReturnValue_c();
void* returnPointerValueOrDefault_c(void * defaultValue);
const void* constPointerReturnValue_c();
const void* returnConstPointerValueOrDefault_c(const void * defaultValue);
void (*functionPointerReturnValue_c())();
void (*returnFunctionPointerValueOrDefault_c(void(*defaultValue)()))();
static void installComparator_c (const char* typeName, MockTypeEqualFunction_c isEqual, MockTypeValueToStringFunction_c valueToString)
{
comparatorList_ = new MockCFunctionComparatorNode(comparatorList_, isEqual, valueToString);
currentMockSupport->installComparator(typeName, *comparatorList_);
}
static void installCopier_c (const char* typeName, MockTypeCopyFunction_c copier)
{
copierList_ = new MockCFunctionCopierNode(copierList_, copier);
currentMockSupport->installCopier(typeName, *copierList_);
}
static void removeAllComparatorsAndCopiers_c()
{
while (comparatorList_) {
MockCFunctionComparatorNode *next = comparatorList_->next_;
delete comparatorList_;
comparatorList_ = next;
}
while (copierList_) {
MockCFunctionCopierNode *next = copierList_->next_;
delete copierList_;
copierList_ = next;
}
currentMockSupport->removeAllComparatorsAndCopiers();
}
static MockExpectedCall_c gExpectedCall = {
withBoolParameters_c,
withIntParameters_c,
withUnsignedIntParameters_c,
withLongIntParameters_c,
withUnsignedLongIntParameters_c,
withLongLongIntParameters_c,
withUnsignedLongLongIntParameters_c,
withDoubleParameters_c,
withDoubleParametersAndTolerance_c,
withStringParameters_c,
withPointerParameters_c,
withConstPointerParameters_c,
withFunctionPointerParameters_c,
withMemoryBufferParameters_c,
withParameterOfType_c,
withOutputParameterReturning_c,
withOutputParameterOfTypeReturning_c,
withUnmodifiedOutputParameter_c,
ignoreOtherParameters_c,
andReturnBoolValue_c,
andReturnUnsignedIntValue_c,
andReturnIntValue_c,
andReturnLongIntValue_c,
andReturnUnsignedLongIntValue_c,
andReturnLongLongIntValue_c,
andReturnUnsignedLongLongIntValue_c,
andReturnDoubleValue_c,
andReturnStringValue_c,
andReturnPointerValue_c,
andReturnConstPointerValue_c,
andReturnFunctionPointerValue_c,
};
static MockActualCall_c gActualCall = {
withActualBoolParameters_c,
withActualIntParameters_c,
withActualUnsignedIntParameters_c,
withActualLongIntParameters_c,
withActualUnsignedLongIntParameters_c,
withActualLongLongIntParameters_c,
withActualUnsignedLongLongIntParameters_c,
withActualDoubleParameters_c,
withActualStringParameters_c,
withActualPointerParameters_c,
withActualConstPointerParameters_c,
withActualFunctionPointerParameters_c,
withActualMemoryBufferParameters_c,
withActualParameterOfType_c,
withActualOutputParameter_c,
withActualOutputParameterOfType_c,
hasReturnValue_c,
returnValue_c,
boolReturnValue_c,
returnBoolValueOrDefault_c,
intReturnValue_c,
returnIntValueOrDefault_c,
unsignedIntReturnValue_c,
returnUnsignedIntValueOrDefault_c,
longIntReturnValue_c,
returnLongIntValueOrDefault_c,
unsignedLongIntReturnValue_c,
returnUnsignedLongIntValueOrDefault_c,
longLongIntReturnValue_c,
returnLongLongIntValueOrDefault_c,
unsignedLongLongIntReturnValue_c,
returnUnsignedLongLongIntValueOrDefault_c,
stringReturnValue_c,
returnStringValueOrDefault_c,
doubleReturnValue_c,
returnDoubleValueOrDefault_c,
pointerReturnValue_c,
returnPointerValueOrDefault_c,
constPointerReturnValue_c,
returnConstPointerValueOrDefault_c,
functionPointerReturnValue_c,
returnFunctionPointerValueOrDefault_c
};
static MockSupport_c gMockSupport = {
strictOrder_c,
expectOneCall_c,
expectNoCall_c,
expectNCalls_c,
actualCall_c,
hasReturnValue_c,
returnValue_c,
boolReturnValue_c,
returnBoolValueOrDefault_c,
intReturnValue_c,
returnIntValueOrDefault_c,
unsignedIntReturnValue_c,
returnUnsignedIntValueOrDefault_c,
longIntReturnValue_c,
returnLongIntValueOrDefault_c,
unsignedLongIntReturnValue_c,
returnUnsignedLongIntValueOrDefault_c,
longLongIntReturnValue_c,
returnLongLongIntValueOrDefault_c,
unsignedLongLongIntReturnValue_c,
returnUnsignedLongLongIntValueOrDefault_c,
stringReturnValue_c,
returnStringValueOrDefault_c,
doubleReturnValue_c,
returnDoubleValueOrDefault_c,
pointerReturnValue_c,
returnPointerValueOrDefault_c,
constPointerReturnValue_c,
returnConstPointerValueOrDefault_c,
functionPointerReturnValue_c,
returnFunctionPointerValueOrDefault_c,
setBoolData_c,
setIntData_c,
setUnsignedIntData_c,
setStringData_c,
setDoubleData_c,
setPointerData_c,
setConstPointerData_c,
setFunctionPointerData_c,
setDataObject_c,
setDataConstObject_c,
getData_c,
disable_c,
enable_c,
ignoreOtherCalls_c,
checkExpectations_c,
expectedCallsLeft_c,
clear_c,
crashOnFailure_c,
installComparator_c,
installCopier_c,
removeAllComparatorsAndCopiers_c
};
MockExpectedCall_c* withBoolParameters_c(const char* name, int value)
{
expectedCall = &expectedCall->withParameter(name, (value != 0));
return &gExpectedCall;
}
MockExpectedCall_c* withIntParameters_c(const char* name, int value)
{
expectedCall = &expectedCall->withParameter(name, value);
return &gExpectedCall;
}
MockExpectedCall_c* withUnsignedIntParameters_c(const char* name, unsigned int value)
{
expectedCall = &expectedCall->withParameter(name, value);
return &gExpectedCall;
}
MockExpectedCall_c* withLongIntParameters_c(const char* name, long int value)
{
expectedCall = &expectedCall->withParameter(name, value);
return &gExpectedCall;
}
MockExpectedCall_c* withUnsignedLongIntParameters_c(const char* name, unsigned long int value)
{
expectedCall = &expectedCall->withParameter(name, value);
return &gExpectedCall;
}
#if CPPUTEST_USE_LONG_LONG
MockExpectedCall_c* withLongLongIntParameters_c(const char* name, cpputest_longlong value)
{
expectedCall = &expectedCall->withParameter(name, value);
return &gExpectedCall;
}
MockExpectedCall_c* withUnsignedLongLongIntParameters_c(const char* name, cpputest_ulonglong value)
{
expectedCall = &expectedCall->withParameter(name, value);
return &gExpectedCall;
}
#else
MockExpectedCall_c* withLongLongIntParameters_c(const char*, cpputest_longlong)
{
FAIL("Long Long type is not supported");
return &gExpectedCall;
}
MockExpectedCall_c* withUnsignedLongLongIntParameters_c(const char*, cpputest_ulonglong)
{
FAIL("Unsigned Long Long type is not supported");
return &gExpectedCall;
}
#endif
MockExpectedCall_c* withDoubleParameters_c(const char* name, double value)
{
expectedCall = &expectedCall->withParameter(name, value);
return &gExpectedCall;
}
MockExpectedCall_c* withDoubleParametersAndTolerance_c(const char* name, double value, double tolerance)
{
expectedCall = &expectedCall->withParameter(name, value, tolerance);
return &gExpectedCall;
}
MockExpectedCall_c* withStringParameters_c(const char* name, const char* value)
{
expectedCall = &expectedCall->withParameter(name, value);
return &gExpectedCall;
}
MockExpectedCall_c* withPointerParameters_c(const char* name, void* value)
{
expectedCall = &expectedCall->withParameter(name, value);
return &gExpectedCall;
}
MockExpectedCall_c* withConstPointerParameters_c(const char* name, const void* value)
{
expectedCall = &expectedCall->withParameter(name, value);
return &gExpectedCall;
}
MockExpectedCall_c* withFunctionPointerParameters_c(const char* name, void (*value)())
{
expectedCall = &expectedCall->withParameter(name, (cpputest_cpp_function_pointer)value);
return &gExpectedCall;
}
MockExpectedCall_c* withMemoryBufferParameters_c(const char* name, const unsigned char* value, size_t size)
{
expectedCall = &expectedCall->withParameter(name, value, size);
return &gExpectedCall;
}
MockExpectedCall_c* withParameterOfType_c(const char* type, const char* name, const void* value)
{
expectedCall = &expectedCall->withParameterOfType(type, name, value);
return &gExpectedCall;
}
MockExpectedCall_c* withOutputParameterReturning_c(const char* name, const void* value, size_t size)
{
expectedCall = &expectedCall->withOutputParameterReturning(name, value, size);
return &gExpectedCall;
}
MockExpectedCall_c* withOutputParameterOfTypeReturning_c(const char* type, const char* name, const void* value)
{
expectedCall = &expectedCall->withOutputParameterOfTypeReturning(type, name, value);
return &gExpectedCall;
}
MockExpectedCall_c* withUnmodifiedOutputParameter_c(const char* name)
{
expectedCall = &expectedCall->withUnmodifiedOutputParameter(name);
return &gExpectedCall;
}
MockExpectedCall_c* ignoreOtherParameters_c()
{
expectedCall = &expectedCall->ignoreOtherParameters();
return &gExpectedCall;
}
MockExpectedCall_c* andReturnBoolValue_c(int value)
{
expectedCall = &expectedCall->andReturnValue(value != 0);
return &gExpectedCall;
}
MockExpectedCall_c* andReturnUnsignedIntValue_c(unsigned int value)
{
expectedCall = &expectedCall->andReturnValue(value);
return &gExpectedCall;
}
MockExpectedCall_c* andReturnIntValue_c(int value)
{
expectedCall = &expectedCall->andReturnValue(value);
return &gExpectedCall;
}
MockExpectedCall_c* andReturnLongIntValue_c(long int value)
{
expectedCall = &expectedCall->andReturnValue(value);
return &gExpectedCall;
}
MockExpectedCall_c* andReturnUnsignedLongIntValue_c(unsigned long int value)
{
expectedCall = &expectedCall->andReturnValue(value);
return &gExpectedCall;
}
#if CPPUTEST_USE_LONG_LONG
MockExpectedCall_c* andReturnLongLongIntValue_c(cpputest_longlong value)
{
expectedCall = &expectedCall->andReturnValue(value);
return &gExpectedCall;
}
MockExpectedCall_c* andReturnUnsignedLongLongIntValue_c(cpputest_ulonglong value)
{
expectedCall = &expectedCall->andReturnValue(value);
return &gExpectedCall;
}
#else
MockExpectedCall_c* andReturnLongLongIntValue_c(cpputest_longlong)
{
FAIL("Long Long type is not supported");
return &gExpectedCall;
}
MockExpectedCall_c* andReturnUnsignedLongLongIntValue_c(cpputest_ulonglong)
{
FAIL("Unsigned Long Long type is not supported");
return &gExpectedCall;
}
#endif
MockExpectedCall_c* andReturnDoubleValue_c(double value)
{
expectedCall = &expectedCall->andReturnValue(value);
return &gExpectedCall;
}
MockExpectedCall_c* andReturnStringValue_c(const char* value)
{
expectedCall = &expectedCall->andReturnValue(value);
return &gExpectedCall;
}
MockExpectedCall_c* andReturnPointerValue_c(void* value)
{
expectedCall = &expectedCall->andReturnValue(value);
return &gExpectedCall;
}
MockExpectedCall_c* andReturnConstPointerValue_c(const void* value)
{
expectedCall = &expectedCall->andReturnValue(value);
return &gExpectedCall;
}
MockExpectedCall_c* andReturnFunctionPointerValue_c(void (*value)())
{
expectedCall = &expectedCall->andReturnValue((cpputest_cpp_function_pointer)value);
return &gExpectedCall;
}
static MockValue_c getMockValueCFromNamedValue(const MockNamedValue& namedValue)
{
MockValue_c returnValue;
if (SimpleString::StrCmp(namedValue.getType().asCharString(), "bool") == 0) {
returnValue.type = MOCKVALUETYPE_BOOL;
returnValue.value.boolValue = namedValue.getBoolValue() ? 1 : 0;
}
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "int") == 0) {
returnValue.type = MOCKVALUETYPE_INTEGER;
returnValue.value.intValue = namedValue.getIntValue();
}
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "unsigned int") == 0) {
returnValue.type = MOCKVALUETYPE_UNSIGNED_INTEGER;
returnValue.value.unsignedIntValue = namedValue.getUnsignedIntValue();
}
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "long int") == 0) {
returnValue.type = MOCKVALUETYPE_LONG_INTEGER;
returnValue.value.longIntValue = namedValue.getLongIntValue();
}
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "unsigned long int") == 0) {
returnValue.type = MOCKVALUETYPE_UNSIGNED_LONG_INTEGER;
returnValue.value.unsignedLongIntValue = namedValue.getUnsignedLongIntValue();
}
#if CPPUTEST_USE_LONG_LONG
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "long long int") == 0) {
returnValue.type = MOCKVALUETYPE_LONG_LONG_INTEGER;
returnValue.value.longLongIntValue = namedValue.getLongLongIntValue();
}
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "unsigned long long int") == 0) {
returnValue.type = MOCKVALUETYPE_UNSIGNED_LONG_LONG_INTEGER;
returnValue.value.unsignedLongLongIntValue = namedValue.getUnsignedLongLongIntValue();
}
#endif
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "double") == 0) {
returnValue.type = MOCKVALUETYPE_DOUBLE;
returnValue.value.doubleValue = namedValue.getDoubleValue();
}
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "const char*") == 0) {
returnValue.type = MOCKVALUETYPE_STRING;
returnValue.value.stringValue = namedValue.getStringValue();
}
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "void*") == 0) {
returnValue.type = MOCKVALUETYPE_POINTER;
returnValue.value.pointerValue = namedValue.getPointerValue();
}
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "const void*") == 0) {
returnValue.type = MOCKVALUETYPE_CONST_POINTER;
returnValue.value.constPointerValue = namedValue.getConstPointerValue();
}
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "void (*)()") == 0) {
returnValue.type = MOCKVALUETYPE_FUNCTIONPOINTER;
returnValue.value.functionPointerValue = (void (*)()) namedValue.getFunctionPointerValue();
}
else if (SimpleString::StrCmp(namedValue.getType().asCharString(), "const unsigned char*") == 0) {
returnValue.type = MOCKVALUETYPE_MEMORYBUFFER;
returnValue.value.memoryBufferValue = namedValue.getMemoryBuffer();
}
else {
returnValue.type = MOCKVALUETYPE_OBJECT;
returnValue.value.objectValue = namedValue.getObjectPointer();
}
return returnValue;
}
void strictOrder_c()
{
currentMockSupport->strictOrder();
}
MockExpectedCall_c* expectOneCall_c(const char* name)
{
expectedCall = ¤tMockSupport->expectOneCall(name);
return &gExpectedCall;
}
void expectNoCall_c(const char* name)
{
currentMockSupport->expectNoCall(name);
}
MockExpectedCall_c* expectNCalls_c(const unsigned int number, const char* name)
{
expectedCall = ¤tMockSupport->expectNCalls(number, name);
return &gExpectedCall;
}
MockActualCall_c* actualCall_c(const char* name)
{
actualCall = ¤tMockSupport->actualCall(name);
return &gActualCall;
}
MockActualCall_c* withActualBoolParameters_c(const char* name, int value)
{
actualCall = &actualCall->withParameter(name, (value != 0));
return &gActualCall;
}
MockActualCall_c* withActualIntParameters_c(const char* name, int value)
{
actualCall = &actualCall->withParameter(name, value);
return &gActualCall;
}
MockActualCall_c* withActualUnsignedIntParameters_c(const char* name, unsigned int value)
{
actualCall = &actualCall->withParameter(name, value);
return &gActualCall;
}
MockActualCall_c* withActualLongIntParameters_c(const char* name, long int value)
{
actualCall = &actualCall->withParameter(name, value);
return &gActualCall;
}
MockActualCall_c* withActualUnsignedLongIntParameters_c(const char* name, unsigned long int value)
{
actualCall = &actualCall->withParameter(name, value);
return &gActualCall;
}
#if CPPUTEST_USE_LONG_LONG
MockActualCall_c* withActualLongLongIntParameters_c(const char* name, cpputest_longlong value)
{
actualCall = &actualCall->withParameter(name, value);
return &gActualCall;
}
MockActualCall_c* withActualUnsignedLongLongIntParameters_c(const char* name, cpputest_ulonglong value)
{
actualCall = &actualCall->withParameter(name, value);
return &gActualCall;
}
#else
MockActualCall_c* withActualLongLongIntParameters_c(const char*, cpputest_longlong)
{
FAIL("Long Long type is not supported");
return &gActualCall;
}
MockActualCall_c* withActualUnsignedLongLongIntParameters_c(const char*, cpputest_ulonglong)
{
FAIL("Unsigned Long Long type is not supported");
return &gActualCall;
}
#endif
MockActualCall_c* withActualDoubleParameters_c(const char* name, double value)
{
actualCall = &actualCall->withParameter(name, value);
return &gActualCall;
}
MockActualCall_c* withActualStringParameters_c(const char* name, const char* value)
{
actualCall = &actualCall->withParameter(name, value);
return &gActualCall;
}
MockActualCall_c* withActualPointerParameters_c(const char* name, void* value)
{
actualCall = &actualCall->withParameter(name, value);
return &gActualCall;
}
MockActualCall_c* withActualConstPointerParameters_c(const char* name, const void* value)
{
actualCall = &actualCall->withParameter(name, value);
return &gActualCall;
}
MockActualCall_c* withActualFunctionPointerParameters_c(const char* name, void (*value)())
{
actualCall = &actualCall->withParameter(name, (cpputest_cpp_function_pointer) value);
return &gActualCall;
}
MockActualCall_c* withActualMemoryBufferParameters_c(const char* name, const unsigned char* value, size_t size)
{
actualCall = &actualCall->withParameter(name, value, size);
return &gActualCall;
}
MockActualCall_c* withActualParameterOfType_c(const char* type, const char* name, const void* value)
{
actualCall = &actualCall->withParameterOfType(type, name, value);
return &gActualCall;
}
MockActualCall_c* withActualOutputParameter_c(const char* name, void* value)
{
actualCall = &actualCall->withOutputParameter(name, value);
return &gActualCall;
}
MockActualCall_c* withActualOutputParameterOfType_c(const char* type, const char* name, void* value)
{
actualCall = &actualCall->withOutputParameterOfType(type, name, value);
return &gActualCall;
}
MockValue_c returnValue_c()
{
return getMockValueCFromNamedValue(actualCall->returnValue());
}
int boolReturnValue_c()
{
return actualCall->returnBoolValue() ? 1 : 0;
}
int returnBoolValueOrDefault_c(int defaultValue)
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return boolReturnValue_c();
}
int intReturnValue_c()
{
return actualCall->returnIntValue();
}
int returnIntValueOrDefault_c(int defaultValue)
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return intReturnValue_c();
}
unsigned int unsignedIntReturnValue_c()
{
return actualCall->returnUnsignedIntValue();
}
unsigned int returnUnsignedIntValueOrDefault_c(unsigned int defaultValue)
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return unsignedIntReturnValue_c();
}
long int longIntReturnValue_c()
{
return actualCall->returnLongIntValue();
}
long int returnLongIntValueOrDefault_c(long int defaultValue)
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return longIntReturnValue_c();
}
unsigned long int unsignedLongIntReturnValue_c()
{
return actualCall->returnUnsignedLongIntValue();
}
unsigned long int returnUnsignedLongIntValueOrDefault_c(unsigned long int defaultValue)
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return unsignedLongIntReturnValue_c();
}
#if CPPUTEST_USE_LONG_LONG
cpputest_longlong longLongIntReturnValue_c()
{
return actualCall->returnLongLongIntValue();
}
cpputest_longlong returnLongLongIntValueOrDefault_c(cpputest_longlong defaultValue)
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return longLongIntReturnValue_c();
}
cpputest_ulonglong unsignedLongLongIntReturnValue_c()
{
return actualCall->returnUnsignedLongLongIntValue();
}
cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault_c(cpputest_ulonglong defaultValue)
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return unsignedLongLongIntReturnValue_c();
}
#else
cpputest_longlong longLongIntReturnValue_c()
{
FAIL("Long Long type is not supported");
cpputest_longlong ret = {};
return ret;
}
cpputest_longlong returnLongLongIntValueOrDefault_c(cpputest_longlong)
{
FAIL("Long Long type is not supported");
cpputest_longlong ret = {};
return ret;
}
cpputest_ulonglong unsignedLongLongIntReturnValue_c()
{
FAIL("Unsigned Long Long type is not supported");
cpputest_ulonglong ret = {};
return ret;
}
cpputest_ulonglong returnUnsignedLongLongIntValueOrDefault_c(cpputest_ulonglong)
{
FAIL("Unsigned Long Long type is not supported");
cpputest_ulonglong ret = {};
return ret;
}
#endif
const char* stringReturnValue_c()
{
return actualCall->returnStringValue();
}
const char* returnStringValueOrDefault_c(const char * defaultValue)
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return stringReturnValue_c();
}
double doubleReturnValue_c()
{
return actualCall->returnDoubleValue();
}
double returnDoubleValueOrDefault_c(double defaultValue)
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return doubleReturnValue_c();
}
void* pointerReturnValue_c()
{
return actualCall->returnPointerValue();
}
void* returnPointerValueOrDefault_c(void * defaultValue)
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return pointerReturnValue_c();
}
const void* constPointerReturnValue_c()
{
return actualCall->returnConstPointerValue();
}
const void* returnConstPointerValueOrDefault_c(const void * defaultValue)
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return constPointerReturnValue_c();
}
void (*functionPointerReturnValue_c())()
{
return (void (*)()) actualCall->returnFunctionPointerValue();
}
void (*returnFunctionPointerValueOrDefault_c(void (*defaultValue)()))()
{
if (!hasReturnValue_c()) {
return defaultValue;
}
return functionPointerReturnValue_c();
}
void disable_c()
{
currentMockSupport->disable();
}
void enable_c()
{
currentMockSupport->enable();
}
void ignoreOtherCalls_c()
{
currentMockSupport->ignoreOtherCalls();
}
void setBoolData_c(const char* name, int value)
{
currentMockSupport->setData(name, (value != 0));
}
void setIntData_c(const char* name, int value)
{
currentMockSupport->setData(name, value);
}
void setUnsignedIntData_c(const char* name, unsigned int value)
{
currentMockSupport->setData(name, value);
}
void setDoubleData_c(const char* name, double value)
{
currentMockSupport->setData(name, value);
}
void setStringData_c(const char* name, const char* value)
{
currentMockSupport->setData(name, value);
}
void setPointerData_c(const char* name, void* value)
{
currentMockSupport->setData(name, value);
}
void setConstPointerData_c(const char* name, const void* value)
{
currentMockSupport->setData(name, value);
}
void setFunctionPointerData_c(const char* name, void (*value)())
{
currentMockSupport->setData(name, (cpputest_cpp_function_pointer) value);
}
void setDataObject_c(const char* name, const char* type, void* value)
{
currentMockSupport->setDataObject(name, type, value);
}
void setDataConstObject_c(const char* name, const char* type, const void* value)
{
currentMockSupport->setDataConstObject(name, type, value);
}
MockValue_c getData_c(const char* name)
{
return getMockValueCFromNamedValue(currentMockSupport->getData(name));
}
int hasReturnValue_c()
{
return currentMockSupport->hasReturnValue();
}
void checkExpectations_c()
{
currentMockSupport->checkExpectations();
}
int expectedCallsLeft_c()
{
return currentMockSupport->expectedCallsLeft();
}
void clear_c()
{
currentMockSupport->clear();
}
void crashOnFailure_c(unsigned shouldCrash)
{
currentMockSupport->crashOnFailure(0 != shouldCrash);
}
MockSupport_c* mock_c()
{
currentMockSupport = &mock("", &failureReporterForC);
return &gMockSupport;
}
MockSupport_c* mock_scope_c(const char* scope)
{
currentMockSupport = &mock(scope, &failureReporterForC);
return &gMockSupport;
}
}
| null |
210 | cpp | cpputest | MockExpectedCallsList.cpp | src/CppUTestExt/MockExpectedCallsList.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/MockExpectedCallsList.h"
#include "CppUTestExt/MockCheckedExpectedCall.h"
MockExpectedCallsList::MockExpectedCallsList() : head_(NULLPTR)
{
}
MockExpectedCallsList::~MockExpectedCallsList()
{
while (head_) {
MockExpectedCallsListNode* next = head_->next_;
delete head_;
head_ = next;
}
}
bool MockExpectedCallsList::hasCallsOutOfOrder() const
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (p->expectedCall_->isOutOfOrder())
return true;
return false;
}
unsigned int MockExpectedCallsList::size() const
{
unsigned int count = 0;
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
count++;
return count;
}
bool MockExpectedCallsList::isEmpty() const
{
return head_ == NULLPTR;
}
unsigned int MockExpectedCallsList::amountOfActualCallsFulfilledFor(const SimpleString& name) const
{
unsigned int count = 0;
for (MockExpectedCallsListNode* p = head_; p; p = p->next_) {
if (p->expectedCall_->relatesTo(name)) {
count += p->expectedCall_->getActualCallsFulfilled();
}
}
return count;
}
unsigned int MockExpectedCallsList::amountOfUnfulfilledExpectations() const
{
unsigned int count = 0;
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (! p->expectedCall_->isFulfilled()) count++;
return count;
}
bool MockExpectedCallsList::hasFinalizedMatchingExpectations() const
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_) {
if (p->expectedCall_->isMatchingActualCallAndFinalized()) {
return true;
}
}
return false;
}
bool MockExpectedCallsList::hasUnfulfilledExpectations() const
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_) {
if (!p->expectedCall_->isFulfilled()) {
return true;
}
}
return false;
}
bool MockExpectedCallsList::hasExpectationWithName(const SimpleString& name) const
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (p->expectedCall_->relatesTo(name))
return true;
return false;
}
void MockExpectedCallsList::addExpectedCall(MockCheckedExpectedCall* call)
{
MockExpectedCallsListNode* newCall = new MockExpectedCallsListNode(call);
if (head_ == NULLPTR)
head_ = newCall;
else {
MockExpectedCallsListNode* lastCall = head_;
while (lastCall->next_) lastCall = lastCall->next_;
lastCall->next_ = newCall;
}
}
void MockExpectedCallsList::addPotentiallyMatchingExpectations(const MockExpectedCallsList& list)
{
for (MockExpectedCallsListNode* p = list.head_; p; p = p->next_)
if (p->expectedCall_->canMatchActualCalls())
addExpectedCall(p->expectedCall_);
}
void MockExpectedCallsList::addExpectationsRelatedTo(const SimpleString& name, const MockExpectedCallsList& list)
{
for (MockExpectedCallsListNode* p = list.head_; p; p = p->next_)
if (p->expectedCall_->relatesTo(name))
addExpectedCall(p->expectedCall_);
}
void MockExpectedCallsList::addExpectations(const MockExpectedCallsList& list)
{
for (MockExpectedCallsListNode* p = list.head_; p; p = p->next_)
addExpectedCall(p->expectedCall_);
}
void MockExpectedCallsList::onlyKeepExpectationsRelatedTo(const SimpleString& name)
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (! p->expectedCall_->relatesTo(name))
p->expectedCall_ = NULLPTR;
pruneEmptyNodeFromList();
}
void MockExpectedCallsList::onlyKeepOutOfOrderExpectations()
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (!p->expectedCall_->isOutOfOrder())
p->expectedCall_ = NULLPTR;
pruneEmptyNodeFromList();
}
void MockExpectedCallsList::onlyKeepUnmatchingExpectations()
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (p->expectedCall_->isMatchingActualCallAndFinalized())
{
p->expectedCall_->resetActualCallMatchingState();
p->expectedCall_ = NULLPTR;
}
pruneEmptyNodeFromList();
}
void MockExpectedCallsList::onlyKeepExpectationsWithInputParameterName(const SimpleString& name)
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (! p->expectedCall_->hasInputParameterWithName(name))
p->expectedCall_ = NULLPTR;
pruneEmptyNodeFromList();
}
void MockExpectedCallsList::onlyKeepExpectationsWithOutputParameterName(const SimpleString& name)
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (! p->expectedCall_->hasOutputParameterWithName(name))
p->expectedCall_ = NULLPTR;
pruneEmptyNodeFromList();
}
void MockExpectedCallsList::onlyKeepExpectationsWithInputParameter(const MockNamedValue& parameter)
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (! p->expectedCall_->hasInputParameter(parameter))
p->expectedCall_ = NULLPTR;
pruneEmptyNodeFromList();
}
void MockExpectedCallsList::onlyKeepExpectationsWithOutputParameter(const MockNamedValue& parameter)
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (! p->expectedCall_->hasOutputParameter(parameter))
p->expectedCall_ = NULLPTR;
pruneEmptyNodeFromList();
}
void MockExpectedCallsList::onlyKeepExpectationsOnObject(const void* objectPtr)
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (! p->expectedCall_->relatesToObject(objectPtr))
p->expectedCall_ = NULLPTR;
pruneEmptyNodeFromList();
}
MockCheckedExpectedCall* MockExpectedCallsList::removeFirstFinalizedMatchingExpectation()
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_) {
if (p->expectedCall_->isMatchingActualCallAndFinalized()) {
MockCheckedExpectedCall* matchingCall = p->expectedCall_;
p->expectedCall_ = NULLPTR;
pruneEmptyNodeFromList();
return matchingCall;
}
}
return NULLPTR;
}
MockCheckedExpectedCall* MockExpectedCallsList::getFirstMatchingExpectation()
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_) {
if (p->expectedCall_->isMatchingActualCall()) {
return p->expectedCall_;
}
}
return NULLPTR;
}
MockCheckedExpectedCall* MockExpectedCallsList::removeFirstMatchingExpectation()
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_) {
if (p->expectedCall_->isMatchingActualCall()) {
MockCheckedExpectedCall* matchingCall = p->expectedCall_;
p->expectedCall_ = NULLPTR;
pruneEmptyNodeFromList();
return matchingCall;
}
}
return NULLPTR;
}
void MockExpectedCallsList::pruneEmptyNodeFromList()
{
MockExpectedCallsListNode* current = head_;
MockExpectedCallsListNode* previous = NULLPTR;
MockExpectedCallsListNode* toBeDeleted = NULLPTR;
while (current) {
if (current->expectedCall_ == NULLPTR) {
toBeDeleted = current;
if (previous == NULLPTR)
head_ = current = current->next_;
else
current = previous->next_ = current->next_;
delete toBeDeleted;
}
else {
previous = current;
current = current->next_;
}
}
}
void MockExpectedCallsList::deleteAllExpectationsAndClearList()
{
while (head_) {
MockExpectedCallsListNode* next = head_->next_;
delete head_->expectedCall_;
delete head_;
head_ = next;
}
}
void MockExpectedCallsList::resetActualCallMatchingState()
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
p->expectedCall_->resetActualCallMatchingState();
}
void MockExpectedCallsList::wasPassedToObject()
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
p->expectedCall_->wasPassedToObject();
}
void MockExpectedCallsList::parameterWasPassed(const SimpleString& parameterName)
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
p->expectedCall_->inputParameterWasPassed(parameterName);
}
void MockExpectedCallsList::outputParameterWasPassed(const SimpleString& parameterName)
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
p->expectedCall_->outputParameterWasPassed(parameterName);
}
static SimpleString stringOrNoneTextWhenEmpty(const SimpleString& inputString, const SimpleString& linePrefix)
{
SimpleString str = inputString;
if (str == "") {
str += linePrefix;
str += "<none>";
}
return str;
}
static 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 MockExpectedCallsList::unfulfilledCallsToString(const SimpleString& linePrefix) const
{
SimpleString str;
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (!p->expectedCall_->isFulfilled())
str = appendStringOnANewLine(str, linePrefix, p->expectedCall_->callToString());
return stringOrNoneTextWhenEmpty(str, linePrefix);
}
SimpleString MockExpectedCallsList::fulfilledCallsToString(const SimpleString& linePrefix) const
{
SimpleString str;
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (p->expectedCall_->isFulfilled())
str = appendStringOnANewLine(str, linePrefix, p->expectedCall_->callToString());
return stringOrNoneTextWhenEmpty(str, linePrefix);
}
SimpleString MockExpectedCallsList::callsWithMissingParametersToString(const SimpleString& linePrefix,
const SimpleString& missingParametersPrefix) const
{
SimpleString str;
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
{
str = appendStringOnANewLine(str, linePrefix, p->expectedCall_->callToString());
str = appendStringOnANewLine(str, linePrefix + missingParametersPrefix, p->expectedCall_->missingParametersToString());
}
return stringOrNoneTextWhenEmpty(str, linePrefix);
}
bool MockExpectedCallsList::hasUnmatchingExpectationsBecauseOfMissingParameters() const
{
for (MockExpectedCallsListNode* p = head_; p; p = p->next_)
if (! p->expectedCall_->areParametersMatchingActualCall())
return true;
return false;
}
| null |
211 | cpp | 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(TestMemoryAllocator* internalAllocator)
: codeReportingList_(NULLPTR), internalAllocator_(internalAllocator)
{
}
CodeMemoryReportFormatter::~CodeMemoryReportFormatter()
{
clearReporting();
}
void CodeMemoryReportFormatter::clearReporting()
{
while (codeReportingList_) {
CodeReportingAllocationNode* oldNode = codeReportingList_;
codeReportingList_ = codeReportingList_->next_;
internalAllocator_->free_memory((char*) oldNode, 0, __FILE__, __LINE__);
}
}
void CodeMemoryReportFormatter::addNodeToList(const char* variableName, void* memory, CodeReportingAllocationNode* next)
{
CodeReportingAllocationNode* newNode = (CodeReportingAllocationNode*) (void*) internalAllocator_->alloc_memory(sizeof(CodeReportingAllocationNode), __FILE__, __LINE__);
newNode->memory_ = memory;
newNode->next_ = next;
SimpleString::StrNCpy(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 + SimpleString::StrLen(file);
while (fileNameOnly != file && *fileNameOnly != '/')
fileNameOnly--;
if (*fileNameOnly == '/') fileNameOnly++;
return fileNameOnly;
}
SimpleString CodeMemoryReportFormatter::createVariableNameFromFileLineInfo(const char *file, size_t line)
{
SimpleString fileNameOnly = extractFileNameFromPath(file);
fileNameOnly.replace(".", "_");
for (int i = 1; i < 100; i++) {
SimpleString variableName = StringFromFormat("%s_%d_%d", fileNameOnly.asCharString(), (int) line, i);
if (!variableExists(variableName))
return variableName;
}
return "";
}
bool CodeMemoryReportFormatter::isNewAllocator(TestMemoryAllocator* allocator)
{
return SimpleString::StrCmp(allocator->alloc_name(), defaultNewAllocator()->alloc_name()) == 0 || SimpleString::StrCmp(allocator->alloc_name(), defaultNewArrayAllocator()->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(TestMemoryAllocator* allocator, const SimpleString& variableName, size_t size)
{
if (isNewAllocator(allocator))
return StringFromFormat("char* %s = new char[%lu]; /* using %s */", variableName.asCharString(), (unsigned long) size, allocator->alloc_name());
else
return StringFromFormat("void* %s = malloc(%lu);", variableName.asCharString(), (unsigned long) size);
}
SimpleString CodeMemoryReportFormatter::getDeallocationString(TestMemoryAllocator* allocator, const SimpleString& variableName, const char* file, size_t line)
{
if (isNewAllocator(allocator))
return StringFromFormat("delete [] %s; /* using %s at %s:%d */", variableName.asCharString(), allocator->free_name(), file, (int) line);
else
return StringFromFormat("free(%s); /* at %s:%d */", variableName.asCharString(), file, (int) line);
}
void CodeMemoryReportFormatter::report_test_start(TestResult* result, UtestShell& test)
{
clearReporting();
result->print(StringFromFormat("*/\nTEST(%s_memoryReport, %s)\n{ /* at %s:%d */\n",
test.getGroup().asCharString(), test.getName().asCharString(), test.getFile().asCharString(), (int) test.getLineNumber()).asCharString());
}
void CodeMemoryReportFormatter::report_test_end(TestResult* result, UtestShell&)
{
result->print("}/*");
}
void CodeMemoryReportFormatter::report_testgroup_start(TestResult* result, UtestShell& test)
{
result->print(StringFromFormat("*/TEST_GROUP(%s_memoryReport)\n{\n};\n/*",
test.getGroup().asCharString()).asCharString());
}
void CodeMemoryReportFormatter::report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, size_t line)
{
SimpleString variableName = createVariableNameFromFileLineInfo(file, line);
result->print(StringFromFormat("\t%s\n", getAllocationString(allocator, variableName, size).asCharString()).asCharString());
addNodeToList(variableName.asCharString(), memory, codeReportingList_);
}
void CodeMemoryReportFormatter::report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, size_t line)
{
SimpleString variableName;
CodeReportingAllocationNode* node = findNode(memory);
if (memory == NULLPTR) variableName = "NULL";
else variableName = node->variableName_;
result->print(StringFromFormat("\t%s\n", getDeallocationString(allocator, variableName, file, line).asCharString()).asCharString());
}
| null |
212 | cpp | cpputest | GTest.cpp | src/CppUTestExt/GTest.cpp | null |
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/GTestSupport.h"
void CppuTestGTestIgnoreLeaksInTest()
{
IGNORE_ALL_LEAKS_IN_TEST();
}
| null |
213 | cpp | 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
{
UtestShell& test_;
TestResult& result_;
public:
MockSupportPluginReporter(UtestShell& test, TestResult& result)
: test_(test), result_(result)
{
}
virtual void failTest(const MockFailure& failure) CPPUTEST_OVERRIDE
{
result_.addFailure(failure);
}
virtual UtestShell* getTestToFail() CPPUTEST_OVERRIDE
{
return &test_;
}
};
MockSupportPlugin::MockSupportPlugin(const SimpleString& name)
: TestPlugin(name)
{
}
MockSupportPlugin::~MockSupportPlugin()
{
clear();
}
void MockSupportPlugin::clear()
{
repository_.clear();
}
void MockSupportPlugin::preTestAction(UtestShell&, TestResult&)
{
mock().installComparatorsAndCopiers(repository_);
}
void MockSupportPlugin::postTestAction(UtestShell& test, TestResult& result)
{
MockSupportPluginReporter reporter(test, result);
mock().setMockFailureStandardReporter(&reporter);
if (!test.hasFailed())
mock().checkExpectations();
mock().clear();
mock().setMockFailureStandardReporter(NULLPTR);
mock().removeAllComparatorsAndCopiers();
}
void MockSupportPlugin::installComparator(const SimpleString& name, MockNamedValueComparator& comparator)
{
repository_.installComparator(name, comparator);
}
void MockSupportPlugin::installCopier(const SimpleString& name, MockNamedValueCopier& copier)
{
repository_.installCopier(name, copier);
}
| null |
214 | cpp | cpputest | MockActualCall.cpp | src/CppUTestExt/MockActualCall.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/MockCheckedActualCall.h"
#include "CppUTestExt/MockCheckedExpectedCall.h"
#include "CppUTestExt/MockFailure.h"
#include "CppUTest/PlatformSpecificFunctions.h"
MockActualCall::MockActualCall()
{
}
MockActualCall::~MockActualCall()
{
}
void MockCheckedActualCall::setName(const SimpleString& name)
{
functionName_ = name;
}
SimpleString MockCheckedActualCall::getName() const
{
return functionName_;
}
MockCheckedActualCall::MockCheckedActualCall(unsigned int callOrder, MockFailureReporter* reporter, const MockExpectedCallsList& allExpectations)
: callOrder_(callOrder), reporter_(reporter), state_(CALL_SUCCEED), expectationsChecked_(false), matchingExpectation_(NULLPTR),
allExpectations_(allExpectations), outputParameterExpectations_(NULLPTR)
{
potentiallyMatchingExpectations_.addPotentiallyMatchingExpectations(allExpectations);
}
MockCheckedActualCall::~MockCheckedActualCall()
{
cleanUpOutputParameterList();
}
void MockCheckedActualCall::setMockFailureReporter(MockFailureReporter* reporter)
{
reporter_ = reporter;
}
UtestShell* MockCheckedActualCall::getTest() const
{
return reporter_->getTestToFail();
}
void MockCheckedActualCall::failTest(const MockFailure& failure)
{
if (!hasFailed()) {
setState(CALL_FAILED);
reporter_->failTest(failure);
}
}
void MockCheckedActualCall::copyOutputParameters(MockCheckedExpectedCall* expectedCall)
{
for (MockOutputParametersListNode* p = outputParameterExpectations_; p; p = p->next_)
{
MockNamedValue outputParameter = expectedCall->getOutputParameter(p->name_);
MockNamedValueCopier* copier = outputParameter.getCopier();
if (copier)
{
copier->copy(p->ptr_, outputParameter.getConstObjectPointer());
}
else if ((outputParameter.getType() == "const void*") && (p->type_ == "void*"))
{
const void* data = outputParameter.getConstPointerValue();
size_t size = outputParameter.getSize();
PlatformSpecificMemCpy(p->ptr_, data, size);
}
else if (outputParameter.getName() != "")
{
SimpleString type = expectedCall->getOutputParameter(p->name_).getType();
MockNoWayToCopyCustomTypeFailure failure(getTest(), type);
failTest(failure);
}
}
}
void MockCheckedActualCall::completeCallWhenMatchIsFound()
{
// Expectations that don't ignore parameters have higher fulfillment preference than those that ignore parameters
matchingExpectation_ = potentiallyMatchingExpectations_.removeFirstFinalizedMatchingExpectation();
if (matchingExpectation_) {
copyOutputParameters(matchingExpectation_);
callHasSucceeded();
} else {
MockCheckedExpectedCall* matchingExpectationWithIgnoredParameters = potentiallyMatchingExpectations_.getFirstMatchingExpectation();
if (matchingExpectationWithIgnoredParameters) {
copyOutputParameters(matchingExpectationWithIgnoredParameters);
}
}
}
void MockCheckedActualCall::callHasSucceeded()
{
setState(CALL_SUCCEED);
}
void MockCheckedActualCall::discardCurrentlyMatchingExpectations()
{
if (matchingExpectation_)
{
matchingExpectation_->resetActualCallMatchingState();
matchingExpectation_ = NULLPTR;
}
potentiallyMatchingExpectations_.onlyKeepUnmatchingExpectations();
}
MockActualCall& MockCheckedActualCall::withName(const SimpleString& name)
{
setName(name);
setState(CALL_IN_PROGRESS);
potentiallyMatchingExpectations_.onlyKeepExpectationsRelatedTo(name);
if (potentiallyMatchingExpectations_.isEmpty()) {
MockUnexpectedCallHappenedFailure failure(getTest(), name, allExpectations_);
failTest(failure);
return *this;
}
completeCallWhenMatchIsFound();
return *this;
}
MockActualCall& MockCheckedActualCall::withCallOrder(unsigned int)
{
return *this;
}
void MockCheckedActualCall::checkInputParameter(const MockNamedValue& actualParameter)
{
if(hasFailed())
{
return;
}
setState(CALL_IN_PROGRESS);
discardCurrentlyMatchingExpectations();
potentiallyMatchingExpectations_.onlyKeepExpectationsWithInputParameter(actualParameter);
if (potentiallyMatchingExpectations_.isEmpty()) {
MockUnexpectedInputParameterFailure failure(getTest(), getName(), actualParameter, allExpectations_);
failTest(failure);
return;
}
potentiallyMatchingExpectations_.parameterWasPassed(actualParameter.getName());
completeCallWhenMatchIsFound();
}
void MockCheckedActualCall::checkOutputParameter(const MockNamedValue& outputParameter)
{
if(hasFailed())
{
return;
}
setState(CALL_IN_PROGRESS);
discardCurrentlyMatchingExpectations();
potentiallyMatchingExpectations_.onlyKeepExpectationsWithOutputParameter(outputParameter);
if (potentiallyMatchingExpectations_.isEmpty()) {
MockUnexpectedOutputParameterFailure failure(getTest(), getName(), outputParameter, allExpectations_);
failTest(failure);
return;
}
potentiallyMatchingExpectations_.outputParameterWasPassed(outputParameter.getName());
completeCallWhenMatchIsFound();
}
MockActualCall& MockCheckedActualCall::withBoolParameter(const SimpleString& name, bool value)
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withUnsignedIntParameter(const SimpleString& name, unsigned int value)
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withIntParameter(const SimpleString& name, int value)
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value)
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withLongIntParameter(const SimpleString& name, long int value)
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
#if CPPUTEST_USE_LONG_LONG
MockActualCall& MockCheckedActualCall::withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value)
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withLongLongIntParameter(const SimpleString& name, cpputest_longlong value)
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
#else
MockActualCall& MockCheckedActualCall::withUnsignedLongLongIntParameter(const SimpleString&, cpputest_ulonglong)
{
FAIL("Unsigned Long Long type is not supported");
return *this;
}
MockActualCall& MockCheckedActualCall::withLongLongIntParameter(const SimpleString&, cpputest_longlong)
{
FAIL("Long Long type is not supported");
return *this;
}
#endif
MockActualCall& MockCheckedActualCall::withDoubleParameter(const SimpleString& name, double value)
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withStringParameter(const SimpleString& name, const char* value)
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withPointerParameter(const SimpleString& name, void* value)
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withConstPointerParameter(const SimpleString& name, const void* value)
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withFunctionPointerParameter(const SimpleString& name, void (*value)())
{
MockNamedValue actualParameter(name);
actualParameter.setValue(value);
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size)
{
MockNamedValue actualParameter(name);
actualParameter.setMemoryBuffer(value, size);
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withParameterOfType(const SimpleString& type, const SimpleString& name, const void* value)
{
MockNamedValue actualParameter(name);
actualParameter.setConstObjectPointer(type, value);
if (actualParameter.getComparator() == NULLPTR) {
MockNoWayToCompareCustomTypeFailure failure(getTest(), type);
failTest(failure);
return *this;
}
checkInputParameter(actualParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withOutputParameter(const SimpleString& name, void* output)
{
addOutputParameter(name, "void*", output);
MockNamedValue outputParameter(name);
outputParameter.setValue(output);
checkOutputParameter(outputParameter);
return *this;
}
MockActualCall& MockCheckedActualCall::withOutputParameterOfType(const SimpleString& type, const SimpleString& name, void* output)
{
addOutputParameter(name, type, output);
MockNamedValue outputParameter(name);
outputParameter.setConstObjectPointer(type, output);
checkOutputParameter(outputParameter);
return *this;
}
bool MockCheckedActualCall::isFulfilled() const
{
return state_ == CALL_SUCCEED;
}
bool MockCheckedActualCall::hasFailed() const
{
return state_ == CALL_FAILED;
}
void MockCheckedActualCall::checkExpectations()
{
if(expectationsChecked_) {
return;
}
expectationsChecked_ = true;
if (state_ != CALL_IN_PROGRESS) {
if(state_ == CALL_SUCCEED) {
matchingExpectation_->callWasMade(callOrder_);
}
potentiallyMatchingExpectations_.resetActualCallMatchingState();
return;
}
if (potentiallyMatchingExpectations_.hasFinalizedMatchingExpectations())
FAIL("Actual call is in progress, but there are finalized matching expectations when checking expectations. This cannot happen."); // LCOV_EXCL_LINE
matchingExpectation_ = potentiallyMatchingExpectations_.removeFirstMatchingExpectation();
if (matchingExpectation_) {
matchingExpectation_->finalizeActualCallMatch();
callHasSucceeded();
matchingExpectation_->callWasMade(callOrder_);
potentiallyMatchingExpectations_.resetActualCallMatchingState();
return;
}
if (potentiallyMatchingExpectations_.hasUnmatchingExpectationsBecauseOfMissingParameters()) {
MockExpectedParameterDidntHappenFailure failure(getTest(), getName(), allExpectations_, potentiallyMatchingExpectations_);
failTest(failure);
}
else {
MockExpectedObjectDidntHappenFailure failure(getTest(), getName(), allExpectations_);
failTest(failure);
}
}
void MockCheckedActualCall::setState(ActualCallState state)
{
state_ = state;
}
MockNamedValue MockCheckedActualCall::returnValue()
{
checkExpectations();
if (matchingExpectation_)
return matchingExpectation_->returnValue();
return MockNamedValue("no return value");
}
bool MockCheckedActualCall::returnBoolValueOrDefault(bool default_value)
{
if (!hasReturnValue()) {
return default_value;
}
return returnBoolValue();
}
bool MockCheckedActualCall::returnBoolValue()
{
return returnValue().getBoolValue();
}
int MockCheckedActualCall::returnIntValueOrDefault(int default_value)
{
if (!hasReturnValue()) {
return default_value;
}
return returnIntValue();
}
int MockCheckedActualCall::returnIntValue()
{
return returnValue().getIntValue();
}
unsigned long int MockCheckedActualCall::returnUnsignedLongIntValue()
{
return returnValue().getUnsignedLongIntValue();
}
unsigned long int MockCheckedActualCall::returnUnsignedLongIntValueOrDefault(unsigned long int default_value)
{
if (!hasReturnValue()) {
return default_value;
}
return returnUnsignedLongIntValue();
}
long int MockCheckedActualCall::returnLongIntValue()
{
return returnValue().getLongIntValue();
}
long int MockCheckedActualCall::returnLongIntValueOrDefault(long int default_value)
{
if (!hasReturnValue()) {
return default_value;
}
return returnLongIntValue();
}
#if CPPUTEST_USE_LONG_LONG
cpputest_ulonglong MockCheckedActualCall::returnUnsignedLongLongIntValue()
{
return returnValue().getUnsignedLongLongIntValue();
}
cpputest_ulonglong MockCheckedActualCall::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong default_value)
{
if (!hasReturnValue()) {
return default_value;
}
return returnUnsignedLongLongIntValue();
}
cpputest_longlong MockCheckedActualCall::returnLongLongIntValue()
{
return returnValue().getLongLongIntValue();
}
cpputest_longlong MockCheckedActualCall::returnLongLongIntValueOrDefault(cpputest_longlong default_value)
{
if (!hasReturnValue()) {
return default_value;
}
return returnLongLongIntValue();
}
#else
cpputest_ulonglong MockCheckedActualCall::returnUnsignedLongLongIntValue()
{
FAIL("Unsigned Long Long type is not supported");
cpputest_ulonglong ret = {};
return ret;
}
cpputest_ulonglong MockCheckedActualCall::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong default_value)
{
FAIL("Unsigned Long Long type is not supported");
return default_value;
}
cpputest_longlong MockCheckedActualCall::returnLongLongIntValue()
{
FAIL("Long Long type is not supported");
cpputest_longlong ret = {};
return ret;
}
cpputest_longlong MockCheckedActualCall::returnLongLongIntValueOrDefault(cpputest_longlong default_value)
{
FAIL("Long Long type is not supported");
return default_value;
}
#endif
double MockCheckedActualCall::returnDoubleValue()
{
return returnValue().getDoubleValue();
}
double MockCheckedActualCall::returnDoubleValueOrDefault(double default_value)
{
if (!hasReturnValue()) {
return default_value;
}
return returnDoubleValue();
}
unsigned int MockCheckedActualCall::returnUnsignedIntValue()
{
return returnValue().getUnsignedIntValue();
}
unsigned int MockCheckedActualCall::returnUnsignedIntValueOrDefault(unsigned int default_value)
{
if (!hasReturnValue()) {
return default_value;
}
return returnUnsignedIntValue();
}
void * MockCheckedActualCall::returnPointerValueOrDefault(void * default_value)
{
if (!hasReturnValue()) {
return default_value;
}
return returnPointerValue();
}
void * MockCheckedActualCall::returnPointerValue()
{
return returnValue().getPointerValue();
}
const void * MockCheckedActualCall::returnConstPointerValue()
{
return returnValue().getConstPointerValue();
}
const void * MockCheckedActualCall::returnConstPointerValueOrDefault(const void * default_value)
{
if (!hasReturnValue()) {
return default_value;
}
return returnConstPointerValue();
}
void (*MockCheckedActualCall::returnFunctionPointerValue())()
{
return returnValue().getFunctionPointerValue();
}
void (*MockCheckedActualCall::returnFunctionPointerValueOrDefault(void (*default_value)()))()
{
if (!hasReturnValue()) {
return default_value;
}
return returnFunctionPointerValue();
}
const char * MockCheckedActualCall::returnStringValueOrDefault(const char * default_value)
{
if (!hasReturnValue()) {
return default_value;
}
return returnStringValue();
}
const char * MockCheckedActualCall::returnStringValue()
{
return returnValue().getStringValue();
}
bool MockCheckedActualCall::hasReturnValue()
{
return ! returnValue().getName().isEmpty();
}
MockActualCall& MockCheckedActualCall::onObject(const void* objectPtr)
{
if(hasFailed()) {
return *this;
}
// Currently matching expectations are not discarded because the passed object
// is ignored if not specifically set in the expectation
potentiallyMatchingExpectations_.onlyKeepExpectationsOnObject(objectPtr);
if ((!matchingExpectation_) && potentiallyMatchingExpectations_.isEmpty()) {
MockUnexpectedObjectFailure failure(getTest(), getName(), objectPtr, allExpectations_);
failTest(failure);
return *this;
}
potentiallyMatchingExpectations_.wasPassedToObject();
if (!matchingExpectation_) {
completeCallWhenMatchIsFound();
}
return *this;
}
void MockCheckedActualCall::addOutputParameter(const SimpleString& name, const SimpleString& type, void* ptr)
{
MockOutputParametersListNode* newNode = new MockOutputParametersListNode(name, type, ptr);
if (outputParameterExpectations_ == NULLPTR)
outputParameterExpectations_ = newNode;
else {
MockOutputParametersListNode* lastNode = outputParameterExpectations_;
while (lastNode->next_) lastNode = lastNode->next_;
lastNode->next_ = newNode;
}
}
void MockCheckedActualCall::cleanUpOutputParameterList()
{
MockOutputParametersListNode* current = outputParameterExpectations_;
MockOutputParametersListNode* toBeDeleted = NULLPTR;
while (current) {
toBeDeleted = current;
outputParameterExpectations_ = current = current->next_;
delete toBeDeleted;
}
}
MockActualCallTrace::MockActualCallTrace()
{
}
MockActualCallTrace::~MockActualCallTrace()
{
}
MockActualCall& MockActualCallTrace::withName(const SimpleString& name)
{
traceBuffer_ += "\nFunction name:";
traceBuffer_ += name;
return *this;
}
MockActualCall& MockActualCallTrace::withCallOrder(unsigned int callOrder)
{
traceBuffer_ += " withCallOrder:";
traceBuffer_ += StringFrom(callOrder);
return *this;
}
void MockActualCallTrace::addParameterName(const SimpleString& name)
{
traceBuffer_ += " ";
traceBuffer_ += name;
traceBuffer_ += ":";
}
MockActualCall& MockActualCallTrace::withBoolParameter(const SimpleString& name, bool value)
{
addParameterName(name);
traceBuffer_ += StringFrom(value);
return *this;
}
MockActualCall& MockActualCallTrace::withUnsignedIntParameter(const SimpleString& name, unsigned int value)
{
addParameterName(name);
traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value);
return *this;
}
MockActualCall& MockActualCallTrace::withIntParameter(const SimpleString& name, int value)
{
addParameterName(name);
traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value);
return *this;
}
MockActualCall& MockActualCallTrace::withUnsignedLongIntParameter(const SimpleString& name, unsigned long int value)
{
addParameterName(name);
traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value);
return *this;
}
MockActualCall& MockActualCallTrace::withLongIntParameter(const SimpleString& name, long int value)
{
addParameterName(name);
traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value);
return *this;
}
#if CPPUTEST_USE_LONG_LONG
MockActualCall& MockActualCallTrace::withUnsignedLongLongIntParameter(const SimpleString& name, cpputest_ulonglong value)
{
addParameterName(name);
traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value);
return *this;
}
MockActualCall& MockActualCallTrace::withLongLongIntParameter(const SimpleString& name, cpputest_longlong value)
{
addParameterName(name);
traceBuffer_ += StringFrom(value) + " " + BracketsFormattedHexStringFrom(value);
return *this;
}
#else
MockActualCall& MockActualCallTrace::withUnsignedLongLongIntParameter(const SimpleString&, cpputest_ulonglong)
{
FAIL("Unsigned Long Long type is not supported");
return *this;
}
MockActualCall& MockActualCallTrace::withLongLongIntParameter(const SimpleString&, cpputest_longlong)
{
FAIL("Long Long type is not supported");
return *this;
}
#endif
MockActualCall& MockActualCallTrace::withDoubleParameter(const SimpleString& name, double value)
{
addParameterName(name);
traceBuffer_ += StringFrom(value);
return *this;
}
MockActualCall& MockActualCallTrace::withStringParameter(const SimpleString& name, const char* value)
{
addParameterName(name);
traceBuffer_ += StringFrom(value);
return *this;
}
MockActualCall& MockActualCallTrace::withPointerParameter(const SimpleString& name, void* value)
{
addParameterName(name);
traceBuffer_ += StringFrom(value);
return *this;
}
MockActualCall& MockActualCallTrace::withConstPointerParameter(const SimpleString& name, const void* value)
{
addParameterName(name);
traceBuffer_ += StringFrom(value);
return *this;
}
MockActualCall& MockActualCallTrace::withFunctionPointerParameter(const SimpleString& name, void (*value)())
{
addParameterName(name);
traceBuffer_ += StringFrom(value);
return *this;
}
MockActualCall& MockActualCallTrace::withMemoryBufferParameter(const SimpleString& name, const unsigned char* value, size_t size)
{
addParameterName(name);
traceBuffer_ += StringFromBinaryWithSizeOrNull(value, size);
return *this;
}
MockActualCall& MockActualCallTrace::withParameterOfType(const SimpleString& typeName, const SimpleString& name, const void* value)
{
traceBuffer_ += " ";
traceBuffer_ += typeName;
addParameterName(name);
traceBuffer_ += StringFrom(value);
return *this;
}
MockActualCall& MockActualCallTrace::withOutputParameter(const SimpleString& name, void* output)
{
addParameterName(name);
traceBuffer_ += StringFrom(output);
return *this;
}
MockActualCall& MockActualCallTrace::withOutputParameterOfType(const SimpleString& typeName, const SimpleString& name, void* output)
{
traceBuffer_ += " ";
traceBuffer_ += typeName;
addParameterName(name);
traceBuffer_ += StringFrom(output);
return *this;
}
bool MockActualCallTrace::hasReturnValue()
{
return false;
}
MockNamedValue MockActualCallTrace::returnValue()
{
return MockNamedValue("");
}
long int MockActualCallTrace::returnLongIntValue()
{
return 0;
}
unsigned long int MockActualCallTrace::returnUnsignedLongIntValue()
{
return 0;
}
unsigned long int MockActualCallTrace::returnUnsignedLongIntValueOrDefault(unsigned long)
{
return 0;
}
long int MockActualCallTrace::returnLongIntValueOrDefault(long int)
{
return 0;
}
#if CPPUTEST_USE_LONG_LONG
cpputest_longlong MockActualCallTrace::returnLongLongIntValue()
{
return 0;
}
cpputest_ulonglong MockActualCallTrace::returnUnsignedLongLongIntValue()
{
return 0;
}
cpputest_ulonglong MockActualCallTrace::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong)
{
return 0;
}
cpputest_longlong MockActualCallTrace::returnLongLongIntValueOrDefault(cpputest_longlong)
{
return 0;
}
#else
cpputest_longlong MockActualCallTrace::returnLongLongIntValue()
{
FAIL("Long Long type is not supported");
cpputest_longlong ret = {};
return ret;
}
cpputest_ulonglong MockActualCallTrace::returnUnsignedLongLongIntValue()
{
FAIL("Unsigned Long Long type is not supported");
cpputest_ulonglong ret = {};
return ret;
}
cpputest_ulonglong MockActualCallTrace::returnUnsignedLongLongIntValueOrDefault(cpputest_ulonglong)
{
FAIL("Unsigned Long Long type is not supported");
cpputest_ulonglong ret = {};
return ret;
}
cpputest_longlong MockActualCallTrace::returnLongLongIntValueOrDefault(cpputest_longlong)
{
FAIL("Long Long type is not supported");
cpputest_longlong ret = {};
return ret;
}
#endif
bool MockActualCallTrace::returnBoolValue()
{
return false;
}
bool MockActualCallTrace::returnBoolValueOrDefault(bool)
{
return false;
}
int MockActualCallTrace::returnIntValue()
{
return 0;
}
double MockActualCallTrace::returnDoubleValue()
{
return 0.0;
}
double MockActualCallTrace::returnDoubleValueOrDefault(double)
{
return returnDoubleValue();
}
unsigned int MockActualCallTrace::returnUnsignedIntValue()
{
return 0;
}
void * MockActualCallTrace::returnPointerValue()
{
return NULLPTR;
}
const void * MockActualCallTrace::returnConstPointerValue()
{
return NULLPTR;
}
void (*MockActualCallTrace::returnFunctionPointerValue())()
{
return NULLPTR;
}
const void * MockActualCallTrace::returnConstPointerValueOrDefault(const void *)
{
return returnConstPointerValue();
}
void * MockActualCallTrace::returnPointerValueOrDefault(void *)
{
return returnPointerValue();
}
void (*MockActualCallTrace::returnFunctionPointerValueOrDefault(void (*)()))()
{
return returnFunctionPointerValue();
}
const char * MockActualCallTrace::returnStringValue()
{
return "";
}
const char * MockActualCallTrace::returnStringValueOrDefault(const char *)
{
return returnStringValue();
}
int MockActualCallTrace::returnIntValueOrDefault(int)
{
return 0;
}
unsigned int MockActualCallTrace::returnUnsignedIntValueOrDefault(unsigned int)
{
return returnUnsignedIntValue();
}
MockActualCall& MockActualCallTrace::onObject(const void* objectPtr)
{
traceBuffer_ += " onObject:";
traceBuffer_ += StringFrom(objectPtr);
return *this;
}
void MockActualCallTrace::clear()
{
traceBuffer_ = "";
}
const char* MockActualCallTrace::getTraceOutput()
{
return traceBuffer_.asCharString();
}
MockActualCallTrace* MockActualCallTrace::instance_ = NULLPTR;
MockActualCallTrace& MockActualCallTrace::instance()
{
if (instance_ == NULLPTR)
instance_ = new MockActualCallTrace;
return *instance_;
}
void MockActualCallTrace::clearInstance()
{
delete instance_;
instance_ = NULLPTR;
}
MockIgnoredActualCall& MockIgnoredActualCall::instance()
{
static MockIgnoredActualCall call;
return call;
}
| null |
215 | cpp | 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, UtestShell& test)
{
result->print(StringFromFormat("TEST(%s, %s)\n", test.getGroup().asCharString(), test.getName().asCharString()).asCharString());
}
void NormalMemoryReportFormatter::report_test_end(TestResult* result, UtestShell& test)
{
result->print(StringFromFormat("ENDTEST(%s, %s)\n", test.getGroup().asCharString(), test.getName().asCharString()).asCharString());
}
void NormalMemoryReportFormatter::report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t size, char* memory, const char* file, size_t line)
{
result->print(StringFromFormat("\tAllocation using %s of size: %lu pointer: %p at %s:%d\n", allocator->alloc_name(), (unsigned long) size, (void*) memory, file, (int) line).asCharString());
}
void NormalMemoryReportFormatter::report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* memory, const char* file, size_t line)
{
result->print(StringFromFormat("\tDeallocation using %s of pointer: %p at %s:%d\n", allocator->free_name(), (void*) memory, file, (int) line).asCharString());
}
void NormalMemoryReportFormatter::report_testgroup_start(TestResult* result, UtestShell& 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 |
216 | cpp | 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"
MockNamedValueComparatorsAndCopiersRepository* MockNamedValue::defaultRepository_ = NULLPTR;
const double MockNamedValue::defaultDoubleTolerance = 0.005;
void MockNamedValue::setDefaultComparatorsAndCopiersRepository(MockNamedValueComparatorsAndCopiersRepository* repository)
{
defaultRepository_ = repository;
}
MockNamedValueComparatorsAndCopiersRepository* MockNamedValue::getDefaultComparatorsAndCopiersRepository()
{
return defaultRepository_;
}
MockNamedValue::MockNamedValue(const SimpleString& name) : name_(name), type_("int"), size_(0), comparator_(NULLPTR), copier_(NULLPTR)
{
value_.intValue_ = 0;
}
MockNamedValue::~MockNamedValue()
{
}
void MockNamedValue::setValue(bool value)
{
type_ = "bool";
value_.boolValue_ = value;
}
void MockNamedValue::setValue(unsigned int value)
{
type_ = "unsigned int";
value_.unsignedIntValue_ = value;
}
void MockNamedValue::setValue(int value)
{
type_ = "int";
value_.intValue_ = value;
}
void MockNamedValue::setValue(long int value)
{
type_ = "long int";
value_.longIntValue_ = value;
}
void MockNamedValue::setValue(unsigned long int value)
{
type_ = "unsigned long int";
value_.unsignedLongIntValue_ = value;
}
#if CPPUTEST_USE_LONG_LONG
void MockNamedValue::setValue(cpputest_longlong value)
{
type_ = "long long int";
value_.longLongIntValue_ = value;
}
void MockNamedValue::setValue(cpputest_ulonglong value)
{
type_ = "unsigned long long int";
value_.unsignedLongLongIntValue_ = value;
}
#else
void MockNamedValue::setValue(cpputest_longlong)
{
FAIL("Long Long type is not supported");
}
void MockNamedValue::setValue(cpputest_ulonglong)
{
FAIL("Unsigned Long Long type is not supported");
}
#endif
void MockNamedValue::setValue(double value)
{
setValue(value, defaultDoubleTolerance);
}
void MockNamedValue::setValue(double value, double tolerance)
{
type_ = "double";
value_.doubleValue_.value = value;
value_.doubleValue_.tolerance = tolerance;
}
void MockNamedValue::setValue(void* value)
{
type_ = "void*";
value_.pointerValue_ = value;
}
void MockNamedValue::setValue(const void* value)
{
type_ = "const void*";
value_.constPointerValue_ = value;
}
void MockNamedValue::setValue(void (*value)())
{
type_ = "void (*)()";
value_.functionPointerValue_ = value;
}
void MockNamedValue::setValue(const char* value)
{
type_ = "const char*";
value_.stringValue_ = value;
}
void MockNamedValue::setMemoryBuffer(const unsigned char* value, size_t size)
{
type_ = "const unsigned char*";
value_.memoryBufferValue_ = value;
size_ = size;
}
void MockNamedValue::setConstObjectPointer(const SimpleString& type, const void* objectPtr)
{
type_ = type;
value_.constObjectPointerValue_ = objectPtr;
if (defaultRepository_)
{
comparator_ = defaultRepository_->getComparatorForType(type);
copier_ = defaultRepository_->getCopierForType(type);
}
}
void MockNamedValue::setObjectPointer(const SimpleString& type, void* objectPtr)
{
type_ = type;
value_.objectPointerValue_ = objectPtr;
if (defaultRepository_)
{
comparator_ = defaultRepository_->getComparatorForType(type);
copier_ = defaultRepository_->getCopierForType(type);
}
}
void MockNamedValue::setSize(size_t size)
{
size_ = size;
}
void MockNamedValue::setName(const char* name)
{
name_ = name;
}
SimpleString MockNamedValue::getName() const
{
return name_;
}
SimpleString MockNamedValue::getType() const
{
return type_;
}
bool MockNamedValue::getBoolValue() const
{
STRCMP_EQUAL("bool", type_.asCharString());
return value_.boolValue_;
}
unsigned int MockNamedValue::getUnsignedIntValue() const
{
if(type_ == "int" && value_.intValue_ >= 0)
return (unsigned int)value_.intValue_;
else
{
STRCMP_EQUAL("unsigned int", type_.asCharString());
return value_.unsignedIntValue_;
}
}
int MockNamedValue::getIntValue() const
{
STRCMP_EQUAL("int", type_.asCharString());
return value_.intValue_;
}
long int MockNamedValue::getLongIntValue() const
{
if(type_ == "int")
return value_.intValue_;
else if(type_ == "unsigned int")
return (long int)value_.unsignedIntValue_;
else
{
STRCMP_EQUAL("long int", type_.asCharString());
return value_.longIntValue_;
}
}
unsigned long int MockNamedValue::getUnsignedLongIntValue() const
{
if(type_ == "unsigned int")
return value_.unsignedIntValue_;
else if(type_ == "int" && value_.intValue_ >= 0)
return (unsigned long int)value_.intValue_;
else if(type_ == "long int" && value_.longIntValue_ >= 0)
return (unsigned long int)value_.longIntValue_;
else
{
STRCMP_EQUAL("unsigned long int", type_.asCharString());
return value_.unsignedLongIntValue_;
}
}
#if CPPUTEST_USE_LONG_LONG
cpputest_longlong MockNamedValue::getLongLongIntValue() const
{
if(type_ == "int")
return value_.intValue_;
else if(type_ == "unsigned int")
return (long long int)value_.unsignedIntValue_;
else if(type_ == "long int")
return value_.longIntValue_;
else if(type_ == "unsigned long int")
return (long long int)value_.unsignedLongIntValue_;
else
{
STRCMP_EQUAL("long long int", type_.asCharString());
return value_.longLongIntValue_;
}
}
cpputest_ulonglong MockNamedValue::getUnsignedLongLongIntValue() const
{
if(type_ == "unsigned int")
return value_.unsignedIntValue_;
else if(type_ == "int" && value_.intValue_ >= 0)
return (unsigned long long int)value_.intValue_;
else if(type_ == "long int" && value_.longIntValue_ >= 0)
return (unsigned long long int)value_.longIntValue_;
else if(type_ == "unsigned long int")
return value_.unsignedLongIntValue_;
else if(type_ == "long long int" && value_.longLongIntValue_ >= 0)
return (unsigned long long int)value_.longLongIntValue_;
else
{
STRCMP_EQUAL("unsigned long long int", type_.asCharString());
return value_.unsignedLongLongIntValue_;
}
}
#else
cpputest_longlong MockNamedValue::getLongLongIntValue() const
{
FAIL("Long Long type is not supported");
cpputest_longlong ret = {};
return ret;
}
cpputest_ulonglong MockNamedValue::getUnsignedLongLongIntValue() const
{
FAIL("Unsigned Long Long type is not supported");
cpputest_ulonglong ret = {};
return ret;
}
#endif
double MockNamedValue::getDoubleValue() const
{
STRCMP_EQUAL("double", type_.asCharString());
return value_.doubleValue_.value;
}
double MockNamedValue::getDoubleTolerance() const
{
STRCMP_EQUAL("double", type_.asCharString());
return value_.doubleValue_.tolerance;
}
const char* MockNamedValue::getStringValue() const
{
STRCMP_EQUAL("const char*", type_.asCharString());
return value_.stringValue_;
}
void* MockNamedValue::getPointerValue() const
{
STRCMP_EQUAL("void*", type_.asCharString());
return value_.pointerValue_;
}
const void* MockNamedValue::getConstPointerValue() const
{
STRCMP_EQUAL("const void*", type_.asCharString());
return value_.pointerValue_;
}
void (*MockNamedValue::getFunctionPointerValue() const)()
{
STRCMP_EQUAL("void (*)()", type_.asCharString());
return value_.functionPointerValue_;
}
const unsigned char* MockNamedValue::getMemoryBuffer() const
{
STRCMP_EQUAL("const unsigned char*", type_.asCharString());
return value_.memoryBufferValue_;
}
const void* MockNamedValue::getConstObjectPointer() const
{
return value_.constObjectPointerValue_;
}
void* MockNamedValue::getObjectPointer() const
{
return value_.objectPointerValue_;
}
size_t MockNamedValue::getSize() const
{
return size_;
}
MockNamedValueComparator* MockNamedValue::getComparator() const
{
return comparator_;
}
MockNamedValueCopier* MockNamedValue::getCopier() const
{
return copier_;
}
bool MockNamedValue::equals(const MockNamedValue& p) const
{
if((type_ == "long int") && (p.type_ == "int"))
return value_.longIntValue_ == p.value_.intValue_;
else if((type_ == "int") && (p.type_ == "long int"))
return value_.intValue_ == p.value_.longIntValue_;
else if((type_ == "unsigned int") && (p.type_ == "int"))
return (p.value_.intValue_ >= 0) && (value_.unsignedIntValue_ == (unsigned int)p.value_.intValue_);
else if((type_ == "int") && (p.type_ == "unsigned int"))
return (value_.intValue_ >= 0) && ((unsigned int)value_.intValue_ == p.value_.unsignedIntValue_);
else if((type_ == "unsigned long int") && (p.type_ == "int"))
return (p.value_.intValue_ >= 0) && (value_.unsignedLongIntValue_ == (unsigned long)p.value_.intValue_);
else if((type_ == "int") && (p.type_ == "unsigned long int"))
return (value_.intValue_ >= 0) && ((unsigned long)value_.intValue_ == p.value_.unsignedLongIntValue_);
else if((type_ == "unsigned int") && (p.type_ == "long int"))
return (p.value_.longIntValue_ >= 0) && (value_.unsignedIntValue_ == (unsigned long)p.value_.longIntValue_);
else if((type_ == "long int") && (p.type_ == "unsigned int"))
return (value_.longIntValue_ >= 0) && ((unsigned long)value_.longIntValue_ == p.value_.unsignedIntValue_);
else if((type_ == "unsigned int") && (p.type_ == "unsigned long int"))
return value_.unsignedIntValue_ == p.value_.unsignedLongIntValue_;
else if((type_ == "unsigned long int") && (p.type_ == "unsigned int"))
return value_.unsignedLongIntValue_ == p.value_.unsignedIntValue_;
else if((type_ == "long int") && (p.type_ == "unsigned long int"))
return (value_.longIntValue_ >= 0) && ((unsigned long)value_.longIntValue_ == p.value_.unsignedLongIntValue_);
else if((type_ == "unsigned long int") && (p.type_ == "long int"))
return (p.value_.longIntValue_ >= 0) && (value_.unsignedLongIntValue_ == (unsigned long) p.value_.longIntValue_);
#if CPPUTEST_USE_LONG_LONG
else if ((type_ == "long long int") && (p.type_ == "int"))
return value_.longLongIntValue_ == p.value_.intValue_;
else if ((type_ == "int") && (p.type_ == "long long int"))
return value_.intValue_ == p.value_.longLongIntValue_;
else if ((type_ == "long long int") && (p.type_ == "long int"))
return value_.longLongIntValue_ == p.value_.longIntValue_;
else if ((type_ == "long int") && (p.type_ == "long long int"))
return value_.longIntValue_ == p.value_.longLongIntValue_;
else if ((type_ == "long long int") && (p.type_ == "unsigned int"))
return (value_.longLongIntValue_ >= 0) && ((unsigned long long)value_.longLongIntValue_ == p.value_.unsignedIntValue_);
else if ((type_ == "unsigned int") && (p.type_ == "long long int"))
return (p.value_.longLongIntValue_ >= 0) && (value_.unsignedIntValue_ == (unsigned long long)p.value_.longLongIntValue_);
else if ((type_ == "long long int") && (p.type_ == "unsigned long int"))
return (value_.longLongIntValue_ >= 0) && ((unsigned long long)value_.longLongIntValue_ == p.value_.unsignedLongIntValue_);
else if ((type_ == "unsigned long int") && (p.type_ == "long long int"))
return (p.value_.longLongIntValue_ >= 0) && (value_.unsignedLongIntValue_ == (unsigned long long)p.value_.longLongIntValue_);
else if ((type_ == "long long int") && (p.type_ == "unsigned long long int"))
return (value_.longLongIntValue_ >= 0) && ((unsigned long long)value_.longLongIntValue_ == p.value_.unsignedLongLongIntValue_);
else if ((type_ == "unsigned long long int") && (p.type_ == "long long int"))
return (p.value_.longLongIntValue_ >= 0) && (value_.unsignedLongLongIntValue_ == (unsigned long long)p.value_.longLongIntValue_);
else if ((type_ == "unsigned long long int") && (p.type_ == "int"))
return (p.value_.intValue_ >= 0) && (value_.unsignedLongLongIntValue_ == (unsigned long long)p.value_.intValue_);
else if ((type_ == "int") && (p.type_ == "unsigned long long int"))
return (value_.intValue_ >= 0) && ((unsigned long long)value_.intValue_ == p.value_.unsignedLongLongIntValue_);
else if ((type_ == "unsigned long long int") && (p.type_ == "unsigned int"))
return value_.unsignedLongLongIntValue_ == p.value_.unsignedIntValue_;
else if ((type_ == "unsigned int") && (p.type_ == "unsigned long long int"))
return value_.unsignedIntValue_ == p.value_.unsignedLongLongIntValue_;
else if ((type_ == "unsigned long long int") && (p.type_ == "long int"))
return (p.value_.longIntValue_ >= 0) && (value_.unsignedLongLongIntValue_ == (unsigned long long)p.value_.longIntValue_);
else if ((type_ == "long int") && (p.type_ == "unsigned long long int"))
return (value_.longIntValue_ >= 0) && ((unsigned long long)value_.longIntValue_ == p.value_.unsignedLongLongIntValue_);
else if ((type_ == "unsigned long long int") && (p.type_ == "unsigned long int"))
return value_.unsignedLongLongIntValue_ == p.value_.unsignedLongIntValue_;
else if ((type_ == "unsigned long int") && (p.type_ == "unsigned long long int"))
return value_.unsignedLongIntValue_ == p.value_.unsignedLongLongIntValue_;
#endif
if (type_ != p.type_) return false;
if (type_ == "bool")
return value_.boolValue_ == p.value_.boolValue_;
else if (type_ == "int")
return value_.intValue_ == p.value_.intValue_;
else if (type_ == "unsigned int")
return value_.unsignedIntValue_ == p.value_.unsignedIntValue_;
else if (type_ == "long int")
return value_.longIntValue_ == p.value_.longIntValue_;
else if (type_ == "unsigned long int")
return value_.unsignedLongIntValue_ == p.value_.unsignedLongIntValue_;
#if CPPUTEST_USE_LONG_LONG
else if (type_ == "long long int")
return value_.longLongIntValue_ == p.value_.longLongIntValue_;
else if (type_ == "unsigned long long int")
return value_.unsignedLongLongIntValue_ == p.value_.unsignedLongLongIntValue_;
#endif
else if (type_ == "const char*")
return SimpleString(value_.stringValue_) == SimpleString(p.value_.stringValue_);
else if (type_ == "void*")
return value_.pointerValue_ == p.value_.pointerValue_;
else if (type_ == "const void*")
return value_.constPointerValue_ == p.value_.constPointerValue_;
else if (type_ == "void (*)()")
return value_.functionPointerValue_ == p.value_.functionPointerValue_;
else if (type_ == "double")
return (doubles_equal(value_.doubleValue_.value, p.value_.doubleValue_.value, value_.doubleValue_.tolerance));
else if (type_ == "const unsigned char*")
{
if (size_ != p.size_) {
return false;
}
return SimpleString::MemCmp(value_.memoryBufferValue_, p.value_.memoryBufferValue_, size_) == 0;
}
if (comparator_)
return comparator_->isEqual(value_.constObjectPointerValue_, p.value_.constObjectPointerValue_);
return false;
}
bool MockNamedValue::compatibleForCopying(const MockNamedValue& p) const
{
if (type_ == p.type_) return true;
if ((type_ == "const void*") && (p.type_ == "void*"))
return true;
return false;
}
SimpleString MockNamedValue::toString() const
{
if (type_ == "bool")
return StringFrom(value_.boolValue_);
else if (type_ == "int")
return StringFrom(value_.intValue_) + " " + BracketsFormattedHexStringFrom(value_.intValue_);
else if (type_ == "unsigned int")
return StringFrom(value_.unsignedIntValue_) + " " + BracketsFormattedHexStringFrom(value_.unsignedIntValue_);
else if (type_ == "long int")
return StringFrom(value_.longIntValue_) + " " + BracketsFormattedHexStringFrom(value_.longIntValue_);
else if (type_ == "unsigned long int")
return StringFrom(value_.unsignedLongIntValue_) + " " + BracketsFormattedHexStringFrom(value_.unsignedLongIntValue_);
#if CPPUTEST_USE_LONG_LONG
else if (type_ == "long long int")
return StringFrom(value_.longLongIntValue_) + " " + BracketsFormattedHexStringFrom(value_.longLongIntValue_);
else if (type_ == "unsigned long long int")
return StringFrom(value_.unsignedLongLongIntValue_) + " " + BracketsFormattedHexStringFrom(value_.unsignedLongLongIntValue_);
#endif
else if (type_ == "const char*")
return value_.stringValue_;
else if (type_ == "void*")
return StringFrom(value_.pointerValue_);
else if (type_ == "void (*)()")
return StringFrom(value_.functionPointerValue_);
else if (type_ == "const void*")
return StringFrom(value_.constPointerValue_);
else if (type_ == "double")
return StringFrom(value_.doubleValue_.value);
else if (type_ == "const unsigned char*")
return StringFromBinaryWithSizeOrNull(value_.memoryBufferValue_, size_);
if (comparator_)
return comparator_->valueToString(value_.constObjectPointerValue_);
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_(NULLPTR)
{
}
SimpleString MockNamedValueListNode::getName() const
{
return data_->getName();
}
SimpleString MockNamedValueListNode::getType() const
{
return data_->getType();
}
MockNamedValueList::MockNamedValueList() : head_(NULLPTR)
{
}
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_ == NULLPTR)
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 NULLPTR;
}
MockNamedValueListNode* MockNamedValueList::begin()
{
return head_;
}
struct MockNamedValueComparatorsAndCopiersRepositoryNode
{
MockNamedValueComparatorsAndCopiersRepositoryNode(const SimpleString& name, MockNamedValueComparator* comparator, MockNamedValueComparatorsAndCopiersRepositoryNode* next)
: name_(name), comparator_(comparator), copier_(NULLPTR), next_(next) {}
MockNamedValueComparatorsAndCopiersRepositoryNode(const SimpleString& name, MockNamedValueCopier* copier, MockNamedValueComparatorsAndCopiersRepositoryNode* next)
: name_(name), comparator_(NULLPTR), copier_(copier), next_(next) {}
MockNamedValueComparatorsAndCopiersRepositoryNode(const SimpleString& name, MockNamedValueComparator* comparator, MockNamedValueCopier* copier, MockNamedValueComparatorsAndCopiersRepositoryNode* next)
: name_(name), comparator_(comparator), copier_(copier), next_(next) {}
SimpleString name_;
MockNamedValueComparator* comparator_;
MockNamedValueCopier* copier_;
MockNamedValueComparatorsAndCopiersRepositoryNode* next_;
};
MockNamedValueComparatorsAndCopiersRepository::MockNamedValueComparatorsAndCopiersRepository() : head_(NULLPTR)
{
}
MockNamedValueComparatorsAndCopiersRepository::~MockNamedValueComparatorsAndCopiersRepository()
{
clear();
}
void MockNamedValueComparatorsAndCopiersRepository::clear()
{
while (head_) {
MockNamedValueComparatorsAndCopiersRepositoryNode* next = head_->next_;
delete head_;
head_ = next;
}
}
void MockNamedValueComparatorsAndCopiersRepository::installComparator(const SimpleString& name, MockNamedValueComparator& comparator)
{
head_ = new MockNamedValueComparatorsAndCopiersRepositoryNode(name, &comparator, head_);
}
void MockNamedValueComparatorsAndCopiersRepository::installCopier(const SimpleString& name, MockNamedValueCopier& copier)
{
head_ = new MockNamedValueComparatorsAndCopiersRepositoryNode(name, &copier, head_);
}
MockNamedValueComparator* MockNamedValueComparatorsAndCopiersRepository::getComparatorForType(const SimpleString& name)
{
for (MockNamedValueComparatorsAndCopiersRepositoryNode* p = head_; p; p = p->next_)
if (p->name_ == name && p->comparator_) return p->comparator_;
return NULLPTR;
}
MockNamedValueCopier* MockNamedValueComparatorsAndCopiersRepository::getCopierForType(const SimpleString& name)
{
for (MockNamedValueComparatorsAndCopiersRepositoryNode* p = head_; p; p = p->next_)
if (p->name_ == name && p->copier_) return p->copier_;
return NULLPTR;
}
void MockNamedValueComparatorsAndCopiersRepository::installComparatorsAndCopiers(const MockNamedValueComparatorsAndCopiersRepository& repository)
{
for (MockNamedValueComparatorsAndCopiersRepositoryNode* p = repository.head_; p; p = p->next_)
head_ = new MockNamedValueComparatorsAndCopiersRepositoryNode(p->name_, p->comparator_, p->copier_, head_);
}
| null |
217 | cpp | 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 |
218 | cpp | 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"
static jmp_buf test_exit_jmp_buf[10];
static int jmp_buf_index = 0;
int PlatformSpecificSetJmp(void (*function) (void* data), void* data)
{
if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {
jmp_buf_index++;
function(data);
jmp_buf_index--;
return 1;
}
return 0;
}
void PlatformSpecificLongJmp()
{
jmp_buf_index--;
longjmp(test_exit_jmp_buf[jmp_buf_index], 1);
}
void PlatformSpecificRestoreJumpBuffer()
{
jmp_buf_index--;
}
void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)
{
printf("-p doesn't work on this platform as it is not implemented. Running inside the process\b");
shell->runOneTest(plugin, *result);
}
static unsigned long TimeInMillisImplementation() {
struct timeval tv;
struct timezone tz;
::gettimeofday(&tv, &tz);
return ((unsigned long)tv.tv_sec * 1000) + ((unsigned long)tv.tv_usec / 1000);
}
unsigned long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation;
TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()
{
return TestOutput::eclipse;
}
static SimpleString TimeStringImplementation() {
time_t tm = time(NULL);
return ctime(&tm);
}
SimpleString GetPlatformSpecificTimeString() = TimeStringImplementation;
int PlatformSpecificVSNprintf(char* str, size_t size, const char* format, va_list args) {
return vsnprintf(str, size, format, args);
}
void PlatformSpecificFlush() {
fflush(stdout);
}
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 PlatformSpecificStdOut = stdout;
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);
}
extern "C" {
static int IsNanImplementation(double d)
{
return isnan(d);
}
static int IsInfImplementation(double d)
{
return isinf(d);
}
int (*PlatformSpecificIsNan)(double) = IsNanImplementation;
int (*PlatformSpecificIsInf)(double) = IsInfImplementation;
}
static PlatformSpecificMutex DummyMutexCreate(void)
{
FAIL("PlatformSpecificMutexCreate is not implemented");
return 0;
}
static void DummyMutexLock(PlatformSpecificMutex mtx)
{
FAIL("PlatformSpecificMutexLock is not implemented");
}
static void DummyMutexUnlock(PlatformSpecificMutex mtx)
{
FAIL("PlatformSpecificMutexUnlock is not implemented");
}
static void DummyMutexDestroy(PlatformSpecificMutex mtx)
{
FAIL("PlatformSpecificMutexDestroy is not implemented");
}
PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = DummyMutexCreate;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy;
void (*PlatformSpecificAbort)(void) = abort;
| null |
219 | cpp | cpputest | UtestPlatform.cpp | src/Platforms/Keil/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
#undef strdup
#undef strndup
#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 unsigned long TimeInMillisImplementation()
{
clock_t t = clock();
t = t * 10;
return (unsigned long)t;
}
unsigned 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 PlatformSpecificStdOut = stdout;
PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation;
void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation;
void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation;
void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation;
void* (*PlatformSpecificMalloc)(size_t) = 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;
void (*PlatformSpecificAbort)(void) = abort;
}
| null |
220 | cpp | cpputest | UtestPlatform.cpp | src/Platforms/C2000/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.
*/
/* Un-comment to use buffer instead of std out */
// #define USE_BUFFER_OUTPUT 1
#include <cstdlib>
#include "CppUTest/TestHarness.h"
#undef malloc
#undef free
#undef calloc
#undef realloc
#undef strdup
#undef strndup
#define far // eliminate "meaningless type qualifier" warning
extern "C" {
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <setjmp.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
}
#undef far
#include "CppUTest/PlatformSpecificFunctions.h"
static jmp_buf test_exit_jmp_buf[10];
static int jmp_buf_index = 0;
#if USE_BUFFER_OUTPUT
// Buffer for crude output routine
#define BUFFER_SIZE 4096
static char buffer [BUFFER_SIZE]; /* "never used" warning is OK */
static int idx = 0;
#endif
TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()
{
return TestOutput::eclipse;
}
static void C2000RunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)
{
result->addFailure(TestFailure(shell, "-p doesn't work on this platform, as it is lacking fork.\b"));
}
void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell*, TestPlugin*, TestResult*) =
C2000RunTestInASeperateProcess;
extern "C" {
static int C2000SetJmp(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 C2000LongJmp()
{
jmp_buf_index--;
longjmp(test_exit_jmp_buf[jmp_buf_index], 1);
}
static void C2000RestoreJumpBuffer()
{
jmp_buf_index--;
}
int (*PlatformSpecificSetJmp)(void (*function) (void*), void*) = C2000SetJmp;
void (*PlatformSpecificLongJmp)(void) = C2000LongJmp;
void (*PlatformSpecificRestoreJumpBuffer)(void) = C2000RestoreJumpBuffer;
static unsigned long C2000TimeInMillis()
{
/* The TI c2000 platform does not have Posix support and thus lacks struct timespec.
* Also, clock() always returns 0 in the simulator. Hence we work with struct tm.tm_hour
* This has two consequences:
* (1) We need to sum up the part in order to get an "elapsed since" time value,
* rather than just using tm_sec.
* (2) There is a possibility of overflow, since we stop at the hour
* (3) Resolution is 1 s, even though we return ms.
*/
time_t t = time((time_t*)0);
struct tm * ptm = gmtime(&t);
unsigned long result = (unsigned long)
((ptm->tm_sec + ptm->tm_min * (time_t)60 + ptm->tm_hour * (time_t)3600) * (time_t)1000);
return result;
}
static const char* TimeStringImplementation()
{
time_t tm = time(NULL);
return ctime(&tm);
}
unsigned long (*GetPlatformSpecificTimeInMillis)() = C2000TimeInMillis;
const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation;
extern int vsnprintf(char*, size_t, const char*, va_list); // not std::vsnprintf()
extern int (*PlatformSpecificVSNprintf)(char *, size_t, const char*, va_list) = vsnprintf;
PlatformSpecificFile C2000FOpen(const char* filename, const char* flag)
{
return fopen(filename, flag);
}
static void C2000FPuts(const char* str, PlatformSpecificFile file)
{
#if USE_BUFFER_OUTPUT
if (file == PlatformSpecificStdOut) {
while (*str && (idx < BUFFER_SIZE)) {
buf[idx++] = *str++;
}
}
else
#endif
{
fputs(str, (FILE*)file);
}
}
static void C2000FClose(PlatformSpecificFile file)
{
fclose((FILE*)file);
}
PlatformSpecificFile PlatformSpecificStdOut = stdout;
PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = C2000FOpen;
void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = C2000FPuts;
void (*PlatformSpecificFClose)(PlatformSpecificFile file) = C2000FClose;
static void CL2000Flush()
{
fflush(stdout);
}
extern void (*PlatformSpecificFlush)(void) = CL2000Flush;
static void* C2000Malloc(size_t size)
{
return (void*)malloc((unsigned long)size);
}
static void* C2000Realloc (void* memory, size_t size)
{
return (void*)realloc(memory, (unsigned long)size);
}
static void C2000Free(void* memory)
{
free(memory);
}
static void* C2000MemCpy(void* s1, const void* s2, size_t size)
{
return (void*)memcpy(s1, s2, size);
}
static void* C2000Memset(void* mem, int c, size_t size)
{
register unsigned long i = size;
register long p = (long) mem;
while (i--) *__farptr_to_word(p++) = c;
return mem;
}
void* (*PlatformSpecificMalloc)(size_t size) = C2000Malloc;
void* (*PlatformSpecificRealloc)(void* memory, size_t size) = C2000Realloc;
void (*PlatformSpecificFree)(void* memory) = C2000Free;
void* (*PlatformSpecificMemCpy)(void* s1, const void* s2, size_t size) = C2000MemCpy;
void* (*PlatformSpecificMemset)(void* mem, int c, size_t size) = C2000Memset;
/*
double PlatformSpecificFabs(double d)
{
return fabs(d);
}
*/
double (*PlatformSpecificFabs)(double) = fabs;
static int IsNanImplementation(double d)
{
return 0;
}
static int IsInfImplementation(double d)
{
return 0;
}
int (*PlatformSpecificIsNan)(double d) = IsNanImplementation;
int (*PlatformSpecificIsInf)(double d) = IsInfImplementation;
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 (*PlatformSpecificSrand)(unsigned int) = srand;
int (*PlatformSpecificRand)(void) = rand;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy;
void (*PlatformSpecificAbort)(void) = abort;
}
| null |
221 | cpp | cpputest | UtestPlatform.cpp | src/Platforms/Dos/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.
*/
/* Un-comment to use buffer instead of std out */
// #define USE_BUFFER_OUTPUT 1
#include <cstdlib>
#include "CppUTest/TestHarness.h"
#undef malloc
#undef free
#undef calloc
#undef realloc
#undef strdup
#undef strndup
#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>
#undef far
#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 DosSetJmp(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 DosLongJmp()
{
jmp_buf_index--;
longjmp(test_exit_jmp_buf[jmp_buf_index], 1);
}
static void DosRestoreJumpBuffer()
{
jmp_buf_index--;
}
int (*PlatformSpecificSetJmp)(void (*function) (void*), void*) = DosSetJmp;
void (*PlatformSpecificLongJmp)(void) = DosLongJmp;
void (*PlatformSpecificRestoreJumpBuffer)(void) = DosRestoreJumpBuffer;
static unsigned long DosTimeInMillis()
{
return (unsigned long)(clock() * 1000 / CLOCKS_PER_SEC);
}
static const char* DosTimeString()
{
time_t tm = time(NULL);
return ctime(&tm);
}
static int DosVSNprintf(char* str, size_t size, const char* format, va_list args) {
return vsnprintf(str, size, format, args);
}
unsigned long (*GetPlatformSpecificTimeInMillis)() = DosTimeInMillis;
const char* (*GetPlatformSpecificTimeString)() = DosTimeString;
int (*PlatformSpecificVSNprintf)(char *, size_t, const char*, va_list) = DosVSNprintf;
PlatformSpecificFile DosFOpen(const char* filename, const char* flag)
{
return fopen(filename, flag);
}
static void DosFPuts(const char* str, PlatformSpecificFile file)
{
fputs(str, (FILE*)file);
}
static void DosFClose(PlatformSpecificFile file)
{
fclose((FILE*)file);
}
PlatformSpecificFile PlatformSpecificStdOut = stdout;
PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = DosFOpen;
void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = DosFPuts;
void (*PlatformSpecificFClose)(PlatformSpecificFile file) = DosFClose;
static void DosFlush()
{
fflush(stdout);
}
extern void (*PlatformSpecificFlush)(void) = DosFlush;
static void* DosMalloc(size_t size)
{
return malloc(size);
}
static void* DosRealloc (void* memory, size_t size)
{
return realloc(memory, size);
}
static void DosFree(void* memory)
{
free(memory);
}
static void* DosMemCpy(void* s1, const void* s2, size_t size)
{
return memcpy(s1, s2, size);
}
static void* DosMemset(void* mem, int c, size_t size)
{
return memset(mem, c, size);
}
void* (*PlatformSpecificMalloc)(size_t size) = DosMalloc;
void* (*PlatformSpecificRealloc)(void* memory, size_t size) = DosRealloc;
void (*PlatformSpecificFree)(void* memory) = DosFree;
void* (*PlatformSpecificMemCpy)(void* s1, const void* s2, size_t size) = DosMemCpy;
void* (*PlatformSpecificMemset)(void* mem, int c, size_t size) = DosMemset;
static void DosSrand(unsigned int seed)
{
srand(seed);
}
static int DosRand()
{
return rand();
}
static double DosFabs(double d)
{
return fabs(d);
}
static int DosIsNan(double d)
{
return isnan(d);
}
static int DosIsInf(double d)
{
return isinf(d);
}
void (*PlatformSpecificSrand)(unsigned int) = DosSrand;
int (*PlatformSpecificRand)(void) = DosRand;
double (*PlatformSpecificFabs)(double) = DosFabs;
int (*PlatformSpecificIsNan)(double d) = DosIsNan;
int (*PlatformSpecificIsInf)(double d) = DosIsInf;
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;
static void DosAbort()
{
abort();
}
void (*PlatformSpecificAbort)(void) = DosAbort;
}
| null |
222 | cpp | cpputest | UtestPlatform.cpp | src/Platforms/armcc/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 <ctype.h>
#include <math.h>
#include "CppUTest/TestHarness.h"
#undef malloc
#undef calloc
#undef realloc
#undef free
#undef strdup
#undef strndup
#define far // eliminate "meaningless type qualifier" warning
#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 DummyPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, 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* shell, TestPlugin* plugin, TestResult* result) =
DummyPlatformSpecificRunTestInASeperateProcess;
int (*PlatformSpecificFork)(void) = 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 (*)(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 unsigned long TimeInMillisImplementation()
{
clock_t t = clock();
return (unsigned long)t;
}
///////////// Time in String
static const char* DummyTimeStringImplementation()
{
time_t tm = 0;
return ctime(&tm);
}
unsigned long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation;
const char* (*GetPlatformSpecificTimeString)() = DummyTimeStringImplementation;
int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list args) = vsnprintf;
static PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag)
{
return fopen(filename, flag);
}
static void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file)
{
fputs(str, (FILE*)file);
}
static void PlatformSpecificFCloseImplementation(PlatformSpecificFile file)
{
fclose((FILE*)file);
}
static void PlatformSpecificFlushImplementation()
{
fflush(stdout);
}
PlatformSpecificFile PlatformSpecificStdOut = stdout;
PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation;
void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation;
void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation;
void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation;
void* (*PlatformSpecificMalloc)(size_t size) = malloc;
void* (*PlatformSpecificRealloc)(void*, size_t) = realloc;
void (*PlatformSpecificFree)(void* memory) = free;
void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = memcpy;
void* (*PlatformSpecificMemset)(void*, int, size_t) = memset;
void (*PlatformSpecificSrand)(unsigned int) = srand;
int (*PlatformSpecificRand)(void) = rand;
static int IsNanImplementation(double d)
{
return isnan(d);
}
static int IsInfImplementation(double d)
{
return isinf(d);
}
static int AtExitImplementation(void(*func)(void))
{
return atexit(func);
}
double (*PlatformSpecificFabs)(double) = fabs;
int (*PlatformSpecificIsNan)(double) = IsNanImplementation;
int (*PlatformSpecificIsInf)(double) = IsInfImplementation;
int (*PlatformSpecificAtExit)(void(*func)(void)) = AtExitImplementation;
static PlatformSpecificMutex DummyMutexCreate(void)
{
return 0;
}
static void DummyMutexLock(PlatformSpecificMutex)
{
}
static void DummyMutexUnlock(PlatformSpecificMutex)
{
}
static void DummyMutexDestroy(PlatformSpecificMutex)
{
}
PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = DummyMutexCreate;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy;
void (*PlatformSpecificAbort)(void) = abort;
}
| null |
223 | cpp | 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
#undef strdup
#undef strndup
#ifdef CPPUTEST_HAVE_GETTIMEOFDAY
#include <sys/time.h>
#endif
#if defined(CPPUTEST_HAVE_FORK) && defined(CPPUTEST_HAVE_WAITPID)
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#endif
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <setjmp.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <signal.h>
#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK
#include <pthread.h>
#endif
#include "CppUTest/PlatformSpecificFunctions.h"
static jmp_buf test_exit_jmp_buf[10];
static int jmp_buf_index = 0;
// There is a possibility that a compiler provides fork but not waitpid.
#if !defined(CPPUTEST_HAVE_FORK) || !defined(CPPUTEST_HAVE_WAITPID)
static void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)
{
result->addFailure(TestFailure(shell, "-p doesn't work on this platform, as it is lacking fork.\b"));
}
static int PlatformSpecificForkImplementation(void)
{
return 0;
}
static int PlatformSpecificWaitPidImplementation(int, int*, int)
{
return 0;
}
#else
static void SetTestFailureByStatusCode(UtestShell* shell, TestResult* result, int status)
{
if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
result->addFailure(TestFailure(shell, "Failed in separate process"));
} else if (WIFSIGNALED(status)) {
SimpleString message("Failed in separate process - killed by signal ");
message += StringFrom(WTERMSIG(status));
result->addFailure(TestFailure(shell, message));
} else if (WIFSTOPPED(status)) {
result->addFailure(TestFailure(shell, "Stopped in separate process - continuing"));
}
}
static void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)
{
const pid_t syscallError = -1;
pid_t cpid;
pid_t w;
int status = 0;
cpid = PlatformSpecificFork();
if (cpid == syscallError) {
result->addFailure(TestFailure(shell, "Call to fork() failed"));
return;
}
if (cpid == 0) { /* Code executed by child */
const size_t initialFailureCount = result->getFailureCount(); // LCOV_EXCL_LINE
shell->runOneTestInCurrentProcess(plugin, *result); // LCOV_EXCL_LINE
_exit(initialFailureCount < result->getFailureCount()); // LCOV_EXCL_LINE
} else { /* Code executed by parent */
size_t amountOfRetries = 0;
do {
w = PlatformSpecificWaitPid(cpid, &status, WUNTRACED);
if (w == syscallError) {
// OS X debugger causes EINTR
if (EINTR == errno) {
if (amountOfRetries > 30) {
result->addFailure(TestFailure(shell, "Call to waitpid() failed with EINTR. Tried 30 times and giving up! Sometimes happens in debugger"));
return;
}
amountOfRetries++;
}
else {
result->addFailure(TestFailure(shell, "Call to waitpid() failed"));
return;
}
} else {
SetTestFailureByStatusCode(shell, result, status);
if (WIFSTOPPED(status)) kill(w, SIGCONT);
}
} while ((w == syscallError) || (!WIFEXITED(status) && !WIFSIGNALED(status)));
}
}
static pid_t PlatformSpecificForkImplementation(void)
{
return fork();
}
static pid_t PlatformSpecificWaitPidImplementation(int pid, int* status, int options)
{
return waitpid(pid, status, options);
}
#endif
TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()
{
return TestOutput::eclipse;
}
void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) =
GccPlatformSpecificRunTestInASeperateProcess;
int (*PlatformSpecificFork)(void) = PlatformSpecificForkImplementation;
int (*PlatformSpecificWaitPid)(int, int*, int) = PlatformSpecificWaitPidImplementation;
extern "C" {
static int PlatformSpecificSetJmpImplementation(void (*function) (void* data), void* data)
{
if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {
jmp_buf_index++;
function(data);
jmp_buf_index--;
return 1;
}
return 0;
}
/*
* MacOSX clang 3.0 doesn't seem to recognize longjmp and thus complains about CPPUTEST_NORETURN.
* The later clang compilers complain when it isn't there. So only way is to check the clang compiler here :(
*/
#ifdef __clang__
#if !((__clang_major__ == 3) && (__clang_minor__ == 0))
CPPUTEST_NORETURN
#endif
#endif
static void PlatformSpecificLongJmpImplementation()
{
jmp_buf_index--;
longjmp(test_exit_jmp_buf[jmp_buf_index], 1);
}
static void PlatformSpecificRestoreJumpBufferImplementation()
{
jmp_buf_index--;
}
void (*PlatformSpecificLongJmp)() = PlatformSpecificLongJmpImplementation;
int (*PlatformSpecificSetJmp)(void (*)(void*), void*) = PlatformSpecificSetJmpImplementation;
void (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferImplementation;
///////////// Time in millis
static unsigned long TimeInMillisImplementation()
{
#ifdef CPPUTEST_HAVE_GETTIMEOFDAY
struct timeval tv;
gettimeofday(&tv, NULL);
return (((unsigned long)tv.tv_sec * 1000) + ((unsigned long)tv.tv_usec / 1000));
#else
return 0;
#endif
}
static const char* TimeStringImplementation()
{
time_t theTime = time(NULLPTR);
static char dateTime[80];
#ifdef STDC_WANT_SECURE_LIB
static struct tm lastlocaltime;
localtime_s(&lastlocaltime, &theTime);
struct tm *tmp = &lastlocaltime;
#else
struct tm *tmp = localtime(&theTime);
#endif
strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp);
return dateTime;
}
unsigned long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation;
const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation;
/* Wish we could add an attribute to the format for discovering mis-use... but the __attribute__(format) seems to not work on va_list */
#ifdef __clang__
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif
#ifdef __clang__
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#endif
int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = vsnprintf;
static PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag)
{
#ifdef STDC_WANT_SECURE_LIB
FILE* file;
fopen_s(&file, filename, flag);
return file;
#else
return fopen(filename, flag);
#endif
}
static void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file)
{
fputs(str, (FILE*)file);
}
static void PlatformSpecificFCloseImplementation(PlatformSpecificFile file)
{
fclose((FILE*)file);
}
static void PlatformSpecificFlushImplementation()
{
fflush(stdout);
}
PlatformSpecificFile PlatformSpecificStdOut = stdout;
PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation;
void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation;
void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation;
void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation;
void* (*PlatformSpecificMalloc)(size_t size) = malloc;
void* (*PlatformSpecificRealloc)(void*, size_t) = realloc;
void (*PlatformSpecificFree)(void* memory) = free;
void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = memcpy;
void* (*PlatformSpecificMemset)(void*, int, size_t) = memset;
/* GCC 4.9.x introduces -Wfloat-conversion, which causes a warning / error
* in GCC's own (macro) implementation of isnan() and isinf().
*/
#if defined(__GNUC__) && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ > 8))
#pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
static int IsNanImplementation(double d)
{
return isnan(d);
}
static int IsInfImplementation(double d)
{
return isinf(d);
}
double (*PlatformSpecificFabs)(double) = fabs;
void (*PlatformSpecificSrand)(unsigned int) = srand;
int (*PlatformSpecificRand)(void) = rand;
int (*PlatformSpecificIsNan)(double) = IsNanImplementation;
int (*PlatformSpecificIsInf)(double) = IsInfImplementation;
int (*PlatformSpecificAtExit)(void(*func)(void)) = atexit; /// this was undefined before
static PlatformSpecificMutex PThreadMutexCreate(void)
{
#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK
pthread_mutex_t *mutex = new pthread_mutex_t;
pthread_mutex_init(mutex, NULLPTR);
return (PlatformSpecificMutex)mutex;
#else
return NULLPTR;
#endif
}
#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK
static void PThreadMutexLock(PlatformSpecificMutex mtx)
{
pthread_mutex_lock((pthread_mutex_t *)mtx);
}
#else
static void PThreadMutexLock(PlatformSpecificMutex)
{
}
#endif
#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK
static void PThreadMutexUnlock(PlatformSpecificMutex mtx)
{
pthread_mutex_unlock((pthread_mutex_t *)mtx);
}
#else
static void PThreadMutexUnlock(PlatformSpecificMutex)
{
}
#endif
#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK
static void PThreadMutexDestroy(PlatformSpecificMutex mtx)
{
pthread_mutex_t *mutex = (pthread_mutex_t *)mtx;
pthread_mutex_destroy(mutex);
delete mutex;
}
#else
static void PThreadMutexDestroy(PlatformSpecificMutex)
{
}
#endif
PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = PThreadMutexCreate;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = PThreadMutexLock;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = PThreadMutexUnlock;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = PThreadMutexDestroy;
void (*PlatformSpecificAbort)(void) = abort;
}
| null |
224 | cpp | cpputest | UtestPlatform.cpp | src/Platforms/VisualCpp/UtestPlatform.cpp | null | #include <stdlib.h>
#include "CppUTest/TestHarness.h"
#undef malloc
#undef free
#undef calloc
#undef realloc
#undef strdup
#undef strndup
#include <stdio.h>
#include <stdarg.h>
#include <setjmp.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <time.h>
#include "CppUTest/PlatformSpecificFunctions.h"
#include <Windows.h>
#include <mmsystem.h>
#include <setjmp.h>
#ifdef STDC_WANT_SECURE_LIB
#define MAYBE_SECURE_FOPEN(fp, filename, flag) fopen_s((fp), (filename), (flag))
#define MAYBE_SECURE_VSNPRINTF(str, size, trunc, format, args) _vsnprintf_s((str), (size), (trunc), (format), (args))
#define MAYBE_SECURE_LOCALTIME(_tm, timer) localtime_s((_tm), (timer))
#else
#define MAYBE_SECURE_FOPEN(fp, filename, flag) *(fp) = fopen((filename), (flag))
#define MAYBE_SECURE_VSNPRINTF(str, size, trunc, format, args) _vsnprintf((str), (size), (format), (args))
#define MAYBE_SECURE_LOCALTIME(_tm, timer) memcpy(_tm, localtime(timer), sizeof(tm));
#endif
static jmp_buf test_exit_jmp_buf[10];
static int jmp_buf_index = 0;
static int VisualCppSetJmp(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;
}
CPPUTEST_NORETURN static void VisualCppLongJmp()
{
jmp_buf_index--;
longjmp(test_exit_jmp_buf[jmp_buf_index], 1);
}
static void VisualCppRestoreJumpBuffer()
{
jmp_buf_index--;
}
int (*PlatformSpecificSetJmp)(void (*function) (void*), void* data) = VisualCppSetJmp;
void (*PlatformSpecificLongJmp)(void) = VisualCppLongJmp;
void (*PlatformSpecificRestoreJumpBuffer)(void) = VisualCppRestoreJumpBuffer;
static void VisualCppRunTestInASeperateProcess(UtestShell* shell, TestPlugin* /* plugin */, TestResult* result)
{
result->addFailure(TestFailure(shell, "-p doesn't work on this platform, as it is lacking fork.\b"));
}
void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) =
VisualCppRunTestInASeperateProcess;
TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()
{
return TestOutput::visualStudio;
}
///////////// Time in millis
static unsigned long VisualCppTimeInMillis()
{
static LARGE_INTEGER s_frequency;
static const BOOL s_use_qpc = QueryPerformanceFrequency(&s_frequency);
if (s_use_qpc)
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return (unsigned long)((now.QuadPart * 1000) / s_frequency.QuadPart);
}
else
{
#ifdef TIMERR_NOERROR
return (unsigned long)timeGetTime();
#else
#if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || (_WIN32_WINNT < _WIN32_WINNT_VISTA)
return (unsigned long)GetTickCount();
#else
return (unsigned long)GetTickCount64();
#endif
#endif
}
}
unsigned long (*GetPlatformSpecificTimeInMillis)() = VisualCppTimeInMillis;
///////////// Time in String
static const char* VisualCppTimeString()
{
time_t the_time = time(NULLPTR);
struct tm the_local_time;
static char dateTime[80];
MAYBE_SECURE_LOCALTIME(&the_local_time, &the_time);
strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", &the_local_time);
return dateTime;
}
const char* (*GetPlatformSpecificTimeString)() = VisualCppTimeString;
////// taken from gcc
static int VisualCppVSNprintf(char *str, size_t size, const char* format, va_list args)
{
char* buf = NULLPTR;
size_t sizeGuess = size;
int result = MAYBE_SECURE_VSNPRINTF( str, size, _TRUNCATE, format, args);
str[size-1] = 0;
while (result == -1)
{
if (buf)
free(buf);
sizeGuess += 10;
buf = (char*)malloc(sizeGuess);
result = MAYBE_SECURE_VSNPRINTF( buf, sizeGuess, _TRUNCATE, format, args);
}
if (buf)
free(buf);
return result;
}
int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = VisualCppVSNprintf;
static PlatformSpecificFile VisualCppFOpen(const char* filename, const char* flag)
{
FILE* file;
MAYBE_SECURE_FOPEN(&file, filename, flag);
return file;
}
static void VisualCppFPuts(const char* str, PlatformSpecificFile file)
{
fputs(str, (FILE*)file);
}
static void VisualCppFClose(PlatformSpecificFile file)
{
fclose((FILE*)file);
}
PlatformSpecificFile PlatformSpecificStdOut = stdout;
PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = VisualCppFOpen;
void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = VisualCppFPuts;
void (*PlatformSpecificFClose)(PlatformSpecificFile file) = VisualCppFClose;
static void VisualCppFlush()
{
fflush(stdout);
}
void (*PlatformSpecificFlush)(void) = VisualCppFlush;
static void* VisualCppMalloc(size_t size)
{
return malloc(size);
}
static void* VisualCppReAlloc(void* memory, size_t size)
{
return realloc(memory, size);
}
static void VisualCppFree(void* memory)
{
free(memory);
}
void (*PlatformSpecificSrand)(unsigned int) = srand;
int (*PlatformSpecificRand)(void) = rand;
void* (*PlatformSpecificMalloc)(size_t size) = VisualCppMalloc;
void* (*PlatformSpecificRealloc)(void* memory, size_t size) = VisualCppReAlloc;
void (*PlatformSpecificFree)(void* memory) = VisualCppFree;
void* (*PlatformSpecificMemCpy)(void* s1, const void* s2, size_t size) = memcpy;
void* (*PlatformSpecificMemset)(void* mem, int c, size_t size) = memset;
static int IsInfImplementation(double d)
{
return !_finite(d);
}
double (*PlatformSpecificFabs)(double d) = fabs;
extern "C" int (*PlatformSpecificIsNan)(double) = _isnan;
extern "C" int (*PlatformSpecificIsInf)(double) = IsInfImplementation;
int (*PlatformSpecificAtExit)(void(*func)(void)) = atexit;
static PlatformSpecificMutex VisualCppMutexCreate(void)
{
CRITICAL_SECTION *critical_section = new CRITICAL_SECTION;
InitializeCriticalSection(critical_section);
return (PlatformSpecificMutex)critical_section;
}
static void VisualCppMutexLock(PlatformSpecificMutex mutex)
{
EnterCriticalSection((CRITICAL_SECTION*)mutex);
}
static void VisualCppMutexUnlock(PlatformSpecificMutex mutex)
{
LeaveCriticalSection((CRITICAL_SECTION*)mutex);
}
static void VisualCppMutexDestroy(PlatformSpecificMutex mutex)
{
CRITICAL_SECTION *critical_section = (CRITICAL_SECTION*)mutex;
DeleteCriticalSection(critical_section);
delete critical_section;
}
PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = VisualCppMutexCreate;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = VisualCppMutexLock;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = VisualCppMutexUnlock;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = VisualCppMutexDestroy;
void (*PlatformSpecificAbort)(void) = abort;
| null |
225 | cpp | 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
#undef strdup
#undef strndup
#include "CppUTest/PlatformSpecificFunctions.h"
void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell*, TestPlugin*, TestResult*) = NULLPTR;
int (*PlatformSpecificFork)() = NULLPTR;
int (*PlatformSpecificWaitPid)(int, int*, int) = NULLPTR;
TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()
{
return TestOutput::eclipse;
}
void (*PlatformSpecificLongJmp)() = NULLPTR;
int (*PlatformSpecificSetJmp)(void (*)(void*), void*) = NULLPTR;
void (*PlatformSpecificRestoreJumpBuffer)() = NULLPTR;
unsigned long (*GetPlatformSpecificTimeInMillis)() = NULLPTR;
const char* (*GetPlatformSpecificTimeString)() = NULLPTR;
/* IO operations */
PlatformSpecificFile PlatformSpecificStdOut = NULLPTR;
PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = NULLPTR;
void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = NULLPTR;
void (*PlatformSpecificFClose)(PlatformSpecificFile file) = NULLPTR;
void (*PlatformSpecificFlush)(void) = NULLPTR;
int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = NULLPTR;
/* Dynamic Memory operations */
void* (*PlatformSpecificMalloc)(size_t) = NULLPTR;
void* (*PlatformSpecificRealloc)(void*, size_t) = NULLPTR;
void (*PlatformSpecificFree)(void*) = NULLPTR;
void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = NULLPTR;
void* (*PlatformSpecificMemset)(void*, int, size_t) = NULLPTR;
double (*PlatformSpecificFabs)(double) = NULLPTR;
int (*PlatformSpecificIsNan)(double) = NULLPTR;
int (*PlatformSpecificIsInf)(double) = NULLPTR;
int (*PlatformSpecificAtExit)(void(*func)(void)) = NULLPTR;
PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = NULLPTR;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex mtx) = NULLPTR;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex mtx) = NULLPTR;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex mtx) = NULLPTR;
void (*PlatformSpecificSrand)(unsigned int) = NULLPTR;
int (*PlatformSpecificRand)(void) = NULLPTR;
void (*PlatformSpecificAbort)(void) = NULLPTR;
| null |
226 | cpp | cpputest | UtestPlatform.cpp | src/Platforms/Borland/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
#undef strdup
#undef strndup
#ifdef CPPUTEST_HAVE_GETTIMEOFDAY
#include <sys/time.h>
#endif
#if defined(CPPUTEST_HAVE_FORK) && defined(CPPUTEST_HAVE_WAITPID)
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#endif
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <setjmp.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <ctype.h>
#include <signal.h>
#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK
#include <pthread.h>
#endif
#include "CppUTest/PlatformSpecificFunctions.h"
const std::nothrow_t std::nothrow;
static jmp_buf test_exit_jmp_buf[10];
static int jmp_buf_index = 0;
// There is a possibility that a compiler provides fork but not waitpid.
// TODO consider using spawn() and cwait()?
#if !defined(CPPUTEST_HAVE_FORK) || !defined(CPPUTEST_HAVE_WAITPID)
static void BorlandPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)
{
result->addFailure(TestFailure(shell, "-p doesn't work on this platform, as it is lacking fork.\b"));
}
static int PlatformSpecificForkImplementation(void)
{
return 0;
}
static int PlatformSpecificWaitPidImplementation(int, int*, int)
{
return 0;
}
#else
static void SetTestFailureByStatusCode(UtestShell* shell, TestResult* result, int status)
{
if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
result->addFailure(TestFailure(shell, "Failed in separate process"));
} else if (WIFSIGNALED(status)) {
SimpleString message("Failed in separate process - killed by signal ");
message += StringFrom(WTERMSIG(status));
result->addFailure(TestFailure(shell, message));
} else if (WIFSTOPPED(status)) {
result->addFailure(TestFailure(shell, "Stopped in separate process - continuing"));
}
}
static void BorlandPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)
{
const pid_t syscallError = -1;
pid_t cpid;
pid_t w;
int status = 0;
cpid = PlatformSpecificFork();
if (cpid == syscallError) {
result->addFailure(TestFailure(shell, "Call to fork() failed"));
return;
}
if (cpid == 0) { /* Code executed by child */
const size_t initialFailureCount = result->getFailureCount(); // LCOV_EXCL_LINE
shell->runOneTestInCurrentProcess(plugin, *result); // LCOV_EXCL_LINE
_exit(initialFailureCount < result->getFailureCount()); // LCOV_EXCL_LINE
} else { /* Code executed by parent */
size_t amountOfRetries = 0;
do {
w = PlatformSpecificWaitPid(cpid, &status, WUNTRACED);
if (w == syscallError) {
// OS X debugger causes EINTR
if (EINTR == errno) {
if (amountOfRetries > 30) {
result->addFailure(TestFailure(shell, "Call to waitpid() failed with EINTR. Tried 30 times and giving up! Sometimes happens in debugger"));
return;
}
amountOfRetries++;
}
else {
result->addFailure(TestFailure(shell, "Call to waitpid() failed"));
return;
}
} else {
SetTestFailureByStatusCode(shell, result, status);
if (WIFSTOPPED(status)) kill(w, SIGCONT);
}
} while ((w == syscallError) || (!WIFEXITED(status) && !WIFSIGNALED(status)));
}
}
static pid_t PlatformSpecificForkImplementation(void)
{
return fork();
}
static pid_t PlatformSpecificWaitPidImplementation(int pid, int* status, int options)
{
return waitpid(pid, status, options);
}
#endif
TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()
{
return TestOutput::eclipse;
}
void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) =
BorlandPlatformSpecificRunTestInASeperateProcess;
int (*PlatformSpecificFork)(void) = PlatformSpecificForkImplementation;
int (*PlatformSpecificWaitPid)(int, int*, int) = PlatformSpecificWaitPidImplementation;
extern "C" {
static int PlatformSpecificSetJmpImplementation(void (*function) (void* data), void* data)
{
if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {
jmp_buf_index++;
function(data);
jmp_buf_index--;
return 1;
}
return 0;
}
static void PlatformSpecificLongJmpImplementation()
{
jmp_buf_index--;
longjmp(test_exit_jmp_buf[jmp_buf_index], 1);
}
static void PlatformSpecificRestoreJumpBufferImplementation()
{
jmp_buf_index--;
}
void (*PlatformSpecificLongJmp)() = PlatformSpecificLongJmpImplementation;
int (*PlatformSpecificSetJmp)(void (*)(void*), void*) = PlatformSpecificSetJmpImplementation;
void (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferImplementation;
///////////// Time in millis
static unsigned long TimeInMillisImplementation()
{
#ifdef CPPUTEST_HAVE_GETTIMEOFDAY
struct timeval tv;
gettimeofday(&tv, NULL);
return ((unsigned long)tv.tv_sec * 1000) + ((unsigned long)tv.tv_usec / 1000));
#else
return 0;
#endif
}
static const char* TimeStringImplementation()
{
time_t theTime = time(NULLPTR);
static char dateTime[80];
struct tm *tmp = localtime(&theTime);
strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp);
return dateTime;
}
unsigned long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation;
const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation;
static int BorlandVSNprintf(char *str, size_t size, const char* format, va_list args)
{
int result = vsnprintf( str, size, format, args);
str[size-1] = 0;
return result;
}
int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = BorlandVSNprintf;
static PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag)
{
return fopen(filename, flag);
}
static void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file)
{
fputs(str, (FILE*)file);
}
static void PlatformSpecificFCloseImplementation(PlatformSpecificFile file)
{
fclose((FILE*)file);
}
static void PlatformSpecificFlushImplementation()
{
fflush(stdout);
}
PlatformSpecificFile PlatformSpecificStdOut = stdout;
PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation;
void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation;
void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation;
void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation;
void* (*PlatformSpecificMalloc)(size_t size) = malloc;
void* (*PlatformSpecificRealloc)(void*, size_t) = realloc;
void (*PlatformSpecificFree)(void* memory) = free;
void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = memcpy;
void* (*PlatformSpecificMemset)(void*, int, size_t) = memset;
static int IsNanImplementation(double d)
{
return _isnan(d);
}
static int IsInfImplementation(double d)
{
return !(_finite(d) || _isnan(d));
}
double (*PlatformSpecificFabs)(double) = fabs;
void (*PlatformSpecificSrand)(unsigned int) = srand;
int (*PlatformSpecificRand)(void) = rand;
int (*PlatformSpecificIsNan)(double) = IsNanImplementation;
int (*PlatformSpecificIsInf)(double) = IsInfImplementation;
int (*PlatformSpecificAtExit)(void(*func)(void)) = atexit; /// this was undefined before
static PlatformSpecificMutex PThreadMutexCreate(void)
{
#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK
pthread_mutex_t *mutex = new pthread_mutex_t;
pthread_mutex_init(mutex, NULLPTR);
return (PlatformSpecificMutex)mutex;
#else
return NULLPTR;
#endif
}
#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK
static void PThreadMutexLock(PlatformSpecificMutex mtx)
{
pthread_mutex_lock((pthread_mutex_t *)mtx);
}
#else
static void PThreadMutexLock(PlatformSpecificMutex)
{
}
#endif
#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK
static void PThreadMutexUnlock(PlatformSpecificMutex mtx)
{
pthread_mutex_unlock((pthread_mutex_t *)mtx);
}
#else
static void PThreadMutexUnlock(PlatformSpecificMutex)
{
}
#endif
#ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK
static void PThreadMutexDestroy(PlatformSpecificMutex mtx)
{
pthread_mutex_t *mutex = (pthread_mutex_t *)mtx;
pthread_mutex_destroy(mutex);
delete mutex;
}
#else
static void PThreadMutexDestroy(PlatformSpecificMutex)
{
}
#endif
PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = PThreadMutexCreate;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = PThreadMutexLock;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = PThreadMutexUnlock;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = PThreadMutexDestroy;
void (*PlatformSpecificAbort)(void) = abort;
}
| null |
227 | cpp | 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 <ctype.h>
#include <math.h>
#include "CppUTest/TestHarness.h"
#undef malloc
#undef calloc
#undef realloc
#undef free
#undef strdup
#undef strndup
#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 DummyPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, 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* shell, TestPlugin* plugin, TestResult* result) =
DummyPlatformSpecificRunTestInASeperateProcess;
int (*PlatformSpecificFork)(void) = 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 (*)(void*), void*) = PlatformSpecificSetJmpImplementation;
void (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferImplementation;
///////////// Time in millis
static unsigned long TimeInMillisImplementation()
{
clock_t t = clock();
t = t * 10;
return (unsigned long)t;
}
///////////// Time in String
static const char* TimeStringImplementation()
{
time_t tm = time(NULL);
char* pTimeStr = ctime(&tm);
char* newlineChar = strchr(pTimeStr, '\n'); // Find the terminating newline character.
if(newlineChar != NULL) *newlineChar = '\0'; //If newline is found replace it with the string terminator.
return (pTimeStr);
}
unsigned long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation;
const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation;
int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list args) = vsnprintf;
static PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag)
{
static int fileNo = 0;
(void)filename;
(void)flag;
fileNo++;
return (void*)fileNo;
}
static void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file)
{
(void)str;
(void)file;
printf("FILE%d:%s",(int)file, str);
}
static void PlatformSpecificFCloseImplementation(PlatformSpecificFile file)
{
(void)file;
}
static void PlatformSpecificFlushImplementation()
{
}
PlatformSpecificFile PlatformSpecificStdOut = stdout;
PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation;
void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation;
void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation;
void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation;
void* (*PlatformSpecificMalloc)(size_t size) = malloc;
void* (*PlatformSpecificRealloc)(void*, size_t) = realloc;
void (*PlatformSpecificFree)(void* memory) = free;
void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = memcpy;
void* (*PlatformSpecificMemset)(void*, int, size_t) = memset;
static int IsNanImplementation(double d)
{
return isnan(d);
}
static int IsInfImplementation(double d)
{
return isinf(d);
}
double (*PlatformSpecificFabs)(double) = fabs;
int (*PlatformSpecificIsNan)(double) = IsNanImplementation;
int (*PlatformSpecificIsInf)(double) = IsInfImplementation;
int (*PlatformSpecificAtExit)(void(*func)(void)) = atexit; /// this was undefined before
static PlatformSpecificMutex DummyMutexCreate(void)
{
return 0;
}
static void DummyMutexLock(PlatformSpecificMutex)
{
}
static void DummyMutexUnlock(PlatformSpecificMutex)
{
}
static void DummyMutexDestroy(PlatformSpecificMutex)
{
}
PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = DummyMutexCreate;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy;
void (*PlatformSpecificSrand)(unsigned int) = srand;
int (*PlatformSpecificRand)(void) = rand;
void (*PlatformSpecificAbort)(void) = abort;
}
| null |
228 | cpp | cpputest-starter-project | AllTests.cpp | tests/AllTests.cpp | null | #include "CppUTest/CommandLineTestRunner.h"
int main(int ac, char** av)
{
return CommandLineTestRunner::RunAllTests(ac, av);
}
| null |
229 | cpp | cpputest-starter-project | ExampleTest.cpp | tests/ExampleTest.cpp | null | #include "CppUTest/TestHarness.h"
extern "C"
{
#include "Example.h"
}
TEST_GROUP(Example)
{
void setup()
{
}
void teardown()
{
}
};
TEST(Example, returns_1)
{
LONGS_EQUAL(1, example());
}
| null |
230 | cpp | cpputest-starter-project | MyFirstTest.cpp | tests/MyFirstTest.cpp | null | #include "CppUTest/TestHarness.h"
extern "C"
{
/*
* Add your c-only include files here
*/
}
TEST_GROUP(MyCode)
{
void setup()
{
}
void teardown()
{
}
};
TEST(MyCode, test1)
{
FAIL("Your test is running! Now delete this line and watch your test pass.");
/*
* Instantiate your class, or call the function, you want to test.
* Then delete this comment
*/
}
| null |
231 | cpp | cpputest-starter-project | io_CppUMock.cpp | tests/io-cppumock/io_CppUMock.cpp | null | #include "CppUTestExt/MockSupport.h"
extern "C"
{
#include "io.h"
}
void IOWrite(IOAddress addr, IOData data)
{
mock("IO")
.actualCall("IOWrite")
.withParameter("addr", (int)addr)
.withParameter("data", (int)data);
}
IOData IORead(IOAddress addr)
{
return (IOData)mock("IO")
.actualCall("IORead")
.withParameter("addr", (int)addr)
.returnValue().getIntValue();
}
| null |
232 | cpp | cpputest-starter-project | io_CppUMockTest.cpp | tests/io-cppumock/io_CppUMockTest.cpp | null |
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
extern "C"
{
#include "io.h"
}
TEST_GROUP(IOReadWrite_CppUMockTest)
{
void setup()
{
}
void teardown()
{
mock("IO").checkExpectations();
mock().clear();
}
};
TEST(IOReadWrite_CppUMockTest, IOWrite)
{
mock("IO")
.expectOneCall("IOWrite")
.withParameter("addr", 0x1000)
.withParameter("data", 0xa000);
IOWrite(0x1000, 0xa000);
}
TEST(IOReadWrite_CppUMockTest, IORead)
{
mock("IO")
.expectOneCall("IORead")
.withParameter("addr", 1000)
.andReturnValue(55);
LONGS_EQUAL(55, IORead(1000));
}
| null |
233 | cpp | cpputest-starter-project | FormatOutputSpy.h | tests/printf-spy/FormatOutputSpy.h | null | #ifndef FORMAT_OUTPUT_SPY_INCLUDED
#define FORMAT_OUTPUT_SPY_INCLUDED
#include "FormatOutput.h"
int FormatOutputSpy(const char * format, ...);
void FormatOutputSpy_Create(unsigned int size);
void FormatOutputSpy_Destroy(void);
const char * FormatOutputSpy_GetOutput(void);
#endif
| null |
234 | cpp | cpputest-starter-project | FormatOutputSpyTest.cpp | tests/printf-spy/FormatOutputSpyTest.cpp | null | #include "CppUTest/TestHarness.h"
extern "C"
{
#include "FormatOutputSpy.h"
}
TEST_GROUP(FormatOutputSpy)
{
void setup()
{
UT_PTR_SET(FormatOutput, FormatOutputSpy);
}
void teardown()
{
FormatOutputSpy_Destroy();
}
};
TEST(FormatOutputSpy, Uninitialized)
{
FormatOutput("hey, this is ignored");
STRCMP_EQUAL("FormatOutputSpy is not initialized", FormatOutputSpy_GetOutput());
}
TEST(FormatOutputSpy, HelloWorld)
{
FormatOutputSpy_Create(50);
FormatOutput("Hello, %s\n", "World");
FormatOutput("Hello, %s\n", "World");
STRCMP_EQUAL(
"Hello, World\n"
"Hello, World\n"
, FormatOutputSpy_GetOutput());
}
TEST(FormatOutputSpy, LimitTheOutputBufferSize)
{
FormatOutputSpy_Create(4);
FormatOutput("Hello, World\n");
STRCMP_EQUAL("Hell", FormatOutputSpy_GetOutput());
}
TEST(FormatOutputSpy, PrintMultipleTimes)
{
FormatOutputSpy_Create(25);
FormatOutput("Hello");
FormatOutput(", World\n");
STRCMP_EQUAL("Hello, World\n", FormatOutputSpy_GetOutput());
}
TEST(FormatOutputSpy, PrintMultipleOutputsPastFull)
{
FormatOutputSpy_Create(12);
FormatOutput("%d", 12345);
FormatOutput("%d", 67890);
FormatOutput("ABCDEF");
STRCMP_EQUAL("1234567890AB", FormatOutputSpy_GetOutput());
}
| null |
235 | cpp | cpputest-starter-project | FormatOutput.h | tests/printf-spy/FormatOutput.h | null | #ifndef FORMAT_OUTPUT_INCLUDED
#define FORMAT_OUTPUT_INCLUDED
extern int (*FormatOutput)(const char *, ...);
#endif /* FORMAT_OUTPIT_INCLUDED */
| null |
236 | cpp | cpputest-starter-project | fff.h | tests/fff/fff.h | null | #ifndef FAKE_FUNCTIONS
#define FAKE_FUNCTIONS
#define FFF_MAX_ARGS (10u)
#ifndef FFF_ARG_HISTORY_LEN
#define FFF_ARG_HISTORY_LEN (50u)
#endif
#ifndef FFF_CALL_HISTORY_LEN
#define FFF_CALL_HISTORY_LEN (50u)
#endif
#ifndef FFF_RESET_ALL_FAKES_LEN
#define FFF_RESET_ALL_FAKES_LEN (50u)
#endif
#ifdef FFF_NO_EXTERN_C /*compiling C with C++ compiler */
#define EXTERN_C
#define END_EXTERN_C
#else
#ifdef __cplusplus
#define EXTERN_C extern "C"{
#define END_EXTERN_C }
#else /* ansi c */
#define EXTERN_C
#define END_EXTERN_C
#endif
#endif
/* Global functions and structs */
EXTERN_C
typedef void (*reset_fake_function_t)(void);
void fff_register_fake(reset_fake_function_t reset_fake);
void fff_reset();
void fff_memset(void * ptr, int value, int num);
typedef struct {
void * call_history[FFF_CALL_HISTORY_LEN];
unsigned int call_history_idx;
reset_fake_function_t reset_fake[FFF_RESET_ALL_FAKES_LEN];
unsigned int reset_fakes_count;
int call_history_overflow;
int registration_overflow;
} fff_globals_t;
#define FFF_OVERFLOW (fff.call_history_overflow || fff.registration_overflow)
#define FFF_RESET_HISTORY() fff.call_history_idx = 0;
#define FFF_RESET fff_reset()
END_EXTERN_C
/* -- INTERNAL HELPER MACROS -- */
#define SET_RETURN_SEQ(FUNCNAME, ARRAY_POINTER, ARRAY_LEN) \
FUNCNAME##_fake.return_val_seq = ARRAY_POINTER; \
FUNCNAME##_fake.return_val_seq_len = ARRAY_LEN;
/* Defining a function to reset a fake function */
#define RESET_FAKE(FUNCNAME) { \
FUNCNAME##_reset_private(); \
} \
#define DECLARE_ARG(type, n) \
type arg##n##_val; \
type arg##n##_history[FFF_ARG_HISTORY_LEN];
#define DECLARE_ALL_FUNC_COMMON \
unsigned int call_count; \
unsigned int arg_histories_dropped; \
unsigned int arg_history_idx; \
unsigned int arg_history_len; \
#define SAVE_ARG(FUNCNAME, n) \
FUNCNAME##_fake.arg##n##_val = arg##n
#define ROOM_FOR_MORE_HISTORY(FUNCNAME) \
FUNCNAME##_fake.call_count < FFF_ARG_HISTORY_LEN
#define SAVE_ARG_HISTORY(FUNCNAME, ARGN) \
FUNCNAME##_fake.arg##ARGN##_history[FUNCNAME##_fake.arg_history_len] = arg##ARGN;\
#define HISTORY_DROPPED(FUNCNAME) \
FUNCNAME##_fake.arg_histories_dropped++
#define DECLARE_VALUE_FUNCTION_VARIABLES(RETURN_TYPE) \
RETURN_TYPE return_val; \
int return_val_seq_len; \
int return_val_seq_idx; \
RETURN_TYPE * return_val_seq; \
#define INCREMENT_CALL_COUNT(FUNCNAME) \
FUNCNAME##_fake.call_count++
#define RETURN_FAKE_RESULT(FUNCNAME) \
if (FUNCNAME##_fake.return_val_seq_len){ /* then its a sequence */ \
if(FUNCNAME##_fake.return_val_seq_idx < FUNCNAME##_fake.return_val_seq_len) { \
return FUNCNAME##_fake.return_val_seq[FUNCNAME##_fake.return_val_seq_idx++]; \
} \
return FUNCNAME##_fake.return_val_seq[FUNCNAME##_fake.return_val_seq_len-1]; /* return last element */ \
} \
return FUNCNAME##_fake.return_val; \
#define DEFINE_RESET_FUNCTION(FUNCNAME) \
void FUNCNAME##_reset_private(){ \
fff_memset(&FUNCNAME##_fake, 0, (int)sizeof(FUNCNAME##_fake)); \
}
/* -- END INTERNAL HELPER MACROS -- */
/* -- GLOBAL HELPERS -- */
EXTERN_C
extern fff_globals_t fff;
END_EXTERN_C
#define DEFINE_FFF_GLOBALS \
EXTERN_C \
fff_globals_t fff; \
\
void fff_memset(void * ptr, int value, int num )\
{\
int i;\
char * p = (char*)ptr;\
for (i = 0; i < num; i++, p++)\
*p = value;\
}\
\
void fff_register_fake(reset_fake_function_t reset_fake)\
{\
if (fff.reset_fakes_count >= FFF_RESET_ALL_FAKES_LEN)\
fff.registration_overflow = 1;\
else\
{\
unsigned int i;\
for (i = 0; i < fff.reset_fakes_count; i++)\
{\
if (fff.reset_fake[i] == reset_fake)\
return;\
}\
fff.reset_fake[fff.reset_fakes_count++] = reset_fake;\
}\
}\
\
void fff_reset()\
{\
unsigned int i;\
for (i = 0; i < fff.reset_fakes_count; i++)\
fff.reset_fake[i]();\
fff_memset(&fff, 0, sizeof(fff));\
}\
END_EXTERN_C
#define FFF_REGISTER_FAKE(FUNCNAME) fff_register_fake(FUNCNAME##_reset_private);
#define REGISTER_CALL(function) \
if(fff.call_history_idx < FFF_CALL_HISTORY_LEN) \
fff.call_history[fff.call_history_idx++] = (void *)function; else fff.call_history_overflow = 1;
/* -- END GLOBAL HELPERS -- */
#define DECLARE_FAKE_VOID_FUNC0(FUNCNAME) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ALL_FUNC_COMMON \
void(*custom_fake)(); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VOID_FUNC0(FUNCNAME) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME(){ \
FFF_REGISTER_FAKE(FUNCNAME);\
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) FUNCNAME##_fake.custom_fake(); \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VOID_FUNC0(FUNCNAME) \
DECLARE_FAKE_VOID_FUNC0(FUNCNAME) \
DEFINE_FAKE_VOID_FUNC0(FUNCNAME) \
#define DECLARE_FAKE_VOID_FUNC1(FUNCNAME, ARG0_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ALL_FUNC_COMMON \
void(*custom_fake)(ARG0_TYPE arg0); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VOID_FUNC1(FUNCNAME, ARG0_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME(ARG0_TYPE arg0){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) FUNCNAME##_fake.custom_fake(arg0); \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VOID_FUNC1(FUNCNAME, ARG0_TYPE) \
DECLARE_FAKE_VOID_FUNC1(FUNCNAME, ARG0_TYPE) \
DEFINE_FAKE_VOID_FUNC1(FUNCNAME, ARG0_TYPE) \
#define DECLARE_FAKE_VOID_FUNC2(FUNCNAME, ARG0_TYPE, ARG1_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ALL_FUNC_COMMON \
void(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VOID_FUNC2(FUNCNAME, ARG0_TYPE, ARG1_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) FUNCNAME##_fake.custom_fake(arg0, arg1); \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VOID_FUNC2(FUNCNAME, ARG0_TYPE, ARG1_TYPE) \
DECLARE_FAKE_VOID_FUNC2(FUNCNAME, ARG0_TYPE, ARG1_TYPE) \
DEFINE_FAKE_VOID_FUNC2(FUNCNAME, ARG0_TYPE, ARG1_TYPE) \
#define DECLARE_FAKE_VOID_FUNC3(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ALL_FUNC_COMMON \
void(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VOID_FUNC3(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) FUNCNAME##_fake.custom_fake(arg0, arg1, arg2); \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VOID_FUNC3(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE) \
DECLARE_FAKE_VOID_FUNC3(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE) \
DEFINE_FAKE_VOID_FUNC3(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE) \
#define DECLARE_FAKE_VOID_FUNC4(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ALL_FUNC_COMMON \
void(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VOID_FUNC4(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3); \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VOID_FUNC4(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE) \
DECLARE_FAKE_VOID_FUNC4(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE) \
DEFINE_FAKE_VOID_FUNC4(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE) \
#define DECLARE_FAKE_VOID_FUNC5(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ARG(ARG4_TYPE, 4) \
DECLARE_ALL_FUNC_COMMON \
void(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VOID_FUNC5(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
SAVE_ARG(FUNCNAME, 4); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
SAVE_ARG_HISTORY(FUNCNAME, 4); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3, arg4); \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VOID_FUNC5(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE) \
DECLARE_FAKE_VOID_FUNC5(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE) \
DEFINE_FAKE_VOID_FUNC5(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE) \
#define DECLARE_FAKE_VOID_FUNC6(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ARG(ARG4_TYPE, 4) \
DECLARE_ARG(ARG5_TYPE, 5) \
DECLARE_ALL_FUNC_COMMON \
void(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VOID_FUNC6(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
SAVE_ARG(FUNCNAME, 4); \
SAVE_ARG(FUNCNAME, 5); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
SAVE_ARG_HISTORY(FUNCNAME, 4); \
SAVE_ARG_HISTORY(FUNCNAME, 5); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3, arg4, arg5); \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VOID_FUNC6(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE) \
DECLARE_FAKE_VOID_FUNC6(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE) \
DEFINE_FAKE_VOID_FUNC6(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE) \
#define DECLARE_FAKE_VOID_FUNC7(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ARG(ARG4_TYPE, 4) \
DECLARE_ARG(ARG5_TYPE, 5) \
DECLARE_ARG(ARG6_TYPE, 6) \
DECLARE_ALL_FUNC_COMMON \
void(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VOID_FUNC7(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
SAVE_ARG(FUNCNAME, 4); \
SAVE_ARG(FUNCNAME, 5); \
SAVE_ARG(FUNCNAME, 6); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
SAVE_ARG_HISTORY(FUNCNAME, 4); \
SAVE_ARG_HISTORY(FUNCNAME, 5); \
SAVE_ARG_HISTORY(FUNCNAME, 6); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3, arg4, arg5, arg6); \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VOID_FUNC7(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE) \
DECLARE_FAKE_VOID_FUNC7(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE) \
DEFINE_FAKE_VOID_FUNC7(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE) \
#define DECLARE_FAKE_VOID_FUNC8(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ARG(ARG4_TYPE, 4) \
DECLARE_ARG(ARG5_TYPE, 5) \
DECLARE_ARG(ARG6_TYPE, 6) \
DECLARE_ARG(ARG7_TYPE, 7) \
DECLARE_ALL_FUNC_COMMON \
void(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6, ARG7_TYPE arg7); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VOID_FUNC8(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6, ARG7_TYPE arg7){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
SAVE_ARG(FUNCNAME, 4); \
SAVE_ARG(FUNCNAME, 5); \
SAVE_ARG(FUNCNAME, 6); \
SAVE_ARG(FUNCNAME, 7); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
SAVE_ARG_HISTORY(FUNCNAME, 4); \
SAVE_ARG_HISTORY(FUNCNAME, 5); \
SAVE_ARG_HISTORY(FUNCNAME, 6); \
SAVE_ARG_HISTORY(FUNCNAME, 7); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VOID_FUNC8(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE) \
DECLARE_FAKE_VOID_FUNC8(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE) \
DEFINE_FAKE_VOID_FUNC8(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE) \
#define DECLARE_FAKE_VOID_FUNC9(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE, ARG8_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ARG(ARG4_TYPE, 4) \
DECLARE_ARG(ARG5_TYPE, 5) \
DECLARE_ARG(ARG6_TYPE, 6) \
DECLARE_ARG(ARG7_TYPE, 7) \
DECLARE_ARG(ARG8_TYPE, 8) \
DECLARE_ALL_FUNC_COMMON \
void(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6, ARG7_TYPE arg7, ARG8_TYPE arg8); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VOID_FUNC9(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE, ARG8_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6, ARG7_TYPE arg7, ARG8_TYPE arg8){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
SAVE_ARG(FUNCNAME, 4); \
SAVE_ARG(FUNCNAME, 5); \
SAVE_ARG(FUNCNAME, 6); \
SAVE_ARG(FUNCNAME, 7); \
SAVE_ARG(FUNCNAME, 8); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
SAVE_ARG_HISTORY(FUNCNAME, 4); \
SAVE_ARG_HISTORY(FUNCNAME, 5); \
SAVE_ARG_HISTORY(FUNCNAME, 6); \
SAVE_ARG_HISTORY(FUNCNAME, 7); \
SAVE_ARG_HISTORY(FUNCNAME, 8); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VOID_FUNC9(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE, ARG8_TYPE) \
DECLARE_FAKE_VOID_FUNC9(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE, ARG8_TYPE) \
DEFINE_FAKE_VOID_FUNC9(FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE, ARG8_TYPE) \
#define DECLARE_FAKE_VALUE_FUNC0(RETURN_TYPE, FUNCNAME) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ALL_FUNC_COMMON \
DECLARE_VALUE_FUNCTION_VARIABLES(RETURN_TYPE) \
RETURN_TYPE(*custom_fake)(); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VALUE_FUNC0(RETURN_TYPE, FUNCNAME) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
RETURN_TYPE FUNCNAME(){ \
FFF_REGISTER_FAKE(FUNCNAME);\
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) return FUNCNAME##_fake.custom_fake(); \
RETURN_FAKE_RESULT(FUNCNAME) \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VALUE_FUNC0(RETURN_TYPE, FUNCNAME) \
DECLARE_FAKE_VALUE_FUNC0(RETURN_TYPE, FUNCNAME) \
DEFINE_FAKE_VALUE_FUNC0(RETURN_TYPE, FUNCNAME) \
#define DECLARE_FAKE_VALUE_FUNC1(RETURN_TYPE, FUNCNAME, ARG0_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ALL_FUNC_COMMON \
DECLARE_VALUE_FUNCTION_VARIABLES(RETURN_TYPE) \
RETURN_TYPE(*custom_fake)(ARG0_TYPE arg0); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VALUE_FUNC1(RETURN_TYPE, FUNCNAME, ARG0_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
RETURN_TYPE FUNCNAME(ARG0_TYPE arg0){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) return FUNCNAME##_fake.custom_fake(arg0); \
RETURN_FAKE_RESULT(FUNCNAME) \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VALUE_FUNC1(RETURN_TYPE, FUNCNAME, ARG0_TYPE) \
DECLARE_FAKE_VALUE_FUNC1(RETURN_TYPE, FUNCNAME, ARG0_TYPE) \
DEFINE_FAKE_VALUE_FUNC1(RETURN_TYPE, FUNCNAME, ARG0_TYPE) \
#define DECLARE_FAKE_VALUE_FUNC2(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ALL_FUNC_COMMON \
DECLARE_VALUE_FUNCTION_VARIABLES(RETURN_TYPE) \
RETURN_TYPE(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VALUE_FUNC2(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
RETURN_TYPE FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) return FUNCNAME##_fake.custom_fake(arg0, arg1); \
RETURN_FAKE_RESULT(FUNCNAME) \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VALUE_FUNC2(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE) \
DECLARE_FAKE_VALUE_FUNC2(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE) \
DEFINE_FAKE_VALUE_FUNC2(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE) \
#define DECLARE_FAKE_VALUE_FUNC3(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ALL_FUNC_COMMON \
DECLARE_VALUE_FUNCTION_VARIABLES(RETURN_TYPE) \
RETURN_TYPE(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VALUE_FUNC3(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
RETURN_TYPE FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) return FUNCNAME##_fake.custom_fake(arg0, arg1, arg2); \
RETURN_FAKE_RESULT(FUNCNAME) \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VALUE_FUNC3(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE) \
DECLARE_FAKE_VALUE_FUNC3(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE) \
DEFINE_FAKE_VALUE_FUNC3(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE) \
#define DECLARE_FAKE_VALUE_FUNC4(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ALL_FUNC_COMMON \
DECLARE_VALUE_FUNCTION_VARIABLES(RETURN_TYPE) \
RETURN_TYPE(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VALUE_FUNC4(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
RETURN_TYPE FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) return FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3); \
RETURN_FAKE_RESULT(FUNCNAME) \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VALUE_FUNC4(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE) \
DECLARE_FAKE_VALUE_FUNC4(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE) \
DEFINE_FAKE_VALUE_FUNC4(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE) \
#define DECLARE_FAKE_VALUE_FUNC5(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ARG(ARG4_TYPE, 4) \
DECLARE_ALL_FUNC_COMMON \
DECLARE_VALUE_FUNCTION_VARIABLES(RETURN_TYPE) \
RETURN_TYPE(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VALUE_FUNC5(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
RETURN_TYPE FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
SAVE_ARG(FUNCNAME, 4); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
SAVE_ARG_HISTORY(FUNCNAME, 4); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) return FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3, arg4); \
RETURN_FAKE_RESULT(FUNCNAME) \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VALUE_FUNC5(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE) \
DECLARE_FAKE_VALUE_FUNC5(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE) \
DEFINE_FAKE_VALUE_FUNC5(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE) \
#define DECLARE_FAKE_VALUE_FUNC6(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ARG(ARG4_TYPE, 4) \
DECLARE_ARG(ARG5_TYPE, 5) \
DECLARE_ALL_FUNC_COMMON \
DECLARE_VALUE_FUNCTION_VARIABLES(RETURN_TYPE) \
RETURN_TYPE(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VALUE_FUNC6(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
RETURN_TYPE FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
SAVE_ARG(FUNCNAME, 4); \
SAVE_ARG(FUNCNAME, 5); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
SAVE_ARG_HISTORY(FUNCNAME, 4); \
SAVE_ARG_HISTORY(FUNCNAME, 5); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) return FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3, arg4, arg5); \
RETURN_FAKE_RESULT(FUNCNAME) \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VALUE_FUNC6(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE) \
DECLARE_FAKE_VALUE_FUNC6(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE) \
DEFINE_FAKE_VALUE_FUNC6(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE) \
#define DECLARE_FAKE_VALUE_FUNC7(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ARG(ARG4_TYPE, 4) \
DECLARE_ARG(ARG5_TYPE, 5) \
DECLARE_ARG(ARG6_TYPE, 6) \
DECLARE_ALL_FUNC_COMMON \
DECLARE_VALUE_FUNCTION_VARIABLES(RETURN_TYPE) \
RETURN_TYPE(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VALUE_FUNC7(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
RETURN_TYPE FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
SAVE_ARG(FUNCNAME, 4); \
SAVE_ARG(FUNCNAME, 5); \
SAVE_ARG(FUNCNAME, 6); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
SAVE_ARG_HISTORY(FUNCNAME, 4); \
SAVE_ARG_HISTORY(FUNCNAME, 5); \
SAVE_ARG_HISTORY(FUNCNAME, 6); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) return FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3, arg4, arg5, arg6); \
RETURN_FAKE_RESULT(FUNCNAME) \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VALUE_FUNC7(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE) \
DECLARE_FAKE_VALUE_FUNC7(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE) \
DEFINE_FAKE_VALUE_FUNC7(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE) \
#define DECLARE_FAKE_VALUE_FUNC8(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ARG(ARG4_TYPE, 4) \
DECLARE_ARG(ARG5_TYPE, 5) \
DECLARE_ARG(ARG6_TYPE, 6) \
DECLARE_ARG(ARG7_TYPE, 7) \
DECLARE_ALL_FUNC_COMMON \
DECLARE_VALUE_FUNCTION_VARIABLES(RETURN_TYPE) \
RETURN_TYPE(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6, ARG7_TYPE arg7); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VALUE_FUNC8(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
RETURN_TYPE FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6, ARG7_TYPE arg7){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
SAVE_ARG(FUNCNAME, 4); \
SAVE_ARG(FUNCNAME, 5); \
SAVE_ARG(FUNCNAME, 6); \
SAVE_ARG(FUNCNAME, 7); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
SAVE_ARG_HISTORY(FUNCNAME, 4); \
SAVE_ARG_HISTORY(FUNCNAME, 5); \
SAVE_ARG_HISTORY(FUNCNAME, 6); \
SAVE_ARG_HISTORY(FUNCNAME, 7); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) return FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); \
RETURN_FAKE_RESULT(FUNCNAME) \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VALUE_FUNC8(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE) \
DECLARE_FAKE_VALUE_FUNC8(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE) \
DEFINE_FAKE_VALUE_FUNC8(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE) \
#define DECLARE_FAKE_VALUE_FUNC9(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE, ARG8_TYPE) \
EXTERN_C \
typedef struct FUNCNAME##_Fake { \
DECLARE_ARG(ARG0_TYPE, 0) \
DECLARE_ARG(ARG1_TYPE, 1) \
DECLARE_ARG(ARG2_TYPE, 2) \
DECLARE_ARG(ARG3_TYPE, 3) \
DECLARE_ARG(ARG4_TYPE, 4) \
DECLARE_ARG(ARG5_TYPE, 5) \
DECLARE_ARG(ARG6_TYPE, 6) \
DECLARE_ARG(ARG7_TYPE, 7) \
DECLARE_ARG(ARG8_TYPE, 8) \
DECLARE_ALL_FUNC_COMMON \
DECLARE_VALUE_FUNCTION_VARIABLES(RETURN_TYPE) \
RETURN_TYPE(*custom_fake)(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6, ARG7_TYPE arg7, ARG8_TYPE arg8); \
} FUNCNAME##_Fake;\
extern FUNCNAME##_Fake FUNCNAME##_fake;\
void FUNCNAME##_reset_private(); \
END_EXTERN_C \
#define DEFINE_FAKE_VALUE_FUNC9(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE, ARG8_TYPE) \
EXTERN_C \
FUNCNAME##_Fake FUNCNAME##_fake;\
RETURN_TYPE FUNCNAME(ARG0_TYPE arg0, ARG1_TYPE arg1, ARG2_TYPE arg2, ARG3_TYPE arg3, ARG4_TYPE arg4, ARG5_TYPE arg5, ARG6_TYPE arg6, ARG7_TYPE arg7, ARG8_TYPE arg8){ \
FFF_REGISTER_FAKE(FUNCNAME);\
SAVE_ARG(FUNCNAME, 0); \
SAVE_ARG(FUNCNAME, 1); \
SAVE_ARG(FUNCNAME, 2); \
SAVE_ARG(FUNCNAME, 3); \
SAVE_ARG(FUNCNAME, 4); \
SAVE_ARG(FUNCNAME, 5); \
SAVE_ARG(FUNCNAME, 6); \
SAVE_ARG(FUNCNAME, 7); \
SAVE_ARG(FUNCNAME, 8); \
if(ROOM_FOR_MORE_HISTORY(FUNCNAME)){\
SAVE_ARG_HISTORY(FUNCNAME, 0); \
SAVE_ARG_HISTORY(FUNCNAME, 1); \
SAVE_ARG_HISTORY(FUNCNAME, 2); \
SAVE_ARG_HISTORY(FUNCNAME, 3); \
SAVE_ARG_HISTORY(FUNCNAME, 4); \
SAVE_ARG_HISTORY(FUNCNAME, 5); \
SAVE_ARG_HISTORY(FUNCNAME, 6); \
SAVE_ARG_HISTORY(FUNCNAME, 7); \
SAVE_ARG_HISTORY(FUNCNAME, 8); \
FUNCNAME##_fake.arg_history_len++;\
}\
else{\
HISTORY_DROPPED(FUNCNAME);\
}\
INCREMENT_CALL_COUNT(FUNCNAME); \
REGISTER_CALL(FUNCNAME); \
if (FUNCNAME##_fake.custom_fake) return FUNCNAME##_fake.custom_fake(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); \
RETURN_FAKE_RESULT(FUNCNAME) \
} \
DEFINE_RESET_FUNCTION(FUNCNAME) \
END_EXTERN_C \
#define FAKE_VALUE_FUNC9(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE, ARG8_TYPE) \
DECLARE_FAKE_VALUE_FUNC9(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE, ARG8_TYPE) \
DEFINE_FAKE_VALUE_FUNC9(RETURN_TYPE, FUNCNAME, ARG0_TYPE, ARG1_TYPE, ARG2_TYPE, ARG3_TYPE, ARG4_TYPE, ARG5_TYPE, ARG6_TYPE, ARG7_TYPE, ARG8_TYPE) \
#define PP_NARG_MINUS2(...) PP_NARG_MINUS2_(__VA_ARGS__, PP_RSEQ_N_MINUS2())
#define PP_NARG_MINUS2_(...) PP_ARG_MINUS2_N(__VA_ARGS__)
#define PP_ARG_MINUS2_N(returnVal, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, N, ...) N
#define PP_RSEQ_N_MINUS2() 9,8,7,6,5,4,3,2,1,0
#define FAKE_VALUE_FUNC(...) FUNC_VALUE_(PP_NARG_MINUS2(__VA_ARGS__), __VA_ARGS__)
#define FUNC_VALUE_(N,...) FUNC_VALUE_N(N,__VA_ARGS__)
#define FUNC_VALUE_N(N,...) FAKE_VALUE_FUNC ## N(__VA_ARGS__)
#define PP_NARG_MINUS1(...) PP_NARG_MINUS1_(__VA_ARGS__, PP_RSEQ_N_MINUS1())
#define PP_NARG_MINUS1_(...) PP_ARG_MINUS1_N(__VA_ARGS__)
#define PP_ARG_MINUS1_N(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, N, ...) N
#define PP_RSEQ_N_MINUS1() 9,8,7,6,5,4,3,2,1,0
#define FAKE_VOID_FUNC(...) FUNC_VOID_(PP_NARG_MINUS1(__VA_ARGS__), __VA_ARGS__)
#define FUNC_VOID_(N,...) FUNC_VOID_N(N,__VA_ARGS__)
#define FUNC_VOID_N(N,...) FAKE_VOID_FUNC ## N(__VA_ARGS__)
#define DECLARE_FAKE_VALUE_FUNC(...) DECLARE_FUNC_VALUE_(PP_NARG_MINUS2(__VA_ARGS__), __VA_ARGS__)
#define DECLARE_FUNC_VALUE_(N,...) DECLARE_FUNC_VALUE_N(N,__VA_ARGS__)
#define DECLARE_FUNC_VALUE_N(N,...) DECLARE_FAKE_VALUE_FUNC ## N(__VA_ARGS__)
#define DEFINE_FAKE_VALUE_FUNC(...) DEFINE_FUNC_VALUE_(PP_NARG_MINUS2(__VA_ARGS__), __VA_ARGS__)
#define DEFINE_FUNC_VALUE_(N,...) DEFINE_FUNC_VALUE_N(N,__VA_ARGS__)
#define DEFINE_FUNC_VALUE_N(N,...) DEFINE_FAKE_VALUE_FUNC ## N(__VA_ARGS__)
#define DECLARE_FAKE_VOID_FUNC(...) DECLARE_FUNC_VOID_(PP_NARG_MINUS1(__VA_ARGS__), __VA_ARGS__)
#define DECLARE_FUNC_VOID_(N,...) DECLARE_FUNC_VOID_N(N,__VA_ARGS__)
#define DECLARE_FUNC_VOID_N(N,...) DECLARE_FAKE_VOID_FUNC ## N(__VA_ARGS__)
#define DEFINE_FAKE_VOID_FUNC(...) DEFINE_FUNC_VOID_(PP_NARG_MINUS1(__VA_ARGS__), __VA_ARGS__)
#define DEFINE_FUNC_VOID_(N,...) DEFINE_FUNC_VOID_N(N,__VA_ARGS__)
#define DEFINE_FUNC_VOID_N(N,...) DEFINE_FAKE_VOID_FUNC ## N(__VA_ARGS__)
#endif // FAKE_FUNCTIONS
#ifdef GENERATE_FAKES
#undef FAKE_VALUE_FUNCTION
#undef FAKE_VOID_FUNCTION
#define FAKE_VALUE_FUNCTION DEFINE_FAKE_VALUE_FUNC
#define FAKE_VOID_FUNCTION DEFINE_FAKE_VOID_FUNC
#else
#define FAKE_VALUE_FUNCTION DECLARE_FAKE_VALUE_FUNC
#define FAKE_VOID_FUNCTION DECLARE_FAKE_VOID_FUNC
#endif
| null |
237 | cpp | cpputest-starter-project | FooExampleFFFTests.cpp | tests/example-fff/FooExampleFFFTests.cpp | null | #include "CppUTest/TestHarness.h"
extern "C"
{
#include "FooExample.fff.h"
}
TEST_GROUP(fff_foo)
{
void setup()
{
FFF_RESET;
}
void teardown()
{
}
};
TEST(fff_foo, function_call_count_is_zero_after_init)
{
LONGS_EQUAL(0, voidfoo0_fake.call_count);
}
TEST(fff_foo, fake_a_void_function_with_no_parameters)
{
voidfoo0();
voidfoo0();
LONGS_EQUAL(2, voidfoo0_fake.call_count);
}
TEST(fff_foo, fake_a_void_function_with_parameters)
{
voidfoo3(42, 3.1415926, "hello world");
LONGS_EQUAL(1, voidfoo3_fake.call_count);
LONGS_EQUAL(42, voidfoo3_fake.arg0_val);
DOUBLES_EQUAL(3.1415926, voidfoo3_fake.arg1_val, 0.00000001);
STRCMP_EQUAL("hello world", voidfoo3_fake.arg2_val);
}
TEST(fff_foo, fake_a_void_function_with_parameter_history)
{
voidfoo3(42, 3.1415926, "hello world");
voidfoo3(43, 2.17, "goodbye world");
LONGS_EQUAL(2, voidfoo3_fake.call_count);
LONGS_EQUAL(42, voidfoo3_fake.arg0_history[0]);
DOUBLES_EQUAL(3.1415926, voidfoo3_fake.arg1_history[0], 0.00000001);
STRCMP_EQUAL("hello world", voidfoo3_fake.arg2_history[0]);
LONGS_EQUAL(43, voidfoo3_fake.arg0_history[1]);
DOUBLES_EQUAL(2.17, voidfoo3_fake.arg1_history[1], 0.00000001);
STRCMP_EQUAL("goodbye world", voidfoo3_fake.arg2_history[1]);
}
TEST(fff_foo, look_at_a_functions_call_history)
{
voidfoo1(42);
voidfoo1(43);
voidfoo1(44);
LONGS_EQUAL(42, voidfoo1_fake.arg0_history[0]);
LONGS_EQUAL(43, voidfoo1_fake.arg0_history[1]);
LONGS_EQUAL(44, voidfoo1_fake.arg0_history[2]);
LONGS_EQUAL( 0, voidfoo1_fake.arg0_history[3]);
}
TEST(fff_foo, global_call_history_is_empty_after_init)
{
POINTERS_EQUAL(0, fff.call_history[0]);
LONGS_EQUAL(0, fff.call_history_idx);
}
TEST(fff_foo, look_at_the_global_call_history)
{
voidfoo1(42);
voidfoo2(43, 3.14159265);
voidfoo3(43, 3.14159265, "hey");
POINTERS_EQUAL(voidfoo1, fff.call_history[0]);
POINTERS_EQUAL(voidfoo2, fff.call_history[1]);
POINTERS_EQUAL(voidfoo3, fff.call_history[2]);
POINTERS_EQUAL( 0, fff.call_history[3]);
}
TEST(fff_foo, value_returning_function)
{
LONGS_EQUAL(0, intfoo0());
intfoo0_fake.return_val = 999;
LONGS_EQUAL(999, intfoo0());
LONGS_EQUAL(2, intfoo0_fake.call_count);
}
TEST(fff_foo, specify_a_sequence_of_return_values)
{
int return_value_sequence[] = {0,1,2,3};
int return_value_sequence_length = sizeof(return_value_sequence)/sizeof(int);
SET_RETURN_SEQ(intfoo0, return_value_sequence, return_value_sequence_length);
LONGS_EQUAL(0, intfoo0());
LONGS_EQUAL(1, intfoo0());
LONGS_EQUAL(2, intfoo0());
LONGS_EQUAL(3, intfoo0());
LONGS_EQUAL(3, intfoo0());
LONGS_EQUAL(3, intfoo0());
LONGS_EQUAL(6, intfoo0_fake.call_count);
}
TEST(fff_foo, specify_a_sequence_of_return_values_but_keep_calling)
{
int return_value_sequence[] = {0,99};
int return_value_sequence_length = sizeof(return_value_sequence)/sizeof(int);
SET_RETURN_SEQ(intfoo0, return_value_sequence, return_value_sequence_length);
LONGS_EQUAL(0, intfoo0());
LONGS_EQUAL(99, intfoo0());
LONGS_EQUAL(99, intfoo0());
LONGS_EQUAL(3, intfoo0_fake.call_count);
}
static int myFakeCalled;
int my_intfoo0(void)
{
myFakeCalled++;
return 42;
}
TEST(fff_foo, provide_a_custom_fake_that_i)
{
myFakeCalled = 0;
intfoo0_fake.return_val = -9999;
intfoo0_fake.custom_fake = my_intfoo0;
LONGS_EQUAL(42, intfoo0());
LONGS_EQUAL(1, intfoo0_fake.call_count);
LONGS_EQUAL(1, myFakeCalled);
}
| null |
238 | cpp | cpputest-starter-project | FooExample.fff.h | tests/example-fff/FooExample.fff.h | null | #include "FooExample.h"
#include "fff.h"
/*
* Specify the fake functions you want in a header file like this one.
*
* Using this form of header, the file will be included once in the test case file, and
*/
FAKE_VOID_FUNCTION(voidfoo0);
FAKE_VOID_FUNCTION(voidfoo1, int);
FAKE_VOID_FUNCTION(voidfoo2, int, double);
FAKE_VOID_FUNCTION(voidfoo3, int, double, const char *);
//...
FAKE_VOID_FUNCTION(voidfoo9, int, int, int, int, int, int, int, int, mytype *);
FAKE_VALUE_FUNCTION(int, intfoo0);
FAKE_VALUE_FUNCTION(int, intfoo1, int);
FAKE_VALUE_FUNCTION(int, intfoo2, int, int);
FAKE_VALUE_FUNCTION(int, intfoo3, int, int, int);
//...
FAKE_VALUE_FUNCTION(int, intfoo9, int, int, int, int, int, int, int, int, mytype *);
| null |
239 | cpp | cpputest-starter-project | io_FFFTest.cpp | tests/io-fff/io_FFFTest.cpp | null | extern "C"
{
#include "io.fff.h"
}
#include "CppUTest/TestHarness.h"
TEST_GROUP(IOReadWriteFFF)
{
void setup()
{
FFF_RESET;
}
void teardown()
{
}
};
TEST(IOReadWriteFFF, IOWrite)
{
IOWrite(99, 333);
LONGS_EQUAL(1, IOWrite_fake.call_count);
LONGS_EQUAL(99, IOWrite_fake.arg0_val);
LONGS_EQUAL(333, IOWrite_fake.arg1_val);
}
TEST(IOReadWriteFFF, IORead)
{
IORead_fake.return_val = 999;
LONGS_EQUAL(999, IORead(99));
LONGS_EQUAL(1, IORead_fake.call_count);
LONGS_EQUAL(99, IORead_fake.arg0_val);
}
TEST(IOReadWriteFFF, MultipleIORead)
{
IOData return_value_sequence[] = {1,2,3,4};
int return_value_sequence_length = sizeof(return_value_sequence)/sizeof(IOData);
SET_RETURN_SEQ(IORead, return_value_sequence, return_value_sequence_length);
LONGS_EQUAL(1, IORead(10));
LONGS_EQUAL(2, IORead(11));
LONGS_EQUAL(3, IORead(12));
LONGS_EQUAL(4, IORead(13));
LONGS_EQUAL(4, IORead_fake.call_count);
LONGS_EQUAL(10, IORead_fake.arg0_history[0]);
LONGS_EQUAL(11, IORead_fake.arg0_history[1]);
LONGS_EQUAL(12, IORead_fake.arg0_history[2]);
LONGS_EQUAL(13, IORead_fake.arg0_history[3]);
}
TEST(IOReadWriteFFF, global_call_history)
{
IOWrite(0,0);
IOWrite(0,0);
IORead(0);
IOWrite(0,0);
POINTERS_EQUAL(IOWrite, fff.call_history[0]);
POINTERS_EQUAL(IOWrite, fff.call_history[1]);
POINTERS_EQUAL(IORead, fff.call_history[2]);
POINTERS_EQUAL(IOWrite, fff.call_history[3]);
LONGS_EQUAL(4, fff.call_history_idx);
}
| null |
240 | cpp | cpputest-starter-project | io.fff.h | tests/io-fff/io.fff.h | null | #include "io.h"
#include "fff.h"
FAKE_VALUE_FUNCTION(IOData, IORead, IOAddress);
FAKE_VOID_FUNCTION(IOWrite, IOAddress, IOData);
| null |
241 | cpp | cpputest-starter-project | io.h | example-include/io.h | null | //- Copyright (c) 2008-20012 James Grenning
//- All rights reserved
//- For use by participants in James' training courses.
#ifndef IO_READ_WRITE_INCLUDED
#define IO_READ_WRITE_INCLUDED
#include <stdint.h>
typedef uint32_t IOAddress;
typedef uint16_t IOData;
IOData IORead(IOAddress offset);
void IOWrite(IOAddress offset, IOData data);
#endif
//Original code thanks to STMicroelectronics.
| null |
242 | cpp | cpputest-starter-project | FooExample.h | example-include/FooExample.h | null | #ifndef FOO_EXAMPLE_H_
#define FOO_EXAMPLE_H_
typedef struct mytype
{
int i;
double x;
} mytype;
void voidfoo0(void);
void voidfoo1(int);
void voidfoo2(int, double);
void voidfoo3(int, double, const char *);
//...
void voidfoo9(int, int, int, int, int, int, int, int, mytype *);
int intfoo0(void);
int intfoo1(int);
int intfoo2(int, int);
int intfoo3(int, int, int);
//...
int intfoo9(int, int, int, int, int, int, int, int, mytype *);
#endif
| null |
243 | cpp | cpputest-starter-project | Example.h | example-include/Example.h | null | #ifndef EXAMPLE_INCLUDED
#define EXAMPLE_INCLUDED
int example(void);
#endif
| null |
244 | cpp | cmake-cpputest | RunAllTests.cpp | tests/RunAllTests.cpp | null | #include "CppUTest/CommandLineTestRunner.h"
IMPORT_TEST_GROUP(LedDriver);
int main(int argc, char** argv)
{
return RUN_ALL_TESTS(argc, argv);
} | null |
245 | cpp | cmake-cpputest | LedDriverTest.cpp | tests/LedDriver/LedDriverTest.cpp | null | /***
* Excerpted from "Test-Driven Development for Embedded C",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt.
* We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/jgade for more book information.
***/
/*- ------------------------------------------------------------------ -*/
/*- Copyright (c) James W. Grenning -- All Rights Reserved -*/
/*- For use by owners of Test-Driven Development for Embedded C, -*/
/*- and attendees of Renaissance Software Consulting, Co. training -*/
/*- classes. -*/
/*- -*/
/*- Available at http://pragprog.com/titles/jgade/ -*/
/*- ISBN 1-934356-62-X, ISBN13 978-1-934356-62-3 -*/
/*- -*/
/*- Authorized users may use this source code in your own -*/
/*- projects, however the source code may not be used to -*/
/*- create training material, courses, books, articles, and -*/
/*- the like. We make no guarantees that this source code is -*/
/*- fit for any purpose. -*/
/*- -*/
/*- www.renaissancesoftware.net [email protected] -*/
/*- ------------------------------------------------------------------ -*/
#include "CppUTest/TestHarness.h"
extern "C"
{
#include "LedDriver.h"
#include "RuntimeErrorStub.h"
}
TEST_GROUP(LedDriver)
{
uint16_t virtualLeds;
void setup()
{
virtualLeds = 0;
LedDriver_Create(&virtualLeds);
}
void teardown()
{
LedDriver_Destroy();
}
};
TEST(LedDriver, LedsAreOffAfterCreate)
{
virtualLeds = 0xffff;
LedDriver_Create(&virtualLeds);
LONGS_EQUAL(0, virtualLeds);
}
TEST(LedDriver, TurnOnLedOne)
{
LedDriver_TurnOn(1);
LONGS_EQUAL(1, virtualLeds);
}
TEST(LedDriver, TurnOffLedOne)
{
LedDriver_TurnOn(1);
LedDriver_TurnOff(1);
LONGS_EQUAL(0, virtualLeds);
}
TEST(LedDriver, TurnOnMultipleLeds)
{
LedDriver_TurnOn(9);
LedDriver_TurnOn(8);
LONGS_EQUAL(0x180, virtualLeds);
}
TEST(LedDriver, TurnOffAnyLed)
{
LedDriver_TurnAllOn();
LedDriver_TurnOff(8);
LONGS_EQUAL(0xff7f, virtualLeds);
}
TEST(LedDriver, LedMemoryIsNotReadable)
{
virtualLeds = 0xffff;
LedDriver_TurnOn(8);
LONGS_EQUAL(0x80, virtualLeds);
}
TEST(LedDriver, UpperAndLowerBounds)
{
LedDriver_TurnOn(1);
LedDriver_TurnOn(16);
LONGS_EQUAL(0x8001, virtualLeds);
}
TEST(LedDriver, OutOfBoundsTurnOnDoesNoHarm)
{
LedDriver_TurnOn(-1);
LedDriver_TurnOn(0);
LedDriver_TurnOn(17);
LedDriver_TurnOn(3141);
LONGS_EQUAL(0, virtualLeds);
}
TEST(LedDriver, OutOfBoundsTurnOffDoesNoHarm)
{
LedDriver_TurnAllOn();
LedDriver_TurnOff(-1);
LedDriver_TurnOff(0);
LedDriver_TurnOff(17);
LedDriver_TurnOff(3141);
LONGS_EQUAL(0xffff, virtualLeds);
}
IGNORE_TEST(LedDriver, OutOfBoundsToDo)
{
// demo shows how to IGNORE a test
}
TEST(LedDriver, OutOfBoundsProducesRuntimeError)
{
LedDriver_TurnOn(-1);
STRCMP_EQUAL("LED Driver: out-of-bounds LED", RuntimeErrorStub_GetLastError());
}
TEST(LedDriver, IsOn)
{
CHECK_EQUAL(FALSE, LedDriver_IsOn(1));
LedDriver_TurnOn(1);
CHECK_EQUAL(TRUE, LedDriver_IsOn(1));
}
TEST(LedDriver, IsOff)
{
CHECK_EQUAL(TRUE, LedDriver_IsOff(12));
LedDriver_TurnOn(12);
CHECK_EQUAL(FALSE, LedDriver_IsOff(12));
}
TEST(LedDriver, OutOfBoundsLedsAreAlwaysOff)
{
CHECK_EQUAL(TRUE, LedDriver_IsOff(0));
CHECK_EQUAL(TRUE, LedDriver_IsOff(17));
CHECK_EQUAL(FALSE, LedDriver_IsOn(0));
CHECK_EQUAL(FALSE, LedDriver_IsOn(17));
}
TEST(LedDriver, AllOn)
{
LedDriver_TurnAllOn();
LONGS_EQUAL(0xffff, virtualLeds);
}
TEST(LedDriver, AllOff)
{
LedDriver_TurnAllOn();
LedDriver_TurnAllOff();
LONGS_EQUAL(0, virtualLeds);
}
| null |
246 | cpp | cmake-cpputest | RuntimeError.h | include/RuntimeError.h | null | /***
* Excerpted from "Test-Driven Development for Embedded C",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt.
* We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/jgade for more book information.
***/
/*- ------------------------------------------------------------------ -*/
/*- Copyright (c) James W. Grenning -- All Rights Reserved -*/
/*- For use by owners of Test-Driven Development for Embedded C, -*/
/*- and attendees of Renaissance Software Consulting, Co. training -*/
/*- classes. -*/
/*- -*/
/*- Available at http://pragprog.com/titles/jgade/ -*/
/*- ISBN 1-934356-62-X, ISBN13 978-1-934356-62-3 -*/
/*- -*/
/*- Authorized users may use this source code in your own -*/
/*- projects, however the source code may not be used to -*/
/*- create training material, courses, books, articles, and -*/
/*- the like. We make no guarantees that this source code is -*/
/*- fit for any purpose. -*/
/*- -*/
/*- www.renaissancesoftware.net [email protected] -*/
/*- ------------------------------------------------------------------ -*/
///
/// At runtime, put an entry in an event log
///
/// @param message the message you want to log
/// @param parameter the param argument number of the function
/// @param file the file to log to
/// @param line the line number for stack trace
///
void RunTimeError(const char * message, int parameter,
const char * file, int line);
/// Code should use this macro instead of the function
#define RUNTIME_ERROR(description, parameter) RuntimeError(description, parameter, __FILE__, __LINE__) | null |
247 | cpp | cmake-cpputest | LedDriver.h | include/LedDriver/LedDriver.h | null | /***
* Excerpted from "Test-Driven Development for Embedded C",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt.
* We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/jgade for more book information.
***/
/*- ------------------------------------------------------------------ -*/
/*- Copyright (c) James W. Grenning -- All Rights Reserved -*/
/*- For use by owners of Test-Driven Development for Embedded C, -*/
/*- and attendees of Renaissance Software Consulting, Co. training -*/
/*- classes. -*/
/*- -*/
/*- Available at http://pragprog.com/titles/jgade/ -*/
/*- ISBN 1-934356-62-X, ISBN13 978-1-934356-62-3 -*/
/*- -*/
/*- Authorized users may use this source code in your own -*/
/*- projects, however the source code may not be used to -*/
/*- create training material, courses, books, articles, and -*/
/*- the like. We make no guarantees that this source code is -*/
/*- fit for any purpose. -*/
/*- -*/
/*- www.renaissancesoftware.net [email protected] -*/
/*- ------------------------------------------------------------------ -*/
#ifndef D_LedDriver_H
#define D_LedDriver_H
#include <stdint.h>
#define TRUE 1
#define FALSE 0
typedef int BOOL;
void LedDriver_Create(uint16_t * ledsAddress);
void LedDriver_Destroy(void);
void LedDriver_TurnOn(int ledNumber);
void LedDriver_TurnOff(int ledNumber);
void LedDriver_TurnAllOn(void);
void LedDriver_TurnAllOff(void);
BOOL LedDriver_IsOn(int ledNumber);
BOOL LedDriver_IsOff(int ledNumber);
#endif /* D_LedDriver_H */ | null |
248 | cpp | cmake-cpputest | RuntimeErrorStub.h | mocks/RuntimeErrorStub.h | null | /***
* Excerpted from "Test-Driven Development for Embedded C",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt.
* We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/jgade for more book information.
***/
/*- ------------------------------------------------------------------ -*/
/*- Copyright (c) James W. Grenning -- All Rights Reserved -*/
/*- For use by owners of Test-Driven Development for Embedded C, -*/
/*- and attendees of Renaissance Software Consulting, Co. training -*/
/*- classes. -*/
/*- -*/
/*- Available at http://pragprog.com/titles/jgade/ -*/
/*- ISBN 1-934356-62-X, ISBN13 978-1-934356-62-3 -*/
/*- -*/
/*- Authorized users may use this source code in your own -*/
/*- projects, however the source code may not be used to -*/
/*- create training material, courses, books, articles, and -*/
/*- the like. We make no guarantees that this source code is -*/
/*- fit for any purpose. -*/
/*- -*/
/*- www.renaissancesoftware.net [email protected] -*/
/*- ------------------------------------------------------------------ -*/
#ifndef D_RuntimeErrorStub_H
#define D_RuntimeErrorStub_H
#include "RuntimeError.h"
///
/// Allows test code to reset the stub
///
void RuntimeErrorStub_Reset(void);
///
/// Retrieve the last error message passed to the stub
/// @return the last error message passed to the stub
///
const char * RuntimeErrorStub_GetLastError(void);
///
/// Retrieve the position of the last parameter that caused the error
/// @return the position of the last parameter that caused the error
///
int RuntimeErrorStub_GetLastParameter(void);
#endif | null |
249 | cpp | firmware_testing | t_math.cpp | code/tests/t_math.cpp | null | /**
* This file has all unit tests for all functions in src/math.c
*/
#include "CppUTest/TestHarness.h"
extern "C" {
#include "common.h"
}
TEST_GROUP(t_math)
{};
/* Test covers addition case */
TEST(t_math, calc_plus)
{
uint8_t ret = calculator('+', 2, 8);
CHECK_EQUAL(10, ret);
}
/* Test covers subtraction case */
TEST(t_math, calc_minus)
{
uint8_t ret = calculator('-', 5, 5);
CHECK_EQUAL(0, ret);
}
/* Tests covers default case */
TEST(t_math, calc_default_mul)
{
uint8_t ret = calculator('*', 1, 5);
CHECK_EQUAL(0, ret);
}
TEST(t_math, calc_default_div)
{
uint8_t ret = calculator('/', 1, 5);
CHECK_EQUAL(0, ret);
}
/* Test covers integer overflow case for addition operations */
TEST(t_math, calc_ret_overflow_add)
{
uint8_t ret = calculator('+', 200, 56);
CHECK_EQUAL(0, ret);
ret = calculator('+', 200, 57);
CHECK_EQUAL(1, ret);
}
/* Test covers integer overflow case for subtraction operations */
TEST(t_math, calc_ret_overflow_minus)
{
uint8_t ret = calculator('-', 0, 1);
CHECK_EQUAL(255, ret);
}
| null |
250 | cpp | firmware_testing | t_other.cpp | code/tests/t_other.cpp | null | /**
* This file has all unit tests for all functions in src/other.c
*/
#include "CppUTest/TestHarness.h"
#include <thread>
extern "C" {
#include <unistd.h>
#include "common.h"
}
extern uint8_t brick_code;
TEST_GROUP(t_other)
{
/* Stuff to do before each test */
void setup()
{
/* Restore original state */
brick_code = 1;
}
/* Stuff to do after each test */
void teardown(){}
};
/**
* Test function that is leaking memory.
* Change memory leak definition CPPUTEST_USE_MEM_LEAK_DETECTION=N to
* CPPUTEST_USE_MEM_LEAK_DETECTION=Y in the MakefileCppUTest.mk file.
* Then Run: make test
*/
TEST(t_other, mem_leak_example)
{
uint8_t ret = mem_leak_function();
CHECK_EQUAL(1, ret);
}
/* Test example calling an ISR */
TEST(t_other, _ISR_)
{
/* Check init conditions */
CHECK_EQUAL(1, brick_code);
ISR();
CHECK_EQUAL(0, brick_code);
}
/**
* Thread that calls ISR function after some microseconds.
*/
void call_ISR(uint32_t usec)
{
usleep(usec);
ISR();
}
/**
* This test example shows how to test specific function that depends
* on a ISR to happen in order to continue it's execution.
*/
TEST(t_other, wait_for_ISR_func)
{
/* Call ISR after 10 usec */
std::thread first (call_ISR, 10);
wait_for_ISR_func();
CHECK_EQUAL(0, brick_code);
first.join();
}
| null |
251 | cpp | firmware_testing | t_main.cpp | code/tests/t_main.cpp | null | /**
* This file has all unit tests for all functions in src/main.c
*/
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
extern "C" {
#include "common.h"
}
TEST_GROUP(t_main)
{
/* Stuff to do before each test */
void setup()
{ }
/* Stuff to do after each test */
void teardown()
{
mock().checkExpectations(); /* Check mock expectations */
mock().clear(); /* Delete metadata */
}
};
/* Test checks correct call of init_device */
TEST(t_main, init_device_call)
{
mock().expectOneCall("i2c_write").withParameter("address", I2C_SLAVE_ADDRESS)
.withParameter("reg_addr", I2C_REG1)
.withParameter("value", I2C_START_DEV)
.andReturnValue(0);
init_device();
}
/**
* Test reconfiguration case, when device does not respond to
* first i2c_read call.
*/
TEST(t_main, check_reconfigure_behaviour)
{
/**
* Expect two i2c_write calls with the same parameters:
* - One is done at the beggining of main function by the init_device();
* - Another is done in the else condition also by init_device();
*/
mock().expectNCalls(2, "i2c_write")
.withParameter("address", I2C_SLAVE_ADDRESS)
.withParameter("reg_addr", I2C_REG1)
.withParameter("value", I2C_START_DEV)
.andReturnValue(0);
/* Expect one i2c_read call and return 0 */
mock().expectOneCall("i2c_read")
.withParameter("address", I2C_SLAVE_ADDRESS)
.withParameter("reg_addr", I2C_REG2)
.andReturnValue(0); /* Will force firmware to enter else condition */
/* Run main firmware function */
uint32_t ret = test_main();
CHECK_EQUAL(0, ret);
}
/**
* Test device behaviour when it's ready to be read by the firmware.
*/
TEST(t_main, check_device_ready)
{
/* Expect one i2w_write call. Ignore parameters */
mock().expectOneCall("i2c_write")
.ignoreOtherParameters()
.andReturnValue(0);
/* Expect i2c_read call and return DEVICE_READYE */
mock().expectOneCall("i2c_read")
.withParameter("address", I2C_SLAVE_ADDRESS)
.withParameter("reg_addr", I2C_REG2)
.andReturnValue(DEVICE_READY);
/* Expect second i2c_read call with reg_addr of I2C_REG3 */
mock().expectOneCall("i2c_read")
.withParameter("address", I2C_SLAVE_ADDRESS)
.withParameter("reg_addr", I2C_REG3)
.andReturnValue(0);
/* Run main firmware function */
uint32_t ret = test_main();
CHECK_EQUAL(0, ret);
}
| null |
252 | cpp | firmware_testing | main.cpp | code/tests/main.cpp | null | /**
* This file is the main test file used by the CppUTest framework.
*/
#include "CppUTest/CommandLineTestRunner.h"
int main(int ac, char** av)
{
return CommandLineTestRunner::RunAllTests(ac, av);
}
| null |
253 | cpp | firmware_testing | i2c_mock.cpp | code/tests/mocks/i2c_mock.cpp | null | /**
* This file contains mock functions of src/hw/i2c.c file. Mocking allows us to
* use these functions in the test framework to test firmware with hardware
* dependencies and define which execution path we want to take.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
extern "C" {
#include "common.h"
}
/**
* I2c read mock function
*/
uint8_t i2c_read(uint8_t address, uint8_t reg_addr)
{
return (uint8_t)
mock().actualCall("i2c_read")
.withParameter("address", address)
.withParameter("reg_addr", reg_addr)
.returnUnsignedIntValueOrDefault(0);
}
/**
* I2c read write function
*/
uint8_t i2c_write(uint8_t address, uint8_t reg_addr, uint8_t value)
{
return (uint8_t)
mock().actualCall("i2c_write")
.withParameter("address", address)
.withParameter("reg_addr", reg_addr)
.withParameter("value", value)
.returnUnsignedIntValueOrDefault(0);
}
| null |
254 | cpp | firmware_testing | common.h | code/src/include/common.h | null |
#ifndef _COMMON_H_
#define _COMMON_H_
#include <inttypes.h>
uint8_t calculator(char op, uint8_t val1, uint8_t val2);
/* I2C Hardware functions and slave registers */
#define I2C_SLAVE_ADDRESS 0x30 /* I2C slave address */
#define I2C_REG1 0x0A /* Register 1 offset */
#define I2C_REG2 0x0B /* Register 2 offset */
#define I2C_REG3 0x0C /* Register 3 offset */
#define I2C_START_DEV 0x01 /* Slave init value */
#define DEVICE_READY 0x10 /* Device ready */
uint8_t i2c_read(uint8_t address, uint8_t reg_addr);
uint8_t i2c_write(uint8_t address, uint8_t reg_addr, uint8_t value);
/* Other Examples */
uint8_t mem_leak_function(void);
void ISR(void);
void wait_for_ISR_func(void);
#ifdef TEST_MAIN
/**
* These functions are only used in the CppUTest framework so that we
* can to test them.
*/
void init_device(void);
uint32_t test_main(void);
#endif
#endif
| null |
255 | cpp | blalor-cpputest | CommandLineArgumentsTest.cpp | tests/CommandLineArgumentsTest.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/TestRegistry.h"
class OptionsPlugin: public TestPlugin
{
public:
OptionsPlugin(const SimpleString& name) :
TestPlugin(name)
{
}
~OptionsPlugin()
{
}
bool parseArguments(int /*ac*/, const char** /*av*/, int /*index*/)
{
return true;
}
};
TEST_GROUP(CommandLineArguments)
{
CommandLineArguments* args;
OptionsPlugin* plugin;
void setup()
{
plugin = new OptionsPlugin("options");
}
void teardown()
{
delete args;
delete plugin;
}
bool newArgumentParser(int argc, const char** argv)
{
args = new CommandLineArguments(argc, argv);
return args->parse(plugin);
}
};
TEST(CommandLineArguments, Create)
{
}
TEST(CommandLineArguments, verboseSetMultipleParameters)
{
const char* argv[] = { "tests.exe", "-v" };
CHECK(newArgumentParser(2, argv));
CHECK(args->isVerbose());
}
TEST(CommandLineArguments, repeatSet)
{
int argc = 2;
const char* argv[] = { "tests.exe", "-r3" };
CHECK(newArgumentParser(argc, argv));
LONGS_EQUAL(3, args->getRepeatCount());
}
TEST(CommandLineArguments, repeatSetDifferentParameter)
{
int argc = 3;
const char* argv[] = { "tests.exe", "-r", "4" };
CHECK(newArgumentParser(argc, argv));
LONGS_EQUAL(4, args->getRepeatCount());
}
TEST(CommandLineArguments, repeatSetDefaultsToTwo)
{
int argc = 2;
const char* argv[] = { "tests.exe", "-r" };
CHECK(newArgumentParser(argc, argv));
LONGS_EQUAL(2, args->getRepeatCount());
}
TEST(CommandLineArguments, setGroupFilter)
{
int argc = 3;
const char* argv[] = { "tests.exe", "-g", "group" };
CHECK(newArgumentParser(argc, argv));
STRCMP_EQUAL("group", args->getGroupFilter().asCharString());
}
TEST(CommandLineArguments, setGroupFilterSameParameter)
{
int argc = 2;
const char* argv[] = { "tests.exe", "-ggroup" };
CHECK(newArgumentParser(argc, argv));
STRCMP_EQUAL("group", args->getGroupFilter().asCharString());
}
TEST(CommandLineArguments, setNameFilter)
{
int argc = 3;
const char* argv[] = { "tests.exe", "-n", "name" };
CHECK(newArgumentParser(argc, argv));
STRCMP_EQUAL("name", args->getNameFilter().asCharString());
}
TEST(CommandLineArguments, setNameFilterSameParameter)
{
int argc = 2;
const char* argv[] = { "tests.exe", "-nname" };
CHECK(newArgumentParser(argc, argv));
STRCMP_EQUAL("name", args->getNameFilter().asCharString());
}
TEST(CommandLineArguments, setNormalOutput)
{
int argc = 2;
const char* argv[] = { "tests.exe", "-onormal" };
CHECK(newArgumentParser(argc, argv));
CHECK(args->isEclipseOutput());
}
TEST(CommandLineArguments, setEclsipeOutput)
{
int argc = 2;
const char* argv[] = { "tests.exe", "-oeclipse" };
CHECK(newArgumentParser(argc, argv));
CHECK(args->isEclipseOutput());
}
TEST(CommandLineArguments, setNormalOutputDifferentParameter)
{
int argc = 3;
const char* argv[] = { "tests.exe", "-o", "normal" };
CHECK(newArgumentParser(argc, argv));
CHECK(args->isEclipseOutput());
}
TEST(CommandLineArguments, setJUnitOutputDifferentParameter)
{
int argc = 3;
const char* argv[] = { "tests.exe", "-o", "junit" };
CHECK(newArgumentParser(argc, argv));
CHECK(args->isJUnitOutput());
}
TEST(CommandLineArguments, setOutputToGarbage)
{
int argc = 3;
const char* argv[] = { "tests.exe", "-o", "garbage" };
CHECK(!newArgumentParser(argc, argv));
}
TEST(CommandLineArguments, weirdParamatersPrintsUsageAndReturnsFalse)
{
int argc = 2;
const char* argv[] = { "tests.exe", "-SomethingWeird" };
CHECK(!newArgumentParser(argc, argv));
STRCMP_EQUAL("usage [-v] [-r#] [-g groupName] [-n testName] [-o{normal, junit}]\n",
args->usage());
}
TEST(CommandLineArguments, pluginKnowsOption)
{
int argc = 2;
const char* argv[] = { "tests.exe", "-pPluginOption" };
TestRegistry::getCurrentRegistry()->installPlugin(plugin);
CHECK(newArgumentParser(argc, argv));
TestRegistry::getCurrentRegistry()->removePluginByName("options");
}
TEST(CommandLineArguments, checkDefaultArguments)
{
int argc = 1;
const char* argv[] = { "tests.exe" };
CHECK(newArgumentParser(argc, argv));
CHECK(!args->isVerbose());
LONGS_EQUAL(1, args->getRepeatCount());
STRCMP_EQUAL("", args->getGroupFilter().asCharString());
STRCMP_EQUAL("", args->getNameFilter().asCharString());
CHECK(args->isEclipseOutput());
}
| null |
256 | cpp | blalor-cpputest | AllTests.cpp | tests/AllTests.cpp | null | /*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/CommandLineTestRunner.h"
int main(int ac, const char** av)
{
/* These checks are here to make sure assertions outside test runs don't crash */
CHECK(true);
LONGS_EQUAL(1, 1);
return CommandLineTestRunner::RunAllTests(ac, av);
}
| null |
257 | cpp | blalor-cpputest | TestRegistryTest.cpp | tests/TestRegistryTest.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/TestOutput.h"
namespace
{
void stub()
{
}
const int testLineNumber = 1;
}
class MockTest: public Utest
{
public:
MockTest(const char* group = "Group") :
Utest(group, "Name", "File", testLineNumber), hasRun_(false)
{
}
void testBody()
{
hasRun_ = true;
}
;
bool hasRun_;
};
class MockTestResult: public TestResult
{
public:
int countTestsStarted;
int countTestsEnded;
int countCurrentTestStarted;
int countCurrentTestEnded;
int countCurrentGroupStarted;
int countCurrentGroupEnded;
MockTestResult(TestOutput& p) :
TestResult(p)
{
resetCount();
}
;
virtual ~MockTestResult()
{
}
;
void resetCount()
{
countTestsStarted = 0;
countTestsEnded = 0;
countCurrentTestStarted = 0;
countCurrentTestEnded = 0;
countCurrentGroupStarted = 0;
countCurrentGroupEnded = 0;
}
virtual void testsStarted()
{
countTestsStarted++;
}
virtual void testsEnded()
{
countTestsEnded++;
}
virtual void currentTestStarted(Utest* /*test*/)
{
countCurrentTestStarted++;
}
virtual void currentTestEnded(Utest* /*test*/)
{
countCurrentTestEnded++;
}
virtual void currentGroupStarted(Utest* /*test*/)
{
countCurrentGroupStarted++;
}
virtual void currentGroupEnded(Utest* /*test*/)
{
countCurrentGroupEnded++;
}
};
TEST_GROUP(TestRegistry)
{
TestRegistry* myRegistry;
StringBufferTestOutput* output;
MockTest* test1;
MockTest* test2;
MockTest* test3;
TestResult *result;
MockTestResult *mockResult;
void setup()
{
output = new StringBufferTestOutput();
mockResult = new MockTestResult(*output);
result = mockResult;
test1 = new MockTest();
test2 = new MockTest();
test3 = new MockTest("group2");
myRegistry = new TestRegistry();
myRegistry->setCurrentRegistry(myRegistry);
}
void teardown()
{
myRegistry->setCurrentRegistry(0);
delete myRegistry;
delete test1;
delete test2;
delete test3;
delete result;
delete output;
}
};
TEST(TestRegistry, registryMyRegistryAndReset)
{
CHECK(myRegistry->getCurrentRegistry() == myRegistry);
}
TEST(TestRegistry, emptyRegistryIsEmpty)
{
CHECK(myRegistry->countTests() == 0);
}
TEST(TestRegistry, addOneTestIsNotEmpty)
{
myRegistry->addTest(test1);
CHECK(myRegistry->countTests() == 1);
}
TEST(TestRegistry, addOneTwoTests)
{
myRegistry->addTest(test1);
myRegistry->addTest(test2);
CHECK(myRegistry->countTests() == 2);
}
TEST(TestRegistry, runTwoTests)
{
myRegistry->addTest(test1);
myRegistry->addTest(test2);
CHECK(!test1->hasRun_);
CHECK(!test2->hasRun_);
myRegistry->runAllTests(*result);
CHECK(test1->hasRun_);
CHECK(test2->hasRun_);
}
TEST(TestRegistry, runTwoTestsCheckResultFunctionsCalled)
{
myRegistry->addTest(test1);
myRegistry->addTest(test2);
myRegistry->runAllTests(*result);
LONGS_EQUAL(1, mockResult->countTestsStarted);
LONGS_EQUAL(1, mockResult->countTestsEnded);
LONGS_EQUAL(1, mockResult->countCurrentGroupStarted);
LONGS_EQUAL(1, mockResult->countCurrentGroupEnded);
LONGS_EQUAL(2, mockResult->countCurrentTestStarted);
LONGS_EQUAL(2, mockResult->countCurrentTestEnded);
}
TEST(TestRegistry, runThreeTestsandTwoGroupsCheckResultFunctionsCalled)
{
myRegistry->addTest(test1);
myRegistry->addTest(test2);
myRegistry->addTest(test3);
myRegistry->runAllTests(*result);
LONGS_EQUAL(2, mockResult->countCurrentGroupStarted);
LONGS_EQUAL(2, mockResult->countCurrentGroupEnded);
LONGS_EQUAL(3, mockResult->countCurrentTestStarted);
LONGS_EQUAL(3, mockResult->countCurrentTestEnded);
}
TEST(TestRegistry, unDoTest)
{
myRegistry->addTest(test1);
CHECK(myRegistry->countTests() == 1);
myRegistry->unDoLastAddTest();
CHECK(myRegistry->countTests() == 0);
}
TEST(TestRegistry, unDoButNoTest)
{
CHECK(myRegistry->countTests() == 0);
myRegistry->unDoLastAddTest();
CHECK(myRegistry->countTests() == 0);
}
TEST(TestRegistry, reallyUndoLastTest)
{
myRegistry->addTest(test1);
myRegistry->addTest(test2);
CHECK(myRegistry->countTests() == 2);
myRegistry->unDoLastAddTest();
CHECK(myRegistry->countTests() == 1);
myRegistry->runAllTests(*result);
CHECK(test1->hasRun_);
CHECK(!test2->hasRun_);
}
| null |
258 | cpp | blalor-cpputest | SimpleStringTest.cpp | tests/SimpleStringTest.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"
TEST_GROUP(SimpleString)
{
};
TEST(SimpleString, defaultAllocatorIsNewArrayAllocator)
{
POINTERS_EQUAL(MemoryLeakAllocator::getCurrentNewArrayAllocator(), SimpleString::getStringAllocator());
}
class MyOwnStringAllocator : public StandardMallocAllocator
{
public:
MyOwnStringAllocator() : memoryWasAllocated(false) {};
virtual ~MyOwnStringAllocator() {};
bool memoryWasAllocated;
char* alloc_memory(size_t size, const char* file, int line)
{
memoryWasAllocated = true;
return StandardMallocAllocator::alloc_memory(size, file, line);
}
};
TEST(SimpleString, allocatorForSimpleStringCanBeReplaced)
{
MyOwnStringAllocator myOwnAllocator;
SimpleString::setStringAllocator(&myOwnAllocator);
SimpleString simpleString;
CHECK(myOwnAllocator.memoryWasAllocated);
SimpleString::setStringAllocator(NULL);
}
TEST(SimpleString, CreateSequence)
{
SimpleString expected("hellohello");
SimpleString actual("hello", 2);
CHECK_EQUAL(expected, actual);
}
TEST(SimpleString, CreateSequenceOfZero)
{
SimpleString expected("");
SimpleString actual("hello", 0);
CHECK_EQUAL(expected, actual);
}
TEST(SimpleString, Copy)
{
SimpleString s1("hello");
SimpleString s2(s1);
CHECK_EQUAL(s1, s2);
}
TEST(SimpleString, Assignment)
{
SimpleString s1("hello");
SimpleString s2("goodbye");
s2 = s1;
CHECK_EQUAL(s1, s2);
}
TEST(SimpleString, Equality)
{
SimpleString s1("hello");
SimpleString s2("hello");
CHECK(s1 == s2);
}
TEST(SimpleString, InEquality)
{
SimpleString s1("hello");
SimpleString s2("goodbye");
CHECK(s1 != s2);
}
TEST(SimpleString, CompareNoCaseWithoutCase)
{
SimpleString s1("hello");
SimpleString s2("hello");
CHECK(s1.equalsNoCase(s2));
}
TEST(SimpleString, CompareNoCaseWithCase)
{
SimpleString s1("hello");
SimpleString s2("HELLO");
CHECK(s1.equalsNoCase(s2));
}
TEST(SimpleString, CompareNoCaseWithCaseNotEqual)
{
SimpleString s1("hello");
SimpleString s2("WORLD");
CHECK(!s1.equalsNoCase(s2));
}
TEST(SimpleString, asCharString)
{
SimpleString s1("hello");
STRCMP_EQUAL("hello", s1.asCharString());
}
TEST(SimpleString, Size)
{
SimpleString s1("hello!");
LONGS_EQUAL(6, s1.size());
}
TEST(SimpleString, toLower)
{
SimpleString s1("AbCdEfG");
SimpleString s2(s1.toLower());
STRCMP_EQUAL("abcdefg", s2.asCharString());
STRCMP_EQUAL("AbCdEfG", s1.asCharString());
}
TEST(SimpleString, Addition)
{
SimpleString s1("hello!");
SimpleString s2("goodbye!");
SimpleString s3("hello!goodbye!");
SimpleString s4;
s4 = s1 + s2;
CHECK_EQUAL(s3, s4);
}
TEST(SimpleString, Concatenation)
{
SimpleString s1("hello!");
SimpleString s2("goodbye!");
SimpleString s3("hello!goodbye!");
SimpleString s4;
s4 += s1;
s4 += s2;
CHECK_EQUAL(s3, s4);
SimpleString s5("hello!goodbye!hello!goodbye!");
s4 += s4;
CHECK_EQUAL(s5, s4);
}
TEST(SimpleString, Contains)
{
SimpleString s("hello!");
SimpleString empty("");
SimpleString beginning("hello");
SimpleString end("lo!");
SimpleString mid("l");
SimpleString notPartOfString("xxxx");
CHECK(s.contains(empty));
CHECK(s.contains(beginning));
CHECK(s.contains(end));
CHECK(s.contains(mid));
CHECK(!s.contains(notPartOfString));
CHECK(empty.contains(empty));
CHECK(!empty.contains(s));
}
TEST(SimpleString, startsWith)
{
SimpleString hi("Hi you!");
SimpleString part("Hi");
SimpleString diff("Hrrm Hi you! ffdsfd");
CHECK(hi.startsWith(part));
CHECK(!part.startsWith(hi));
CHECK(!diff.startsWith(hi));
}
TEST(SimpleString, split)
{
SimpleString hi("hello\nworld\nhow\ndo\nyou\ndo\n\n");
SimpleStringCollection collection;
hi.split("\n", collection);
LONGS_EQUAL(7, collection.size());
STRCMP_EQUAL("hello\n", collection[0].asCharString());
STRCMP_EQUAL("world\n", collection[1].asCharString());
STRCMP_EQUAL("how\n", collection[2].asCharString());
STRCMP_EQUAL("do\n", collection[3].asCharString());
STRCMP_EQUAL("you\n", collection[4].asCharString());
STRCMP_EQUAL("do\n", collection[5].asCharString());
STRCMP_EQUAL("\n", collection[6].asCharString());
}
TEST(SimpleString, splitNoTokenOnTheEnd)
{
SimpleString string("Bah Yah oops");
SimpleStringCollection collection;
string.split(" ", collection);
LONGS_EQUAL(3, collection.size());
STRCMP_EQUAL("Bah ", collection[0].asCharString());
STRCMP_EQUAL("Yah ", collection[1].asCharString());
STRCMP_EQUAL("oops", collection[2].asCharString());
}
TEST(SimpleString, count)
{
SimpleString str("ha ha ha ha");
LONGS_EQUAL(4, str.count("ha"));
}
TEST(SimpleString, countTogether)
{
SimpleString str("hahahaha");
LONGS_EQUAL(4, str.count("ha"));
}
TEST(SimpleString, endsWith)
{
SimpleString str("Hello World");
CHECK(str.endsWith("World"));
CHECK(!str.endsWith("Worl"));
CHECK(!str.endsWith("Hello"));
SimpleString str2("ah");
CHECK(str2.endsWith("ah"));
CHECK(!str2.endsWith("baah"));
SimpleString str3("");
CHECK(!str3.endsWith("baah"));
SimpleString str4("ha ha ha ha");
CHECK(str4.endsWith("ha"));
}
TEST(SimpleString, replaceCharWithChar)
{
SimpleString str("abcabcabca");
str.replace('a', 'b');
STRCMP_EQUAL("bbcbbcbbcb", str.asCharString());
}
TEST(SimpleString, replaceStringWithString)
{
SimpleString str("boo baa boo baa boo");
str.replace("boo", "boohoo");
STRCMP_EQUAL("boohoo baa boohoo baa boohoo", str.asCharString());
}
TEST(SimpleString, subStringFromEmptyString)
{
SimpleString str("");
STRCMP_EQUAL("", str.subString(0, 1).asCharString());
}
TEST(SimpleString, subStringFromSmallString)
{
SimpleString str("H");
STRCMP_EQUAL("H", str.subString(0, 1).asCharString());
}
TEST(SimpleString, subStringFromPos0)
{
SimpleString str("Hello World");
STRCMP_EQUAL("Hello", str.subString(0, 5).asCharString());
}
TEST(SimpleString, subStringFromPos1)
{
SimpleString str("Hello World");
STRCMP_EQUAL("ello ", str.subString(1, 5).asCharString());
}
TEST(SimpleString, subStringFromPos5WithAmountLargerThanString)
{
SimpleString str("Hello World");
STRCMP_EQUAL("World", str.subString(6, 10).asCharString());
}
TEST(SimpleString, subStringBeginPosOutOfBounds)
{
SimpleString str("Hello World");
STRCMP_EQUAL("", str.subString(13, 5).asCharString());
}
TEST(SimpleString, copyInBufferNormal)
{
SimpleString str("Hello World");
size_t bufferSize = str.size()+1;
char* buffer = (char*) malloc(bufferSize);
str.copyToBuffer(buffer, bufferSize);
STRCMP_EQUAL(str.asCharString(), buffer);
free(buffer);
}
TEST(SimpleString, copyInBufferWithEmptyBuffer)
{
SimpleString str("Hello World");
char* buffer= NULL;
str.copyToBuffer(buffer, 0);
POINTERS_EQUAL(NULL, buffer);
}
TEST(SimpleString, copyInBufferWithBiggerBufferThanNeeded)
{
SimpleString str("Hello");
int bufferSize = 20;
char* buffer= (char*) malloc(bufferSize);
str.copyToBuffer(buffer, bufferSize);
STRCMP_EQUAL(str.asCharString(), buffer);
free(buffer);
}
TEST(SimpleString, ContainsNull)
{
SimpleString s(0);
CHECK(!s.contains("something"));
}
TEST(SimpleString, NULLReportsNullString)
{
STRCMP_EQUAL("(null)", StringFromOrNull((char*) NULL).asCharString());
}
TEST(SimpleString, Characters)
{
SimpleString s(StringFrom('a'));
SimpleString s2(StringFrom('a'));
CHECK(s == s2);
}
TEST(SimpleString, Doubles)
{
SimpleString s(StringFrom(1.2));
STRCMP_EQUAL("1.200000", s.asCharString());
s = StringFrom(1.2, 2);
STRCMP_EQUAL("1.20", s.asCharString());
}
TEST(SimpleString, HexStrings)
{
SimpleString h1 = HexStringFrom(0xffff);
STRCMP_EQUAL("ffff", h1.asCharString());
}
TEST(SimpleString, StringFromFormat)
{
SimpleString h1 = StringFromFormat("%s %s! %d", "Hello", "World", 2009);
STRCMP_EQUAL("Hello World! 2009", h1.asCharString());
}
TEST(SimpleString, StringFromFormatLarge)
{
const char* s = "ThisIsAPrettyLargeStringAndIfWeAddThisManyTimesToABufferItWillbeFull";
SimpleString h1 = StringFromFormat("%s%s%s%s%s%s%s%s%s%s", s, s, s, s, s, s, s, s, s, s);
LONGS_EQUAL(10, h1.count(s));
}
static int WrappedUpVSNPrintf(char* buf, int n, const char* format, ...)
{
va_list arguments;
va_start(arguments, format);
int result = PlatformSpecificVSNprintf(buf, n, format, arguments);
va_end(arguments);
return result;
}
TEST(SimpleString, PlatformSpecificSprintf_fits)
{
char buf[10];
int count = WrappedUpVSNPrintf(buf, sizeof(buf), "%s", "12345");
STRCMP_EQUAL("12345", buf);
LONGS_EQUAL(5, count);
}
TEST(SimpleString, PlatformSpecificSprintf_doesNotFit)
{
char buf[10];
int count = WrappedUpVSNPrintf(buf, sizeof(buf), "%s", "12345678901");
STRCMP_EQUAL("123456789", buf);
LONGS_EQUAL(11, count);
}
TEST(SimpleString, PadStringsToSameLengthString1Larger)
{
SimpleString str1("1");
SimpleString str2("222");
SimpleString::padStringsToSameLength(str1, str2, '4');
STRCMP_EQUAL("441", str1.asCharString());
STRCMP_EQUAL("222", str2.asCharString());
}
TEST(SimpleString, PadStringsToSameLengthString2Larger)
{
SimpleString str1(" ");
SimpleString str2("");
SimpleString::padStringsToSameLength(str1, str2, ' ');
STRCMP_EQUAL(" ", str1.asCharString());
STRCMP_EQUAL(" ", str2.asCharString());
}
TEST(SimpleString, PadStringsToSameLengthWithSameLengthStrings)
{
SimpleString str1("123");
SimpleString str2("123");
SimpleString::padStringsToSameLength(str1, str2, ' ');
STRCMP_EQUAL("123", str1.asCharString());
STRCMP_EQUAL("123", str2.asCharString());
}
TEST(SimpleString, NullParameters2)
{
SimpleString* arr = new SimpleString[100];
delete[] arr;
}
TEST(SimpleString, CollectionMultipleAllocateNoLeaksMemory)
{
SimpleStringCollection col;
col.allocate(5);
col.allocate(5);
// CHECK no memory leak
}
TEST(SimpleString, CollectionReadOutOfBoundsReturnsEmptyString)
{
SimpleStringCollection col;
col.allocate(3);
STRCMP_EQUAL("", col[3].asCharString());
}
TEST(SimpleString, CollectionWritingToEmptyString)
{
SimpleStringCollection col;
col.allocate(3);
col[3] = SimpleString("HAH");
STRCMP_EQUAL("", col[3].asCharString());
}
#if CPPUTEST_USE_STD_CPP_LIB
TEST(SimpleString, fromStdString)
{
std::string s("hello");
SimpleString s1(StringFrom(s));
STRCMP_EQUAL("hello", s1.asCharString());
}
TEST(SimpleString, CHECK_EQUAL_Uint32_t)
{
uint32_t i = 0xffffffff;
CHECK_EQUAL(i, i);
}
TEST(SimpleString, CHECK_EQUAL_Uint16_t)
{
uint16_t i = 0xffff;
CHECK_EQUAL(i, i);
}
TEST(SimpleString, CHECK_EQUAL_Uint8_t)
{
uint8_t i = 0xff;
CHECK_EQUAL(i, i);
}
TEST(SimpleString, Uint32_t)
{
uint32_t i = 0xffffffff;
SimpleString result = StringFrom(i);
CHECK_EQUAL("4294967295 (0xffffffff)", result);
}
TEST(SimpleString, Uint16_t)
{
uint16_t i = 0xffff;
SimpleString result = StringFrom(i);
CHECK_EQUAL("65535 (0xffff)", result);
}
TEST(SimpleString, Uint8_t)
{
uint8_t i = 0xff;
SimpleString result = StringFrom(i);
CHECK_EQUAL("255 (0xff)", result);
}
#endif
| null |
259 | cpp | blalor-cpputest | MemoryLeakAllocatorTest.cpp | tests/MemoryLeakAllocatorTest.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"
TEST_GROUP(MemoryLeakAllocatorTest)
{
MemoryLeakAllocator* allocator;
void teardown()
{
if (allocator) delete allocator;
}
};
TEST(MemoryLeakAllocatorTest, SetCurrentNewAllocator)
{
allocator = new StandardNewAllocator;
MemoryLeakAllocator::setCurrentNewAllocator(allocator);
POINTERS_EQUAL(allocator, MemoryLeakAllocator::getCurrentNewAllocator());
MemoryLeakAllocator::setCurrentNewAllocatorToDefault();
POINTERS_EQUAL(StandardNewAllocator::defaultAllocator(), MemoryLeakAllocator::getCurrentNewAllocator());
}
TEST(MemoryLeakAllocatorTest, SetCurrentNewArrayAllocator)
{
allocator = new StandardNewArrayAllocator;
MemoryLeakAllocator::setCurrentNewArrayAllocator(allocator);
POINTERS_EQUAL(allocator, MemoryLeakAllocator::getCurrentNewArrayAllocator());
MemoryLeakAllocator::setCurrentNewArrayAllocatorToDefault();
POINTERS_EQUAL(StandardNewArrayAllocator::defaultAllocator(), MemoryLeakAllocator::getCurrentNewArrayAllocator());
}
TEST(MemoryLeakAllocatorTest, SetCurrentMallocAllocator)
{
allocator = new StandardMallocAllocator;
MemoryLeakAllocator::setCurrentMallocAllocator(allocator);
POINTERS_EQUAL(allocator, MemoryLeakAllocator::getCurrentMallocAllocator());
MemoryLeakAllocator::setCurrentMallocAllocatorToDefault();
POINTERS_EQUAL(StandardMallocAllocator::defaultAllocator(), MemoryLeakAllocator::getCurrentMallocAllocator());
}
TEST(MemoryLeakAllocatorTest, MallocAllocation)
{
allocator = new StandardMallocAllocator;
allocator->free_memory(allocator->alloc_memory(100, "file", 1), "file", 1);
}
TEST(MemoryLeakAllocatorTest, MallocNames)
{
allocator = new StandardMallocAllocator;
STRCMP_EQUAL("Standard Malloc Allocator", allocator->name());
STRCMP_EQUAL("malloc", allocator->alloc_name());
STRCMP_EQUAL("free", allocator->free_name());
}
TEST(MemoryLeakAllocatorTest, NewAllocation)
{
allocator = new StandardNewAllocator;
allocator->free_memory(allocator->alloc_memory(100, "file", 1), "file", 1);
}
TEST(MemoryLeakAllocatorTest, NewNames)
{
allocator = new StandardNewAllocator;
STRCMP_EQUAL("Standard New Allocator", allocator->name());
STRCMP_EQUAL("new", allocator->alloc_name());
STRCMP_EQUAL("delete", allocator->free_name());
}
TEST(MemoryLeakAllocatorTest, NewArrayAllocation)
{
allocator = new StandardNewArrayAllocator;
allocator->free_memory(allocator->alloc_memory(100, "file", 1), "file", 1);
}
TEST(MemoryLeakAllocatorTest, NewArrayNames)
{
allocator = new StandardNewArrayAllocator;
STRCMP_EQUAL("Standard New [] Allocator", allocator->name());
STRCMP_EQUAL("new []", allocator->alloc_name());
STRCMP_EQUAL("delete []", allocator->free_name());
}
TEST(MemoryLeakAllocatorTest, NullUnknownAllocation)
{
allocator = new NullUnknownAllocator;
allocator->free_memory(allocator->alloc_memory(100, "file", 1), "file", 1);
}
TEST(MemoryLeakAllocatorTest, NullUnknownNames)
{
allocator = new NullUnknownAllocator;
STRCMP_EQUAL("Null Allocator", allocator->name());
STRCMP_EQUAL("unknown", allocator->alloc_name());
STRCMP_EQUAL("unknown", allocator->free_name());
}
| null |
260 | cpp | blalor-cpputest | CommandLineTestRunnerTest.cpp | tests/CommandLineTestRunnerTest.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/TestRegistry.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTest/TestPlugin.h"
TEST_GROUP(CommandLineTestRunner)
{
void setup()
{
}
void teardown()
{
}
};
IGNORE_TEST(CommandLineTestRunner, HmmmmWhatToWrite)
{
//TODO: maybe some tests are in order
}
| null |
261 | cpp | blalor-cpputest | MemoryLeakOperatorOverloadsTest.cpp | tests/MemoryLeakOperatorOverloadsTest.cpp | null | #include "CppUTest/TestHarness.h"
#include "CppUTest/MemoryLeakAllocator.h"
#include "CppUTest/MemoryLeakDetector.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTest/PlatformSpecificFunctions.h"
#include "AllocationInCppFile.h"
extern "C"
{
#include "AllocationInCFile.h"
}
TEST_GROUP(BasicBehavior)
{
};
TEST(BasicBehavior, CanDeleteNullPointers)
{
delete (char*) NULL;
delete [] (char*) NULL;
}
#ifndef CPPUTEST_MEM_LEAK_DETECTION_DISABLED
TEST(BasicBehavior, deleteArrayInvalidatesMemory)
{
unsigned char* memory = new unsigned char[10];
PlatformSpecificMemset(memory, 0xAB, 10);
delete [] memory;
CHECK(memory[5] != 0xCB);
}
TEST(BasicBehavior, deleteInvalidatesMemory)
{
unsigned char* memory = new unsigned char;
*memory = 0xAD;
delete memory;
CHECK(*memory != 0xAD);
}
#endif
TEST(BasicBehavior, freeInvalidatesMemory)
{
unsigned char* memory = (unsigned char*) cpputest_malloc(sizeof(unsigned char));
*memory = 0xAD;
cpputest_free(memory);
CHECK(*memory != 0xAD);
}
TEST_GROUP(MemoryLeakOverridesToBeUsedInProductionCode)
{
MemoryLeakDetector* memLeakDetector;
void setup()
{
memLeakDetector = MemoryLeakWarningPlugin::getGlobalDetector();
}
};
TEST(MemoryLeakOverridesToBeUsedInProductionCode, UseNativeMallocByTemporarlySwitchingOffMalloc)
{
int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking);
#if CPPUTEST_USE_MALLOC_MACROS
#undef malloc
#undef free
#endif
void* memory = malloc(10);
LONGS_EQUAL(memLeaks, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking));
free (memory);
#if CPPUTEST_USE_MALLOC_MACROS
#include "CppUTest/MemoryLeakDetectorMallocMacros.h"
#endif
}
/* TEST... allowing for a new overload in a class */
class NewDummyClass
{
public:
#if CPPUTEST_USE_NEW_MACROS
#undef new
#endif
void* operator new (size_t size, int additional)
#if CPPUTEST_USE_NEW_MACROS
#include "CppUTest/MemoryLeakDetectorNewMacros.h"
#endif
{
return malloc(size * additional);
}
};
TEST(MemoryLeakOverridesToBeUsedInProductionCode, UseNativeNewByTemporarlySwitchingOffNew)
{
#if CPPUTEST_USE_NEW_MACROS
#undef new
#undef delete
#endif
char* memory = new char[10];
delete [] memory;
#if CPPUTEST_USE_NEW_MACROS
#include "CppUTest/MemoryLeakDetectorNewMacros.h"
#endif
}
#if CPPUTEST_USE_MEM_LEAK_DETECTION
TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewMacroOverloadViaIncludeFileWorks)
{
char* leak = newAllocation();
STRCMP_NOCASE_CONTAINS("AllocationInCppFile.cpp", memLeakDetector->report(mem_leak_period_checking));
delete leak;
}
TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewArrayMacroOverloadViaIncludeFileWorks)
{
char* leak = newArrayAllocation();
STRCMP_NOCASE_CONTAINS("AllocationInCppFile.cpp", memLeakDetector->report(mem_leak_period_checking));
delete[] leak;
}
TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocOverrideWorks)
{
char* leak = mallocAllocation();
STRCMP_NOCASE_CONTAINS("AllocationInCFile.c", memLeakDetector->report(mem_leak_period_checking));
freeAllocation(leak);
}
TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocWithButFreeWithoutLeakDetectionDoesntCrash)
{
char* leak = mallocAllocation();
freeAllocationWithoutMacro(leak);
STRCMP_CONTAINS("Memory leak reports about malloc and free can be caused", memLeakDetector->report(mem_leak_period_checking));
memLeakDetector->removeMemoryLeakInformationWithoutCheckingOrDeallocating(leak);
}
TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewOverloadingWithoutMacroWorks)
{
char* leak = newAllocationWithoutMacro();
STRCMP_CONTAINS("unknown", memLeakDetector->report(mem_leak_period_checking));
delete leak;
}
TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewArrayOverloadingWithoutMacroWorks)
{
char* leak = newArrayAllocationWithoutMacro();
STRCMP_CONTAINS("unknown", memLeakDetector->report(mem_leak_period_checking));
delete[] leak;
}
#else
TEST(MemoryLeakOverridesToBeUsedInProductionCode, MemoryOverridesAreDisabled)
{
char* leak = newAllocation();
STRCMP_EQUAL("No memory leaks were detected.", memLeakDetector->report(mem_leak_period_checking));
delete leak;
}
#endif
TEST_GROUP(OutOfMemoryTestsForOperatorNew)
{
MemoryLeakAllocator* no_memory_allocator;
void setup()
{
no_memory_allocator = new NullUnknownAllocator;
MemoryLeakAllocator::setCurrentNewAllocator(no_memory_allocator);
MemoryLeakAllocator::setCurrentNewArrayAllocator(no_memory_allocator);
}
void teardown()
{
MemoryLeakAllocator::setCurrentNewAllocatorToDefault();
MemoryLeakAllocator::setCurrentNewArrayAllocatorToDefault();
delete no_memory_allocator;
}
};
#if CPPUTEST_USE_MEM_LEAK_DETECTION
#if CPPUTEST_USE_STD_CPP_LIB
TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorThrowsAnExceptionWhenUsingStdCppNew)
{
try {
new char;
FAIL("Should have thrown an exception!")
}
catch (std::bad_alloc) {
}
}
TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorThrowsAnExceptionWhenUsingStdCppNew)
{
try {
new char[10];
FAIL("Should have thrown an exception!")
}
catch (std::bad_alloc) {
}
}
#else
TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNull)
{
POINTERS_EQUAL(NULL, new char);
}
TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNull)
{
POINTERS_EQUAL(NULL, new char[10]);
}
#endif
#undef new
#if CPPUTEST_USE_STD_CPP_LIB
TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorThrowsAnExceptionWhenUsingStdCppNewWithoutOverride)
{
try {
new char;
FAIL("Should have thrown an exception!")
}
catch (std::bad_alloc) {
}
}
TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorThrowsAnExceptionWhenUsingStdCppNewWithoutOverride)
{
try {
new char[10];
FAIL("Should have thrown an exception!")
}
catch (std::bad_alloc) {
}
}
#else
TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNullWithoutOverride)
{
POINTERS_EQUAL(NULL, new char);
}
TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNullWithoutOverride)
{
POINTERS_EQUAL(NULL, new char[10]);
}
#endif
#endif
| null |
262 | cpp | blalor-cpputest | JUnitOutputTest.cpp | tests/JUnitOutputTest.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/PlatformSpecificFunctions.h"
static long millisTime;
static const char* theTime = "1978-10-03T00:00:00";
static long MockGetPlatformSpecificTimeInMillis()
{
return millisTime;
}
static const char* MockGetPlatformSpecificTimeString()
{
return theTime;
}
TEST_GROUP(JUnitOutputTest)
{
class MockJUnitTestOutput: public JUnitTestOutput
{
public:
enum
{
testGroupSize = 10
};
enum
{
defaultSize = 7
};
int filesOpened;
int fileBalance;
SimpleString fileName_;
SimpleString buffer_;
TestResult* res_;
struct TestData
{
TestData() :
tst_(0), testName_(0), failure_(0)
{
}
;
Utest* tst_;
SimpleString* testName_;
TestFailure* failure_;
};
struct TestGroupData
{
TestGroupData() :
numberTests_(0), totalFailures_(0), name_(""), testData_(0)
{
}
;
int numberTests_;
int totalFailures_;
SimpleString name_;
TestData* testData_;
};
TestGroupData testGroupData_[testGroupSize];
TestGroupData& currentGroup()
{
return testGroupData_[filesOpened - 1];
}
void resetXmlFile()
{
buffer_ = "";
}
MockJUnitTestOutput() :
filesOpened(0), fileBalance(0), res_(0)
{
for (int i = 0; i < testGroupSize; i++) {
testGroupData_[i].numberTests_ = 0;
testGroupData_[i].totalFailures_ = 0;
}
}
;
void setResult(TestResult* testRes)
{
res_ = testRes;
}
virtual ~MockJUnitTestOutput()
{
for (int i = 0; i < testGroupSize; i++) {
for (int j = 0; j < testGroupData_[i].numberTests_; j++) {
delete testGroupData_[i].testData_[j].tst_;
delete testGroupData_[i].testData_[j].testName_;
if (testGroupData_[i].testData_[j].failure_) delete testGroupData_[i].testData_[j].failure_;
}
if (testGroupData_[i].testData_) delete[] testGroupData_[i].testData_;
}
LONGS_EQUAL(0, fileBalance);
}
void writeToFile(const SimpleString& buf)
{
buffer_ += buf;
}
void openFileForWrite(const SimpleString& in_FileName)
{
filesOpened++;
fileBalance++;
fileName_ = in_FileName;
}
void closeFile()
{
CHECK_XML_FILE();
resetXmlFile();
fileBalance--;
}
void createTestsInGroup(int index, int amount, const char* group, const char* basename)
{
testGroupData_[index].name_ = group;
testGroupData_[index].numberTests_ = amount;
testGroupData_[index].testData_ = new TestData[amount];
for (int i = 0; i < amount; i++) {
TestData& testData = testGroupData_[index].testData_[i];
testData.testName_ = new SimpleString(basename);
*testData.testName_ += StringFrom((long) i);
testData.tst_ = new Utest(group, testData.testName_->asCharString(), "file", 1);
}
}
void runTests()
{
res_->testsStarted();
for (int i = 0; i < testGroupSize; i++) {
TestGroupData& data = testGroupData_[i];
if (data.numberTests_ == 0) continue;
millisTime = 0;
res_->currentGroupStarted(data.testData_[0].tst_);
for (int j = 0; j < data.numberTests_; j++) {
TestData& testData = data.testData_[j];
millisTime = 0;
res_->currentTestStarted(testData.tst_);
if (testData.failure_) print(*testData.failure_);
millisTime = 10;
res_->currentTestEnded(testData.tst_);
}
millisTime = 50;
res_->currentGroupEnded(data.testData_[0].tst_);
}
res_->testsEnded();
}
void setFailure(int groupIndex, int testIndex, const char* fileName, int lineNumber, const char* message)
{
TestData& data = testGroupData_[groupIndex].testData_[testIndex];
data.failure_ = new TestFailure(data.tst_, fileName, lineNumber, message);
testGroupData_[groupIndex].totalFailures_++;
}
void CHECK_HAS_XML_HEADER(SimpleString string)
{
STRCMP_EQUAL("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n", string.asCharString());
}
void CHECK_TEST_SUITE_START(SimpleString output)
{
TestGroupData& group = currentGroup();
SimpleString buf = StringFromFormat("<testsuite errors=\"0\" failures=\"%d\" hostname=\"localhost\" name=\"%s\" tests=\"%d\" time=\"0.050\" timestamp=\"%s\">\n", group.totalFailures_,
group.name_.asCharString(), group.numberTests_, theTime);
CHECK_EQUAL(buf, output);
}
void CHECK_XML_FILE()
{
size_t totalSize = currentGroup().numberTests_ + defaultSize + (currentGroup().totalFailures_ * 2);
SimpleStringCollection col;
buffer_.split("\n", col);
CHECK(col.size() >= totalSize);
CHECK_HAS_XML_HEADER(col[0]);
CHECK_TEST_SUITE_START(col[1]);
CHECK_PROPERTIES_START(col[2]);
CHECK_PROPERTIES_END(col[3]);
CHECK_TESTS(&col[4]);
CHECK_SYSTEM_OUT(col[col.size() - 3]);
CHECK_SYSTEM_ERR(col[col.size() - 2]);
CHECK_TEST_SUITE_END(col[col.size() - 1]);
}
void CHECK_PROPERTIES_START(const SimpleString& output)
{
STRCMP_EQUAL("<properties>\n", output.asCharString());
}
void CHECK_PROPERTIES_END(const SimpleString& output)
{
STRCMP_EQUAL("</properties>\n", output.asCharString());
}
void CHECK_SYSTEM_OUT(const SimpleString& output)
{
STRCMP_EQUAL("<system-out></system-out>\n", output.asCharString());
}
void CHECK_SYSTEM_ERR(const SimpleString& output)
{
STRCMP_EQUAL("<system-err></system-err>\n", output.asCharString());
}
void CHECK_TEST_SUITE_END(const SimpleString& output)
{
STRCMP_EQUAL("</testsuite>", output.asCharString());
}
void CHECK_TESTS(SimpleString* arr)
{
for (int index = 0, curTest = 0; curTest < currentGroup().numberTests_; curTest++, index++) {
SimpleString buf = StringFromFormat("<testcase classname=\"%s\" name=\"%s\" time=\"0.010\">\n", currentGroup().name_.asCharString(),
currentGroup().testData_[curTest].tst_->getName().asCharString());
CHECK_EQUAL(buf, arr[index]);
if (currentGroup().testData_[curTest].failure_) {
CHECK_FAILURE(arr, index, curTest);
}
buf = "</testcase>\n";
CHECK_EQUAL(buf, arr[++index]);
}
}
void CHECK_FAILURE(SimpleString* arr, int& i, int curTest)
{
TestFailure& f = *currentGroup().testData_[curTest].failure_;
i++;
SimpleString message = f.getMessage().asCharString();
message.replace('"', '\'');
message.replace('<', '[');
message.replace('>', ']');
message.replace("\n", "{newline}");
SimpleString buf = StringFromFormat("<failure message=\"%s:%d: %s\" type=\"AssertionFailedError\">\n", f.getFileName().asCharString(), f.getFailureLineNumber(), message.asCharString());
CHECK_EQUAL(buf, arr[i]);
i++;
STRCMP_EQUAL("</failure>\n", arr[i].asCharString());
}
};
MockJUnitTestOutput * output;
TestResult *res;
void setup()
{
output = new MockJUnitTestOutput();
res = new TestResult(*output);
output->setResult(res);
SetPlatformSpecificTimeInMillisMethod(MockGetPlatformSpecificTimeInMillis);
SetPlatformSpecificTimeStringMethod(MockGetPlatformSpecificTimeString);
}
void teardown()
{
delete output;
delete res;
SetPlatformSpecificTimeInMillisMethod(0);
SetPlatformSpecificTimeStringMethod(0);
}
void runTests()
{
output->printTestsStarted();
output->runTests();
output->printTestsEnded(*res);
}
};
TEST(JUnitOutputTest, oneTestInOneGroupAllPass)
{
output->createTestsInGroup(0, 1, "group", "name");
runTests();
STRCMP_EQUAL("cpputest_group.xml", output->fileName_.asCharString());
LONGS_EQUAL(1, output->filesOpened);
}
TEST(JUnitOutputTest, fiveTestsInOneGroupAllPass)
{
output->createTestsInGroup(0, 5, "group", "name");
runTests();
}
TEST(JUnitOutputTest, multipleTestsInTwoGroupAllPass)
{
output->createTestsInGroup(0, 3, "group", "name");
output->createTestsInGroup(1, 8, "secondGroup", "secondName");
runTests();
LONGS_EQUAL(2, output->filesOpened);
}
TEST(JUnitOutputTest, oneTestInOneGroupFailed)
{
output->createTestsInGroup(0, 1, "failedGroup", "failedName");
output->setFailure(0, 0, "file", 1, "Test <\"just\"> failed");
runTests();
}
TEST(JUnitOutputTest, fiveTestsInOneGroupAndThreeFail)
{
output->printTestsStarted();
output->createTestsInGroup(0, 5, "failedGroup", "failedName");
output->setFailure(0, 0, "file", 1, "Test just failed");
output->setFailure(0, 1, "file", 5, "Also failed");
output->setFailure(0, 4, "file", 8, "And failed again");
runTests();
}
TEST(JUnitOutputTest, fourGroupsAndSomePassAndSomeFail)
{
output->printTestsStarted();
output->createTestsInGroup(0, 5, "group1", "firstName");
output->createTestsInGroup(1, 50, "group2", "secondName");
output->createTestsInGroup(2, 3, "group3", "thirdName");
output->createTestsInGroup(3, 5, "group4", "fourthName");
output->setFailure(0, 0, "file", 1, "Test just failed");
output->printTestsEnded(*res);
runTests();
}
TEST(JUnitOutputTest, messageWithNewLine)
{
output->createTestsInGroup(0, 1, "failedGroup", "failedName");
output->setFailure(0, 0, "file", 1, "Test \n failed");
runTests();
}
| null |
263 | cpp | blalor-cpputest | MemoryLeakDetectorTest.cpp | tests/MemoryLeakDetectorTest.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"
class MemoryLeakFailureForTest: public MemoryLeakFailure
{
public:
virtual ~MemoryLeakFailureForTest()
{
}
;
virtual void fail(char* fail_string)
{
*message = fail_string;
}
SimpleString *message;
};
class NewAllocatorForMemoryLeakDetectionTest: public StandardNewAllocator
{
public:
NewAllocatorForMemoryLeakDetectionTest() :
alloc_called(0), free_called(0)
{
}
int alloc_called;
int free_called;
char* alloc_memory(size_t size, const char*, int)
{
alloc_called++;
return StandardNewAllocator::alloc_memory(size, "file", 1);
}
void free_memory(char* memory, const char* file, int line)
{
free_called++;
StandardNewAllocator::free_memory(memory, file, line);
}
};
class MallocAllocatorForMemoryLeakDetectionTest: public StandardMallocAllocator
{
public:
MallocAllocatorForMemoryLeakDetectionTest() :
alloc_called(0), free_called(0), allocMemoryLeakNodeCalled(0), freeMemoryLeakNodeCalled(0)
{
}
int alloc_called;
int free_called;
int allocMemoryLeakNodeCalled;
int freeMemoryLeakNodeCalled;
char* alloc_memory(size_t size, const char* file, int line)
{
alloc_called++;
return StandardMallocAllocator::alloc_memory(size, file, line);
}
void free_memory(char* memory, const char* file, int line)
{
free_called++;
StandardMallocAllocator::free_memory(memory, file, line);
}
char* allocMemoryLeakNode(size_t size)
{
allocMemoryLeakNodeCalled++;
return StandardMallocAllocator::alloc_memory(size, __FILE__, __LINE__);
}
void freeMemoryLeakNode(char* memory)
{
freeMemoryLeakNodeCalled++;
StandardMallocAllocator::free_memory(memory, __FILE__, __LINE__);
}
};
TEST_GROUP(MemoryLeakDetectorTest)
{
MemoryLeakDetector* detector;
MemoryLeakFailureForTest *reporter;
MallocAllocatorForMemoryLeakDetectionTest* mallocAllocator;
NewAllocatorForMemoryLeakDetectionTest* newAllocator;
StandardNewArrayAllocator* newArrayAllocator;
void setup()
{
detector = new MemoryLeakDetector;
reporter = new MemoryLeakFailureForTest;
mallocAllocator = new MallocAllocatorForMemoryLeakDetectionTest;
newAllocator = new NewAllocatorForMemoryLeakDetectionTest;
newArrayAllocator = new StandardNewArrayAllocator;
detector->init(reporter);
detector->enable();
detector->startChecking();
reporter->message = new SimpleString();
}
void teardown()
{
delete reporter->message;
delete detector;
delete reporter;
delete mallocAllocator;
delete newAllocator;
delete newArrayAllocator;
}
};
TEST(MemoryLeakDetectorTest, OneLeak)
{
char* mem = detector->allocMemory(newAllocator, 3);
detector->stopChecking();
SimpleString output = detector->report(mem_leak_period_checking);
CHECK(output.contains(MEM_LEAK_HEADER));
CHECK(output.contains("size: 3"));
CHECK(output.contains("new"));
CHECK(output.contains(MEM_LEAK_FOOTER));
PlatformSpecificFree(mem);
LONGS_EQUAL(1, newAllocator->alloc_called);
LONGS_EQUAL(0, newAllocator->free_called);
}
TEST(MemoryLeakDetectorTest, OneHundredLeaks)
{
const int amount_alloc = 100;
char *mem[amount_alloc];
for (int i = 0; i < amount_alloc; i++)
mem[i] = detector->allocMemory(mallocAllocator, 3);
detector->stopChecking();
SimpleString output = detector->report(mem_leak_period_checking);
STRCMP_CONTAINS(MEM_LEAK_HEADER, output.asCharString());
STRCMP_CONTAINS(MEM_LEAK_FOOTER, output.asCharString());
STRCMP_CONTAINS(MEM_LEAK_ADDITION_MALLOC_WARNING, output.asCharString());
//don't reuse i for vc6 compatibility
for (int j = 0; j < amount_alloc; j++)
PlatformSpecificFree(mem[j]);
}
TEST(MemoryLeakDetectorTest, OneLeakOutsideCheckingPeriod)
{
detector->stopChecking();
char* mem = detector->allocMemory(newAllocator, 4);
SimpleString output = detector->report(mem_leak_period_all);
CHECK(output.contains(MEM_LEAK_HEADER));
CHECK(output.contains("size: 4"));
CHECK(output.contains("new"));
CHECK(output.contains(MEM_LEAK_FOOTER));
PlatformSpecificFree(mem);
}
TEST(MemoryLeakDetectorTest, NoLeaksWhatsoever)
{
detector->stopChecking();
STRCMP_EQUAL(MEM_LEAK_NONE, detector->report(mem_leak_period_checking));
STRCMP_EQUAL(MEM_LEAK_NONE, detector->report(mem_leak_period_all));
}
TEST(MemoryLeakDetectorTest, TwoLeaksUsingOperatorNew)
{
char* mem = detector->allocMemory(newAllocator, 4);
char* mem2 = detector->allocMemory(newAllocator, 8);
detector->stopChecking();
SimpleString output = detector->report(mem_leak_period_checking);
LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking));
CHECK(output.contains("size: 8"));
CHECK(output.contains("size: 4"));
PlatformSpecificFree(mem);
PlatformSpecificFree(mem2);
}
TEST(MemoryLeakDetectorTest, OneAllocButNoLeak)
{
char* mem = detector->allocMemory(newAllocator, 4);
detector->deallocMemory(newAllocator, mem);
detector->stopChecking();
STRCMP_EQUAL(MEM_LEAK_NONE, detector->report(mem_leak_period_checking));
LONGS_EQUAL(1, newAllocator->alloc_called);
LONGS_EQUAL(1, newAllocator->free_called);
}
TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeak)
{
char* mem = detector->allocMemory(newAllocator, 4);
char* mem2 = detector->allocMemory(newAllocator, 12);
detector->deallocMemory(newAllocator, mem);
detector->stopChecking();
SimpleString output = detector->report(mem_leak_period_checking);
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking));
CHECK(output.contains("size: 12"));
CHECK(!output.contains("size: 4"));
PlatformSpecificFree(mem2);
LONGS_EQUAL(2, newAllocator->alloc_called);
LONGS_EQUAL(1, newAllocator->free_called);
}
TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeakReverseOrder)
{
char* mem = detector->allocMemory(newAllocator, 4);
char* mem2 = detector->allocMemory(newAllocator, 12);
detector->deallocMemory(newAllocator, mem2);
detector->stopChecking();
SimpleString output = detector->report(mem_leak_period_checking);
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking));
CHECK(!output.contains("size: 12"));
CHECK(output.contains("size: 4"));
PlatformSpecificFree(mem);
}
TEST(MemoryLeakDetectorTest, DeleteNonAlocatedMemory)
{
char a;
char* pa = &a;
detector->deallocMemory(mallocAllocator, pa, "FREE.c", 100);
detector->stopChecking();
CHECK(reporter->message->contains(MEM_LEAK_DEALLOC_NON_ALLOCATED));
CHECK(reporter->message->contains(" allocated at file: <unknown> line: 0 size: 0 type: unknown"));
CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free"));
LONGS_EQUAL(0, newAllocator->free_called);
}
TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriod)
{
detector->stopChecking();
char* mem = detector->allocMemory(newAllocator, 4);
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking));
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all));
detector->deallocMemory(newAllocator, mem);
}
TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriodComplicatedCase)
{
char* mem = detector->allocMemory(newAllocator, 4);
detector->stopChecking();
char* mem2 = detector->allocMemory(newAllocator, 8);
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking));
detector->clearAllAccounting(mem_leak_period_checking);
PlatformSpecificFree(mem);
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking));
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all));
detector->startChecking();
char* mem3 = detector->allocMemory(newAllocator, 4);
detector->stopChecking();
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking));
LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all));
detector->clearAllAccounting(mem_leak_period_checking);
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking));
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all));
detector->clearAllAccounting(mem_leak_period_all);
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all));
PlatformSpecificFree(mem2);
PlatformSpecificFree(mem3);
}
TEST(MemoryLeakDetectorTest, OneLeakUsingOperatorNewWithFileLine)
{
char* mem = detector->allocMemory(newAllocator, 4, "file.cpp", 1234);
detector->stopChecking();
SimpleString output = detector->report(mem_leak_period_checking);
CHECK(output.contains("file.cpp"));
CHECK(output.contains("1234"));
PlatformSpecificFree(mem);
}
TEST(MemoryLeakDetectorTest, OneAllocAndFreeUsingArrayNew)
{
char* mem = detector->allocMemory(newArrayAllocator, 10, "file.cpp", 1234);
char* mem2 = detector->allocMemory(newArrayAllocator, 12);
LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all));
SimpleString output = detector->report(mem_leak_period_checking);
CHECK(output.contains("new []"));
detector->deallocMemory(newArrayAllocator, mem);
detector->deallocMemory(newArrayAllocator, mem2);
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all));
detector->stopChecking();
}
TEST(MemoryLeakDetectorTest, OneAllocAndFree)
{
char* mem = detector->allocMemory(mallocAllocator, 10, "file.cpp", 1234);
char* mem2 = detector->allocMemory(mallocAllocator, 12);
LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking));
SimpleString output = detector->report(mem_leak_period_checking);
CHECK(output.contains("malloc"));
detector->deallocMemory(mallocAllocator, mem);
detector->deallocMemory(mallocAllocator, mem2, "file.c", 5678);
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all));
detector->stopChecking();
}
TEST(MemoryLeakDetectorTest, OneRealloc)
{
char* mem1 = detector->allocMemory(mallocAllocator, 10, "file.cpp", 1234);
char* mem2 = detector->reallocMemory(mallocAllocator, mem1, 1000, "other.cpp", 5678);
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking));
SimpleString output = detector->report(mem_leak_period_checking);
CHECK(output.contains("other.cpp"));
detector->deallocMemory(mallocAllocator, mem2);
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all));
detector->stopChecking();
LONGS_EQUAL(1, mallocAllocator->alloc_called);
LONGS_EQUAL(1, mallocAllocator->free_called);
LONGS_EQUAL(2, mallocAllocator->allocMemoryLeakNodeCalled);
LONGS_EQUAL(2, mallocAllocator->freeMemoryLeakNodeCalled);
}
TEST(MemoryLeakDetectorTest, AllocAndFreeWithDifferenceInstancesOfTheSameAllocatorType)
{
StandardNewArrayAllocator newArrayAllocatorTwo;
char* mem = detector->allocMemory(newArrayAllocator, 100, "ALLOC.c", 10);
detector->deallocMemory(&newArrayAllocatorTwo, mem, "FREE.c", 100);
detector->stopChecking();
STRCMP_EQUAL("", reporter->message->asCharString());
}
TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherType)
{
char* mem = detector->allocMemory(newArrayAllocator, 100, "ALLOC.c", 10);
detector->deallocMemory(mallocAllocator, mem, "FREE.c", 100);
detector->stopChecking();
CHECK(reporter->message->contains(MEM_LEAK_ALLOC_DEALLOC_MISMATCH));
CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 100 type: new []"));
CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free"));
}
TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherTypeWithCheckingDisabled)
{
detector->disableAllocationTypeChecking();
char* mem = detector->allocMemory(newArrayAllocator, 100, "ALLOC.c", 10);
detector->deallocMemory(newArrayAllocator, mem, "FREE.c", 100);
detector->stopChecking();
STRCMP_EQUAL("", reporter->message->asCharString());
detector->enableAllocationTypeChecking();
}
TEST(MemoryLeakDetectorTest, mallocLeakGivesAdditionalWarning)
{
char* mem = detector->allocMemory(mallocAllocator, 100, "ALLOC.c", 10);
detector->stopChecking();
SimpleString output = detector->report(mem_leak_period_checking);
STRCMP_CONTAINS("Memory leak reports about malloc and free can be caused by allocating using the cpputest version of malloc", output.asCharString());
PlatformSpecificFree(mem);
}
TEST(MemoryLeakDetectorTest, newLeakDoesNotGiveAdditionalWarning)
{
char* mem = detector->allocMemory(newAllocator, 100, "ALLOC.c", 10);
detector->stopChecking();
SimpleString output = detector->report(mem_leak_period_checking);
CHECK(! output.contains("Memory leak reports about malloc and free"));
PlatformSpecificFree(mem);
}
TEST(MemoryLeakDetectorTest, MarkCheckingPeriodLeaksAsNonCheckingPeriod)
{
char* mem = detector->allocMemory(newArrayAllocator, 100);
char* mem2 = detector->allocMemory(newArrayAllocator, 100);
detector->stopChecking();
LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking));
LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all));
detector->markCheckingPeriodLeaksAsNonCheckingPeriod();
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking));
LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all));
PlatformSpecificFree(mem);
PlatformSpecificFree(mem2);
}
TEST(MemoryLeakDetectorTest, memoryCorruption)
{
char* mem = detector->allocMemory(mallocAllocator, 10, "ALLOC.c", 10);
mem[10] = 'O';
mem[11] = 'H';
detector->deallocMemory(mallocAllocator, mem, "FREE.c", 100);
detector->stopChecking();
CHECK(reporter->message->contains(MEM_LEAK_MEMORY_CORRUPTION));
CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 10 type: malloc"));
CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free"));
}
TEST(MemoryLeakDetectorTest, safelyDeleteNULL)
{
detector->deallocMemory(newAllocator, 0);
STRCMP_EQUAL("", reporter->message->asCharString());
}
TEST(MemoryLeakDetectorTest, periodDisabled)
{
detector->disable();
char* mem = detector->allocMemory(mallocAllocator, 2);
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all));
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_disabled));
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_enabled));
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking));
detector->deallocMemory(mallocAllocator, mem);
}
TEST(MemoryLeakDetectorTest, periodEnabled)
{
detector->enable();
char* mem = detector->allocMemory(mallocAllocator, 2);
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all));
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled));
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled));
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking));
detector->deallocMemory(mallocAllocator, mem);
}
TEST(MemoryLeakDetectorTest, periodChecking)
{
char* mem = detector->allocMemory(mallocAllocator, 2);
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all));
LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled));
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled));
LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking));
detector->deallocMemory(mallocAllocator, mem);
}
TEST(MemoryLeakDetectorTest, allocateWithANullAllocatorCausesNoProblems)
{
char* mem = detector->allocMemory(NullUnknownAllocator::defaultAllocator(), 2);
detector->deallocMemory(NullUnknownAllocator::defaultAllocator(), mem);
}
TEST(MemoryLeakDetectorTest, invalidateMemory)
{
unsigned char* mem = (unsigned char*)detector->allocMemory(mallocAllocator, 2);
detector->invalidateMemory((char*)mem);
CHECK(mem[0] == 0xCD);
CHECK(mem[1] == 0xCD);
detector->deallocMemory(mallocAllocator, mem);
}
TEST(MemoryLeakDetectorTest, invalidateMemoryNULLShouldWork)
{
detector->invalidateMemory(NULL);
}
TEST_GROUP(SimpleStringBuffer)
{
};
TEST(SimpleStringBuffer, simpleTest)
{
SimpleStringBuffer buffer;
buffer.add("Hello");
buffer.add(" World");
STRCMP_EQUAL("Hello World", buffer.toString());
}
TEST(SimpleStringBuffer, writePastLimit)
{
SimpleStringBuffer buffer;
for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN * 2; i++)
buffer.add("h");
SimpleString str("h", SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN-1);
STRCMP_EQUAL(str.asCharString(), buffer.toString());
}
TEST(SimpleStringBuffer, setWriteLimit)
{
SimpleStringBuffer buffer;
buffer.setWriteLimit(10);
for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN ; i++)
buffer.add("h");
SimpleString str("h", 10);
STRCMP_EQUAL(str.asCharString(), buffer.toString());
}
TEST(SimpleStringBuffer, setWriteLimitTooHighIsIgnored)
{
SimpleStringBuffer buffer;
buffer.setWriteLimit(SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN+10);
for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN+10; i++)
buffer.add("h");
SimpleString str("h", SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN-1);
STRCMP_EQUAL(str.asCharString(), buffer.toString());
}
TEST(SimpleStringBuffer, resetWriteLimit)
{
SimpleStringBuffer buffer;
buffer.setWriteLimit(10);
for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN ; i++)
buffer.add("h");
buffer.resetWriteLimit();
buffer.add(SimpleString("h", 10).asCharString());
SimpleString str("h", 20);
STRCMP_EQUAL(str.asCharString(), buffer.toString());
}
TEST_GROUP(ReallocBugReported) { };
TEST(ReallocBugReported, ThisSituationShouldntCrash)
{
StandardMallocAllocator allocator;
MemoryLeakDetector detector;
char* mem = detector.allocMemory(&allocator, 5, "file", 1);
mem = detector.reallocMemory(&allocator, mem, 19, "file", 1);
detector.deallocMemory(&allocator, mem);
}
| null |
264 | cpp | blalor-cpputest | NullTestTest.cpp | tests/NullTestTest.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"
TEST_GROUP(NullTest)
{
NullTest* nullTest;
TEST_SETUP()
{
nullTest = new NullTest();
}
TEST_TEARDOWN()
{
delete nullTest;
}
};
TEST(NullTest, Create)
{
}
TEST(NullTest, InstanceAlwaysTheSame)
{
NullTest& _instance = NullTest::instance();
CHECK(&_instance == &NullTest::instance());
}
TEST(NullTest, NullTestsDontCount)
{
NullTest& _instance = NullTest::instance();
CHECK(_instance.countTests() == 0);
}
| null |
265 | cpp | blalor-cpputest | AllocationInCppFile.h | tests/AllocationInCppFile.h | null | #ifndef ALLOCATIONINCPPFILE_H
#define ALLOCATIONINCPPFILE_H
char* newAllocation();
char* newArrayAllocation();
char* newAllocationWithoutMacro();
char* newArrayAllocationWithoutMacro();
#endif
| null |
266 | cpp | blalor-cpputest | TestFailureTest.cpp | tests/TestFailureTest.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"
namespace
{
const int failLineNumber = 2;
const char* failFileName = "fail.cpp";
}
static double zero = 0.0;
static const double nan = zero / zero;
TEST_GROUP(TestFailure)
{
Utest* test;
StringBufferTestOutput* printer;
void setup()
{
test = new NullTest(failFileName, failLineNumber-1);
printer = new StringBufferTestOutput();
}
void teardown()
{
delete test;
delete printer;
}
;
};
#define FAILURE_EQUAL(a, b) STRCMP_EQUAL_LOCATION(a, b.getMessage().asCharString(), __FILE__, __LINE__)
TEST(TestFailure, CreateFailure)
{
TestFailure f1(test, failFileName, failLineNumber, "the failure message");
TestFailure f2(test, "the failure message");
TestFailure f3(test, failFileName, failLineNumber);
}
TEST(TestFailure, GetTestFileAndLineFromFailure)
{
TestFailure f1(test, failFileName, failLineNumber, "the failure message");
STRCMP_EQUAL(failFileName, f1.getTestFileName().asCharString());
LONGS_EQUAL(1, f1.getTestLineNumber());
}
TEST(TestFailure, CreatePassingEqualsFailure)
{
EqualsFailure f(test, failFileName, failLineNumber, "expected", "actual");
FAILURE_EQUAL("expected <expected>\n\tbut was <actual>", f);
}
TEST(TestFailure, EqualsFailureWithNullAsActual)
{
EqualsFailure f(test, failFileName, failLineNumber, "expected", NULL);
FAILURE_EQUAL("expected <expected>\n\tbut was <(null)>", f);
}
TEST(TestFailure, EqualsFailureWithNullAsExpected)
{
EqualsFailure f(test, failFileName, failLineNumber, NULL, "actual");
FAILURE_EQUAL("expected <(null)>\n\tbut was <actual>", f);
}
TEST(TestFailure, CheckEqualFailure)
{
CheckEqualFailure f(test, failFileName, failLineNumber, "expected", "actual");
FAILURE_EQUAL("expected <expected>\n"
"\tbut was <actual>\n"
"\tdifference starts at position 0 at: < actual >\n"
"\t ^", f);
}
TEST(TestFailure, CheckFailure)
{
CheckFailure f(test, failFileName, failLineNumber, "CHECK", "chk");
FAILURE_EQUAL("CHECK(chk) failed", f);
}
TEST(TestFailure, FailFailure)
{
FailFailure f(test, failFileName, failLineNumber, "chk");
FAILURE_EQUAL("chk", f);
}
TEST(TestFailure, LongsEqualFailure)
{
LongsEqualFailure f(test, failFileName, failLineNumber, 1, 2);
FAILURE_EQUAL("expected <1 0x1>\n\tbut was <2 0x2>", f);
}
TEST(TestFailure, StringsEqualFailure)
{
StringEqualFailure f(test, failFileName, failLineNumber, "abc", "abd");
FAILURE_EQUAL("expected <abc>\n"
"\tbut was <abd>\n"
"\tdifference starts at position 2 at: < abd >\n"
"\t ^", f);
}
TEST(TestFailure, StringsEqualFailureAtTheEnd)
{
StringEqualFailure f(test, failFileName, failLineNumber, "abc", "ab");
FAILURE_EQUAL("expected <abc>\n"
"\tbut was <ab>\n"
"\tdifference starts at position 2 at: < ab >\n"
"\t ^", f);
}
TEST(TestFailure, StringsEqualFailureNewVariantAtTheEnd)
{
StringEqualFailure f(test, failFileName, failLineNumber, "EndOfALongerString", "EndOfALongerStrinG");
FAILURE_EQUAL("expected <EndOfALongerString>\n"
"\tbut was <EndOfALongerStrinG>\n"
"\tdifference starts at position 17 at: <ongerStrinG >\n"
"\t ^", f);
}
TEST(TestFailure, StringsEqualFailureWithNewLinesAndTabs)
{
StringEqualFailure f(test, failFileName, failLineNumber,
"StringWith\t\nDifferentString",
"StringWith\t\ndifferentString");
FAILURE_EQUAL("expected <StringWith\t\nDifferentString>\n"
"\tbut was <StringWith\t\ndifferentString>\n"
"\tdifference starts at position 12 at: <ringWith\t\ndifferentS>\n"
"\t \t\n^", f);
}
TEST(TestFailure, StringsEqualFailureInTheMiddle)
{
StringEqualFailure f(test, failFileName, failLineNumber, "aa", "ab");
FAILURE_EQUAL("expected <aa>\n"
"\tbut was <ab>\n"
"\tdifference starts at position 1 at: < ab >\n"
"\t ^", f);
}
TEST(TestFailure, StringsEqualFailureAtTheBeginning)
{
StringEqualFailure f(test, failFileName, failLineNumber, "aaa", "bbb");
FAILURE_EQUAL("expected <aaa>\n"
"\tbut was <bbb>\n"
"\tdifference starts at position 0 at: < bbb >\n"
"\t ^", f);
}
TEST(TestFailure, StringsEqualNoCaseFailure)
{
StringEqualNoCaseFailure f(test, failFileName, failLineNumber, "ABC", "abd");
FAILURE_EQUAL("expected <ABC>\n"
"\tbut was <abd>\n"
"\tdifference starts at position 2 at: < abd >\n"
"\t ^", f);
}
TEST(TestFailure, StringsEqualNoCaseFailure2)
{
StringEqualNoCaseFailure f(test, failFileName, failLineNumber, "ac", "AB");
FAILURE_EQUAL("expected <ac>\n"
"\tbut was <AB>\n"
"\tdifference starts at position 1 at: < AB >\n"
"\t ^", f);
}
TEST(TestFailure, DoublesEqualNormal)
{
DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, 2.0, 3.0);
FAILURE_EQUAL("expected <1.000000>\n"
"\tbut was <2.000000> threshold used was <3.000000>", f);
}
TEST(TestFailure, DoublesEqualExpectedIsNaN)
{
DoublesEqualFailure f(test, failFileName, failLineNumber, nan, 2.0, 3.0);
FAILURE_EQUAL("expected <Nan - Not a number>\n"
"\tbut was <2.000000> threshold used was <3.000000>\n"
"\tCannot make comparisons with Nan", f);
}
TEST(TestFailure, DoublesEqualActualIsNaN)
{
DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, nan, 3.0);
FAILURE_EQUAL("expected <1.000000>\n"
"\tbut was <Nan - Not a number> threshold used was <3.000000>\n"
"\tCannot make comparisons with Nan", f);
}
TEST(TestFailure, DoublesEqualThresholdIsNaN)
{
DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, 2.0, nan);
FAILURE_EQUAL("expected <1.000000>\n"
"\tbut was <2.000000> threshold used was <Nan - Not a number>\n"
"\tCannot make comparisons with Nan", f);
}
| null |
267 | cpp | blalor-cpputest | CheatSheetTest.cpp | tests/CheatSheetTest.cpp | null |
static void (*real_one) ();
static void stub(){}
/* in CheatSheetTest.cpp */
#include "CppUTest/TestHarness.h"
/* Declare TestGroup with name CheatSheet */
TEST_GROUP(CheatSheet)
{
/* declare a setup method for the test group. Optional. */
void setup ()
{
/* Set method real_one to stub. Automatically restore in teardown */
UT_PTR_SET(real_one, stub);
}
/* Declare a teardown method for the test group. Optional */
void teardown()
{
}
}; /* Do not forget semicolumn */
/* Declare one test within the test group */
TEST(CheatSheet, TestName)
{
/* Check two longs are equal */
LONGS_EQUAL(1, 1);
/* Check a condition */
CHECK(true == true);
/* Check a string */
STRCMP_EQUAL("HelloWorld", "HelloWorld");
}
| null |
268 | cpp | blalor-cpputest | AllocationInCFile.h | tests/AllocationInCFile.h | null | #ifndef ALLOCATIONINCFILE_H
#define ALLOCATIONINCFILE_H
extern char* mallocAllocation();
extern void freeAllocation(void* memory);
extern void freeAllocationWithoutMacro(void* memory);
#endif
| null |
269 | cpp | blalor-cpputest | SetPluginTest.cpp | tests/SetPluginTest.cpp | null | #include "CppUTest/TestHarness.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestPlugin.h"
void orig_func1()
{
}
void stub_func1()
{
}
void orig_func2()
{
}
void stub_func2()
{
}
void (*fp1)();
void (*fp2)();
TEST_GROUP(SetPointerPluginTest)
{
SetPointerPlugin* plugin_;
TestRegistry* myRegistry_;
StringBufferTestOutput* output_;
TestResult* result_;
void setup()
{
myRegistry_ = new TestRegistry();
plugin_ = new SetPointerPlugin("TestSetPlugin");
myRegistry_->setCurrentRegistry(myRegistry_);
myRegistry_->installPlugin(plugin_);
output_ = new StringBufferTestOutput();
result_ = new TestResult(*output_);
}
void teardown()
{
myRegistry_->setCurrentRegistry(0);
delete myRegistry_;
delete plugin_;
delete output_;
delete result_;
}
};
class FunctionPointerUtest: public Utest
{
public:
void setup()
{
UT_PTR_SET(fp1, stub_func1);
UT_PTR_SET(fp2, stub_func2);
UT_PTR_SET(fp2, stub_func2);
}
void testBody()
{
CHECK(fp1 == stub_func1);
CHECK(fp2 == stub_func2);
}
};
TEST(SetPointerPluginTest, installTwoFunctionPointer)
{
FunctionPointerUtest *tst = new FunctionPointerUtest();
;
fp1 = orig_func1;
fp2 = orig_func2;
myRegistry_->addTest(tst);
myRegistry_->runAllTests(*result_);
CHECK(fp1 == orig_func1);
CHECK(fp2 == orig_func2);
LONGS_EQUAL(0, result_->getFailureCount());
delete tst;
}
class MaxFunctionPointerUtest: public Utest
{
public:
int numOfFpSets;
MaxFunctionPointerUtest(int num) :
numOfFpSets(num)
{
}
;
void setup()
{
for (int i = 0; i < numOfFpSets; ++i)
UT_PTR_SET(fp1, stub_func1);
}
};
IGNORE_TEST(SetPointerPluginTest, installTooMuchFunctionPointer)
{
MaxFunctionPointerUtest *tst = new MaxFunctionPointerUtest(SetPointerPlugin::MAX_SET + 1);
myRegistry_->addTest(tst);
myRegistry_->runAllTests(*result_);
LONGS_EQUAL(1, result_->getFailureCount());
delete tst;
}
double orig_double = 3.0;
double* orig_double_ptr = &orig_double;
double stub_double = 4.0;
class SetDoublePointerUtest: public Utest
{
public:
void setup()
{
UT_PTR_SET(orig_double_ptr, &stub_double);
}
void testBody()
{
CHECK(orig_double_ptr == &stub_double);
}
};
TEST(SetPointerPluginTest, doublePointer)
{
SetDoublePointerUtest *doubletst = new SetDoublePointerUtest();
myRegistry_->addTest(doubletst);
CHECK(orig_double_ptr == &orig_double);
delete doubletst;
}
| null |
270 | cpp | blalor-cpputest | MemoryLeakWarningTest.cpp | tests/MemoryLeakWarningTest.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/TestOutput.h"
#include "CppUTest/MemoryLeakWarningPlugin.h"
#include "CppUTest/MemoryLeakDetector.h"
#include "CppUTest/MemoryLeakAllocator.h"
#include "CppUTest/TestTestingFixture.h"
static char* leak1;
static long* leak2;
class DummyReporter: public MemoryLeakFailure
{
public:
virtual ~DummyReporter()
{
}
virtual void fail(char* /*fail_string*/)
{
}
};
static MemoryLeakDetector* detector;
static MemoryLeakWarningPlugin* memPlugin;
static DummyReporter dummy;
static MemoryLeakAllocator* allocator;
TEST_GROUP(MemoryLeakWarningTest)
{
TestTestingFixture* fixture;
void setup()
{
fixture = new TestTestingFixture();
detector = new MemoryLeakDetector();
allocator = new StandardNewAllocator;
detector->init(&dummy);
memPlugin = new MemoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", detector);
fixture->registry_->installPlugin(memPlugin);
memPlugin->enable();
leak1 = 0;
leak2 = 0;
}
void teardown()
{
detector->deallocMemory(allocator, leak1);
detector->deallocMemory(allocator, leak2);
delete fixture;
delete memPlugin;
delete detector;
delete allocator;
}
};
void _testTwoLeaks()
{
leak1 = detector->allocMemory(allocator, 10);
leak2 = (long*) detector->allocMemory(allocator, 4);
}
TEST(MemoryLeakWarningTest, TwoLeaks)
{
fixture->setTestFunction(_testTwoLeaks);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
fixture->assertPrintContains("Total number of leaks: 2");
}
void _testIgnore2()
{
memPlugin->expectLeaksInTest(2);
leak1 = detector->allocMemory(allocator, 10);
leak2 = (long*) detector->allocMemory(allocator, 4);
}
TEST(MemoryLeakWarningTest, Ignore2)
{
fixture->setTestFunction(_testIgnore2);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
}
static void _failAndLeakMemory()
{
leak1 = detector->allocMemory(allocator, 10);
FAIL("");
}
TEST(MemoryLeakWarningTest, FailingTestDoesNotReportMemoryLeaks)
{
fixture->setTestFunction(_failAndLeakMemory);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
| null |
271 | cpp | blalor-cpputest | TestOutputTest.cpp | tests/TestOutputTest.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/TestResult.h"
#include "CppUTest/PlatformSpecificFunctions.h"
static long millisTime;
static long MockGetPlatformSpecificTimeInMillis()
{
return millisTime;
}
TEST_GROUP(TestOutput)
{
TestOutput* printer;
StringBufferTestOutput* mock;
Utest* tst;
TestFailure *f;
TestFailure *f2;
TestFailure *f3;
TestResult* result;
void setup()
{
mock = new StringBufferTestOutput();
printer = mock;
tst = new Utest("group", "test", "file", 10);
f = new TestFailure(tst, "failfile", 20, "message");
f2 = new TestFailure(tst, "file", 20, "message");
f3 = new TestFailure(tst, "file", 2, "message");
result = new TestResult(*mock);
result->setTotalExecutionTime(10);
millisTime = 0;
SetPlatformSpecificTimeInMillisMethod(MockGetPlatformSpecificTimeInMillis);
}
void teardown()
{
delete printer;
delete tst;
delete f;
delete f2;
delete f3;
delete result;
SetPlatformSpecificTimeInMillisMethod(0);
}
};
TEST(TestOutput, PrintConstCharStar)
{
printer->print("hello");
printer->print("hello\n");
STRCMP_EQUAL("hellohello\n", mock->getOutput().asCharString());
}
TEST(TestOutput, PrintLong)
{
printer->print(1234);
STRCMP_EQUAL("1234", mock->getOutput().asCharString());
}
TEST(TestOutput, PrintDouble)
{
printer->printDouble(12.34);
STRCMP_EQUAL("12.340", mock->getOutput().asCharString());
}
TEST(TestOutput, StreamOperators)
{
*printer << "n=" << 1234;
STRCMP_EQUAL("n=1234", mock->getOutput().asCharString());
}
TEST(TestOutput, PrintTestEnded)
{
printer->printCurrentTestEnded(*result);
STRCMP_EQUAL(".", mock->getOutput().asCharString());
}
TEST(TestOutput, PrintTestALot)
{
for (int i = 0; i < 60; ++i) {
printer->printCurrentTestEnded(*result);
}
STRCMP_EQUAL("..................................................\n..........", mock->getOutput().asCharString());
}
TEST(TestOutput, SetProgressIndicator)
{
result->setProgressIndicator(".");
printer->printCurrentTestEnded(*result);
result->setProgressIndicator("!");
printer->printCurrentTestEnded(*result);
result->setProgressIndicator(".");
printer->printCurrentTestEnded(*result);
STRCMP_EQUAL(".!.", mock->getOutput().asCharString());
}
TEST(TestOutput, PrintTestVerboseStarted)
{
mock->verbose();
printer->printCurrentTestStarted(*tst);
STRCMP_EQUAL("TEST(group, test)", mock->getOutput().asCharString());
}
TEST(TestOutput, PrintTestVerboseEnded)
{
mock->verbose();
result->currentTestStarted(tst);
millisTime = 5;
result->currentTestEnded(tst);
STRCMP_EQUAL("TEST(group, test) - 5 ms\n", mock->getOutput().asCharString());
}
TEST(TestOutput, PrintTestRun)
{
printer->printTestRun(2, 3);
STRCMP_EQUAL("Test run 2 of 3\n", mock->getOutput().asCharString());
}
TEST(TestOutput, PrintTestRunOnlyOne)
{
printer->printTestRun(1, 1);
STRCMP_EQUAL("", mock->getOutput().asCharString());
}
TEST(TestOutput, PrintWithFailureInSameFile)
{
printer->print(*f2);
STRCMP_EQUAL("\nfile:20: error: Failure in TEST(group, test)\n\tmessage\n\n", mock->getOutput().asCharString());
}
TEST(TestOutput, PrintFailureWithFailInDifferentFile)
{
printer->print(*f);
const char* expected =
"\nfile:10: error: Failure in TEST(group, test)"
"\nfailfile:20: error:\n\tmessage\n\n";
STRCMP_EQUAL(expected, mock->getOutput().asCharString());
}
TEST(TestOutput, PrintFailureWithFailInHelper)
{
printer->print(*f3);
const char* expected =
"\nfile:10: error: Failure in TEST(group, test)"
"\nfile:2: error:\n\tmessage\n\n";
STRCMP_EQUAL(expected, mock->getOutput().asCharString());
}
TEST(TestOutput, PrintTestStarts)
{
printer->printTestsStarted();
STRCMP_EQUAL("", mock->getOutput().asCharString());
}
TEST(TestOutput, printTestsEnded)
{
result->countTest();
result->countCheck();
result->countIgnored();
result->countIgnored();
result->countRun();
result->countRun();
result->countRun();
printer->printTestsEnded(*result);
STRCMP_EQUAL("\nOK (1 tests, 3 ran, 1 checks, 2 ignored, 0 filtered out, 10 ms)\n\n", mock->getOutput().asCharString());
}
TEST(TestOutput, printTestsEndedWithFailures)
{
result->addFailure(*f);
printer->flush();
printer->printTestsEnded(*result);
STRCMP_EQUAL("\nErrors (1 failures, 0 tests, 0 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)\n\n", mock->getOutput().asCharString());
}
| null |
272 | cpp | blalor-cpputest | AllTests.h | tests/AllTests.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.
*/
//Include this in the test main to execute these tests
IMPORT_TEST_GROUP( Utest);
IMPORT_TEST_GROUP( Failure);
IMPORT_TEST_GROUP( TestOutput);
IMPORT_TEST_GROUP( SimpleString);
IMPORT_TEST_GROUP( TestInstaller);
IMPORT_TEST_GROUP( NullTest);
IMPORT_TEST_GROUP( MemoryLeakWarningTest);
IMPORT_TEST_GROUP( TestHarness_c);
IMPORT_TEST_GROUP( CommandLineTestRunner);
IMPORT_TEST_GROUP( JUnitOutputTest);
IMPORT_TEST_GROUP( MemoryLeakDetectorTest);
/* In allTest.cpp */
IMPORT_TEST_GROUP(CheatSheet);
| null |
273 | cpp | blalor-cpputest | AllocationInCppFile.cpp | tests/AllocationInCppFile.cpp | null | /* This file is for emulating allocations in a C++ file.
* It is used simulating the use of the memory leak detector on production code in C++
*/
#undef new
#include "CppUTest/MemoryLeakDetectorNewMacros.h"
char* newAllocation()
{
return new char;
}
char* newArrayAllocation()
{
return new char[100];
}
#undef new
char* newAllocationWithoutMacro()
{
return new char;
}
char* newArrayAllocationWithoutMacro()
{
return new char[100];
}
| null |
274 | cpp | blalor-cpputest | PreprocessorTest.cpp | tests/PreprocessorTest.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"
TEST_GROUP(PreprocessorTest)
{
};
/* TODO: Need to fix this on all platforms! */
#if 0
#ifndef CPPUTEST_COMPILATION
TEST(PreprocessorTest, FailWhenCPPUTEST_COMPILATIONIsNotDefined)
{
FAIL("CPPUTEST_COMPILATION should always be defined when compiling CppUTest");
}
#endif
#endif
| null |
275 | cpp | blalor-cpputest | TestResultTest.cpp | tests/TestResultTest.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/PlatformSpecificFunctions.h"
#include "CppUTest/TestOutput.h"
static long MockGetPlatformSpecificTimeInMillis()
{
return 10;
}
TEST_GROUP(TestResult)
{
TestOutput* printer;
StringBufferTestOutput* mock;
TestResult* res;
void setup()
{
mock = new StringBufferTestOutput();
printer = mock;
res = new TestResult(*printer);
SetPlatformSpecificTimeInMillisMethod(MockGetPlatformSpecificTimeInMillis);
}
void teardown()
{
SetPlatformSpecificTimeInMillisMethod(0);
delete printer;
delete res;
}
};
TEST(TestResult, TestEndedWillPrintResultsAndExecutionTime)
{
res->testsEnded();
CHECK(mock->getOutput().contains("10 ms"));
}
| null |
276 | cpp | blalor-cpputest | PluginTest.cpp | tests/PluginTest.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/TestOutput.h"
#include "CppUTest/TestTestingFixture.h"
#define GENERIC_PLUGIN "GenericPlugin"
#define GENERIC_PLUGIN2 "GenericPlugin2"
#define GENERIC_PLUGIN3 "GenericPlugin3"
static int sequenceNumber;
class DummyPlugin: public TestPlugin
{
public:
DummyPlugin(const SimpleString& name) :
TestPlugin(name), preAction(0), postAction(0)
{
}
virtual ~DummyPlugin()
{
}
virtual void preTestAction(Utest&, TestResult&)
{
preAction++;
preActionSequence = sequenceNumber++;
}
virtual void postTestAction(Utest&, TestResult&)
{
postAction++;
postActionSequence = sequenceNumber++;
}
int preAction;
int preActionSequence;
int postAction;
int postActionSequence;
};
class DummyPluginWhichAcceptsParameters: public DummyPlugin
{
public:
DummyPluginWhichAcceptsParameters(const SimpleString& name) :
DummyPlugin(name)
{
}
virtual bool parseArguments(int ac, const char** av, int index)
{
SimpleString argument (av[index]);
if (argument == "-paccept")
return true;
return TestPlugin::parseArguments(ac, av, index);
}
};
TEST_GROUP(PluginTest)
{
DummyPlugin* firstPlugin;
DummyPluginWhichAcceptsParameters* secondPlugin;
DummyPlugin* thirdPlugin;
TestTestingFixture *genFixture;
TestRegistry *registry;
void setup()
{
firstPlugin = new DummyPlugin(GENERIC_PLUGIN);
secondPlugin = new DummyPluginWhichAcceptsParameters(GENERIC_PLUGIN2);
thirdPlugin = new DummyPlugin(GENERIC_PLUGIN3);
genFixture = new TestTestingFixture;
registry = genFixture->registry_;
registry->installPlugin(firstPlugin);
sequenceNumber = 1;
}
void teardown()
{
delete firstPlugin;
delete secondPlugin;
delete thirdPlugin;
delete genFixture;
}
};
#define GENERIC_PLUGIN "GenericPlugin"
#define GENERIC_PLUGIN4 "GenericPlugin4"
TEST(PluginTest, PluginHasName)
{
CHECK_EQUAL(GENERIC_PLUGIN, firstPlugin->getName());
}
TEST(PluginTest, InstallPlugin)
{
CHECK_EQUAL(firstPlugin, registry->getFirstPlugin());
CHECK_EQUAL(firstPlugin, registry->getPluginByName(GENERIC_PLUGIN));
}
TEST(PluginTest, InstallMultiplePlugins)
{
registry->installPlugin(thirdPlugin);
CHECK_EQUAL(firstPlugin, registry->getPluginByName(GENERIC_PLUGIN));
CHECK_EQUAL(thirdPlugin, registry->getPluginByName(GENERIC_PLUGIN3));
CHECK_EQUAL(0, registry->getPluginByName("I do not exist"));
}
TEST(PluginTest, ActionsAllRun)
{
genFixture->runAllTests();
genFixture->runAllTests();
CHECK_EQUAL(2, firstPlugin->preAction);
CHECK_EQUAL(2, firstPlugin->postAction);
}
TEST(PluginTest, Sequence)
{
registry->installPlugin(thirdPlugin);
genFixture->runAllTests();
CHECK_EQUAL(1, thirdPlugin->preActionSequence);
CHECK_EQUAL(2, firstPlugin->preActionSequence);
CHECK_EQUAL(3, firstPlugin->postActionSequence);
CHECK_EQUAL(4, thirdPlugin->postActionSequence);
}
TEST(PluginTest, DisablesPluginsDontRun)
{
registry->installPlugin(thirdPlugin);
thirdPlugin->disable();
genFixture->runAllTests();
CHECK(!thirdPlugin->isEnabled());
thirdPlugin->enable();
genFixture->runAllTests();
CHECK_EQUAL(2, firstPlugin->preAction);
CHECK_EQUAL(1, thirdPlugin->preAction);
CHECK(thirdPlugin->isEnabled());
}
TEST(PluginTest, ParseArgumentsForUnknownArgumentsFails)
{
registry->installPlugin(secondPlugin);
const char *cmd_line[] = {"nonsense", "andmorenonsense"};
CHECK(registry->getFirstPlugin()->parseAllArguments(2, cmd_line, 0) == false );
}
TEST(PluginTest, ParseArgumentsContinuesAndSucceedsWhenAPluginCanParse)
{
registry->installPlugin(secondPlugin);
const char *cmd_line[] = {"-paccept", "andmorenonsense"};
CHECK(registry->getFirstPlugin()->parseAllArguments(2, cmd_line, 0));
}
| null |
277 | cpp | blalor-cpputest | UtestTest.cpp | tests/UtestTest.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/TestRegistry.h"
#include "CppUTest/TestTestingFixture.h"
static bool afterCheck;
TEST_GROUP(Utest)
{
TestTestingFixture* fixture;
void setup()
{
fixture = new TestTestingFixture();
afterCheck = false;
}
void teardown()
{
delete fixture;
}
void testFailureWith(void(*method)())
{
fixture->setTestFunction(method);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
CHECK(!afterCheck);
}
void testFailureWithMethodShouldContain(void(*method)(), const char * expected)
{
fixture->setTestFunction(method);
fixture->runAllTests();
fixture->assertPrintContains(expected);
LONGS_EQUAL(1, fixture->getFailureCount());
CHECK(!afterCheck);
}
};
static void _passMethod()
{
CHECK(true);
afterCheck = true;
}
static void _passPrint()
{
UT_PRINT("Hello World!");
}
static void _passPrintF()
{
UT_PRINT(StringFromFormat("Hello %s %d", "World!", 2009));
}
static void _failMethod()
{
FAIL("This test fails");
afterCheck = true;
}
static void _failMethodFAIL_TEST()
{
FAIL_TEST("This test fails");
afterCheck = true;
}
static void _failMethodCHECK()
{
CHECK(false);
afterCheck = true;
}
static void _failMethodCHECK_TRUE()
{
CHECK_TRUE(false);
afterCheck = true;
}
static void _failMethodCHECK_FALSE()
{
CHECK_FALSE(true);
afterCheck = true;
}
static void _failMethodCHECK_EQUAL()
{
CHECK_EQUAL(1, 2);
afterCheck = true;
}
static void _failMethodSTRCMP_CONTAINS()
{
STRCMP_CONTAINS("hello", "world");
afterCheck = true;
}
static void _failMethodSTRCMP_NOCASE_CONTAINS()
{
STRCMP_NOCASE_CONTAINS("hello", "WORLD");
afterCheck = true;
}
static void _failMethodLONGS_EQUAL()
{
LONGS_EQUAL(1, 0xff);
afterCheck = true;
}
static void _failMethodBYTES_EQUAL()
{
BYTES_EQUAL('a', 'b');
afterCheck = true;
}
static void _failMethodPOINTERS_EQUAL()
{
POINTERS_EQUAL((void*)0xa5a5, (void*)0xf0f0);
afterCheck = true;
}
static void _failMethodDOUBLES_EQUAL()
{
DOUBLES_EQUAL(0.12, 44.1, 0.3);
afterCheck = true;
}
TEST(Utest, FailurePrintsSomething)
{
testFailureWith(_failMethod);
fixture->assertPrintContains(__FILE__);
fixture->assertPrintContains("This test fails");
}
TEST(Utest, FailureWithFailTest)
{
testFailureWith(_failMethodFAIL_TEST);
}
TEST(Utest, FailurePrintHexOutputForLongInts)
{
testFailureWith(_failMethodLONGS_EQUAL);
fixture->assertPrintContains("expected < 1 0x01>");
fixture->assertPrintContains("but was <255 0xff>");
}
TEST(Utest, FailurePrintHexOutputForPointers)
{
testFailureWith(_failMethodPOINTERS_EQUAL);
fixture->assertPrintContains("expected <0xa5a5>");
fixture->assertPrintContains("but was <0xf0f0>");
}
TEST(Utest, FailureWithDOUBLES_EQUAL)
{
testFailureWith(_failMethodDOUBLES_EQUAL);
}
#include "CppUTest/PlatformSpecificFunctions.h"
TEST(Utest, compareDoubles)
{
double zero = 0.0;
double nan = zero / zero;
CHECK(doubles_equal(1.0, 1.001, 0.01));
CHECK(!doubles_equal(nan, 1.001, 0.01));
CHECK(!doubles_equal(1.0, nan, 0.01));
CHECK(!doubles_equal(1.0, 1.001, nan));
CHECK(!doubles_equal(1.0, 1.1, 0.05));
double a = 1.2345678;
CHECK(doubles_equal(a, a, 0.000000001));
}
TEST(Utest, FailureWithCHECK)
{
testFailureWith(_failMethodCHECK);
}
TEST(Utest, FailureWithCHECK_TRUE)
{
testFailureWith(_failMethodCHECK_TRUE);
fixture->assertPrintContains("CHECK_TRUE");
}
TEST(Utest, FailureWithCHECK_FALSE)
{
testFailureWith(_failMethodCHECK_FALSE);
fixture->assertPrintContains("CHECK_FALSE");
}
TEST(Utest, FailureWithCHECK_EQUAL)
{
testFailureWith(_failMethodCHECK_EQUAL);
}
TEST(Utest, FailureWithSTRCMP_CONTAINS)
{
testFailureWith(_failMethodSTRCMP_CONTAINS);
}
TEST(Utest, FailureWithSTRCMP_NOCASE_CONTAINS)
{
testFailureWith(_failMethodSTRCMP_NOCASE_CONTAINS);
}
TEST(Utest, FailureWithBYTES_EQUAL)
{
testFailureWith(_failMethodBYTES_EQUAL);
}
TEST(Utest, SuccessPrintsNothing)
{
fixture->setTestFunction(_passMethod);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
fixture->assertPrintContains(".\nOK (1 tests");
CHECK(afterCheck);
}
TEST(Utest, PrintPrintsWhateverPrintPrints)
{
fixture->setTestFunction(_passPrint);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
fixture->assertPrintContains("Hello World!");
fixture->assertPrintContains(__FILE__);
}
TEST(Utest, PrintPrintsPrintf)
{
fixture->setTestFunction(_passPrintF);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
fixture->assertPrintContains("Hello World! 2009");
}
TEST(Utest, allMacros)
{
CHECK(0 == 0);
LONGS_EQUAL(1,1);
BYTES_EQUAL(0xab,0xab);
CHECK_EQUAL(100,100);
STRCMP_EQUAL("THIS", "THIS");
STRCMP_CONTAINS("THIS", "THISTHAT");
STRCMP_NOCASE_EQUAL("this", "THIS");
STRCMP_NOCASE_CONTAINS("this", "THISTHAT");
DOUBLES_EQUAL(1.0, 1.0, .01);
POINTERS_EQUAL(this, this);
}
static int functionThatReturnsAValue()
{
CHECK(0 == 0);
LONGS_EQUAL(1,1);
BYTES_EQUAL(0xab,0xab);
CHECK_EQUAL(100,100);
STRCMP_EQUAL("THIS", "THIS");
DOUBLES_EQUAL(1.0, 1.0, .01);
POINTERS_EQUAL(0, 0);
return 0;
}
TEST(Utest, allMacrosFromFunctionThatReturnsAValue)
{
functionThatReturnsAValue();
}
TEST(Utest, AssertsActLikeStatements)
{
if (fixture != 0) CHECK(true)
else CHECK(false)
if (fixture != 0) CHECK_EQUAL(true, true)
else CHECK_EQUAL(false, false)
if (fixture != 0) STRCMP_EQUAL("", "")
else STRCMP_EQUAL("", " ")
if (fixture != 0)
STRCMP_CONTAINS("con", "contains")
else
STRCMP_CONTAINS("hello", "world")
if (fixture != 0)
LONGS_EQUAL(1, 1)
else
LONGS_EQUAL(1, 0)
if (fixture != 0)
DOUBLES_EQUAL(1, 1, 0.01)
else
DOUBLES_EQUAL(1, 0, 0.01)
if (false)
FAIL("")
else CHECK(true);;
if (true) ;
else
FAIL("")
}
IGNORE_TEST(Utest, IgnoreTestSupportsAllMacros)
{
CHECK(true);
CHECK_EQUAL(true, true);
STRCMP_EQUAL("", "");
LONGS_EQUAL(1, 1);
DOUBLES_EQUAL(1, 1, 0.01);
FAIL("");
}
IGNORE_TEST(Utest, IgnoreTestAccessingFixture)
{
CHECK(fixture != 0);
}
TEST(Utest, MacrosUsedInSetup)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture->setSetup(_failMethod);
fixture->setTestFunction(_passMethod);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
TEST(Utest, MacrosUsedInTearDown)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture->setTeardown(_failMethod);
fixture->setTestFunction(_passMethod);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
static int teardownCalled = 0;
static void _teardownMethod()
{
teardownCalled++;
}
TEST(Utest, TeardownCalledAfterTestFailure)
{
teardownCalled = 0;
IGNORE_ALL_LEAKS_IN_TEST();
fixture->setTeardown(_teardownMethod);
fixture->setTestFunction(_failMethod);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
LONGS_EQUAL(1, teardownCalled);
}
static int stopAfterFailure = 0;
static void _stopAfterFailureMethod()
{
FAIL("fail");
stopAfterFailure++;
}
TEST(Utest, TestStopsAfterTestFailure)
{
IGNORE_ALL_LEAKS_IN_TEST();
stopAfterFailure = 0;
fixture->setTestFunction(_stopAfterFailureMethod);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
TEST(Utest, TestStopsAfterSetupFailure)
{
stopAfterFailure = 0;
fixture->setSetup(_stopAfterFailureMethod);
fixture->setTeardown(_stopAfterFailureMethod);
fixture->setTestFunction(_failMethod);
fixture->runAllTests();
LONGS_EQUAL(2, fixture->getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
static bool destructorWasCalledOnFailedTest = false;
class DestructorOughtToBeCalled
{
public:
virtual ~DestructorOughtToBeCalled()
{
destructorWasCalledOnFailedTest = true;
}
};
static void _destructorCalledForLocalObjects()
{
DestructorOughtToBeCalled pleaseCallTheDestructor;
destructorWasCalledOnFailedTest = false;
FAIL("fail");
}
/* This test can only pass when we use exception handling instead of longjmp */
IGNORE_TEST(Utest, DestructorIsCalledForLocalObjectsWhenTheTestFails)
{
fixture->setTestFunction(_destructorCalledForLocalObjects);
fixture->runAllTests();
CHECK(destructorWasCalledOnFailedTest);
}
TEST_BASE(MyOwnTest)
{
MyOwnTest() :
inTest(false)
{
}
bool inTest;
void setup()
{
CHECK(!inTest);
inTest = true;
}
void teardown()
{
CHECK(inTest);
inTest = false;
}
};
TEST_GROUP_BASE(UtestMyOwn, MyOwnTest)
{
};
TEST(UtestMyOwn, test)
{
CHECK(inTest);
}
class NullParameterTest: public Utest
{
};
TEST(UtestMyOwn, NullParameters)
{
NullParameterTest nullTest; /* Bug fix tests for creating a test without a name, fix in SimpleString */
TestRegistry* reg = TestRegistry::getCurrentRegistry();
nullTest.shouldRun(reg->getGroupFilter(), reg->getNameFilter());
}
| null |
278 | cpp | blalor-cpputest | TestInstallerTest.cpp | tests/TestInstallerTest.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"
// this is file scope because the test is installed
// with all other tests, which also happen to be
// created as static instances at file scope
static NullTest nullTest;
TEST_GROUP(TestInstaller)
{
TestInstaller* testInstaller;
TestRegistry* myRegistry;
void setup()
{
myRegistry = new TestRegistry();
myRegistry->setCurrentRegistry(myRegistry);
testInstaller = new TestInstaller(&nullTest, "TestInstaller", "test", __FILE__, __LINE__);
}
void teardown()
{
myRegistry->setCurrentRegistry(0);
testInstaller->unDo();
delete testInstaller;
delete myRegistry;
}
};
TEST(TestInstaller, Create)
{
}
| null |
279 | cpp | blalor-cpputest | TestHarness_cTest.cpp | tests/TestHarness_cTest.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.
*/
extern "C"
{
#define _WCHART
#include "CppUTest/TestHarness_c.h"
}
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTest/PlatformSpecificFunctions.h"
TEST_GROUP(TestHarness_c)
{
TestTestingFixture* fixture;
TEST_SETUP()
{
fixture = new TestTestingFixture();
}
TEST_TEARDOWN()
{
delete fixture;
}
};
void _failIntMethod()
{
CHECK_EQUAL_C_INT(1, 2);
}
TEST(TestHarness_c, checkInt)
{
CHECK_EQUAL_C_INT(2, 2);
fixture->setTestFunction(_failIntMethod);
fixture->runAllTests();
fixture->assertPrintContains("expected <1>\n but was <2>");
fixture->assertPrintContains("arness_c");
}
void _failRealMethod()
{
CHECK_EQUAL_C_REAL(1.0, 2.0, 0.5);
}
TEST(TestHarness_c, checkReal)
{
CHECK_EQUAL_C_REAL(1.0, 1.1, 0.5);
fixture->setTestFunction(_failRealMethod);
fixture->runAllTests();
fixture->assertPrintContains("expected <1.000000>\n but was <2.000000>");
fixture->assertPrintContains("arness_c");
}
void _failCharMethod()
{
CHECK_EQUAL_C_CHAR('a', 'c');
}
TEST(TestHarness_c, checkChar)
{
CHECK_EQUAL_C_CHAR('a', 'a');
fixture->setTestFunction(_failCharMethod);
fixture->runAllTests();
fixture->assertPrintContains("expected <a>\n but was <c>");
fixture->assertPrintContains("arness_c");
}
void _failStringMethod()
{
CHECK_EQUAL_C_STRING("Hello", "Hello World");
}
TEST(TestHarness_c, checkString)
{
CHECK_EQUAL_C_STRING("Hello", "Hello");
fixture->setTestFunction(_failStringMethod);
fixture->runAllTests();
StringEqualFailure failure(this, "file", 1, "Hello", "Hello World");
fixture->assertPrintContains(failure.getMessage());
fixture->assertPrintContains("arness_c");
}
void _failTextMethod()
{
FAIL_TEXT_C("Booo");
}
TEST(TestHarness_c, checkFailText)
{
fixture->setTestFunction(_failTextMethod);
fixture->runAllTests();
fixture->assertPrintContains("Booo");
fixture->assertPrintContains("arness_c");
}
void _failMethod()
{
FAIL_C();
}
TEST(TestHarness_c, checkFail)
{
fixture->setTestFunction(_failMethod);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
fixture->assertPrintContains("arness_c");
}
void _CheckMethod()
{
CHECK_C(false);
}
TEST(TestHarness_c, checkCheck)
{
CHECK_C(true);
fixture->setTestFunction(_CheckMethod);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
TEST(TestHarness_c, cpputest_malloc_out_of_memory)
{
cpputest_malloc_set_out_of_memory();
CHECK(0 == cpputest_malloc(100));
cpputest_malloc_set_not_out_of_memory();
void * mem = cpputest_malloc(100);
CHECK(0 != mem);
cpputest_free(mem);
}
TEST(TestHarness_c, cpputest_malloc_out_of_memory_after_n_mallocs)
{
cpputest_malloc_set_out_of_memory_countdown(3);
void * m1 = cpputest_malloc(10);
void * m2 = cpputest_malloc(11);
void * m3 = cpputest_malloc(12);
CHECK(m1);
CHECK(m2);
POINTERS_EQUAL(0, m3);
cpputest_malloc_set_not_out_of_memory();
cpputest_free(m1);
cpputest_free(m2);
}
TEST(TestHarness_c, cpputest_malloc_out_of_memory_after_0_mallocs)
{
cpputest_malloc_set_out_of_memory_countdown(0);
void * m1 = cpputest_malloc(10);
CHECK(m1 == 0);
cpputest_malloc_set_not_out_of_memory();
}
TEST(TestHarness_c, count_mallocs)
{
cpputest_malloc_count_reset();
void * m1 = cpputest_malloc(10);
void * m2 = cpputest_malloc(11);
void * m3 = cpputest_malloc(12);
cpputest_free(m1);
cpputest_free(m2);
cpputest_free(m3);
LONGS_EQUAL(3, cpputest_malloc_get_count());
}
TEST(TestHarness_c, cpputest_calloc)
{
void * mem = cpputest_calloc(10, 10);
CHECK(0 != mem);
cpputest_free(mem);
}
TEST(TestHarness_c, cpputest_realloc_larger)
{
const char* number_string = "123456789";
char* mem1 = (char*) cpputest_malloc(10);
PlatformSpecificStrCpy(mem1, number_string);
CHECK(mem1 != 0);
char* mem2 = (char*) cpputest_realloc(mem1, 1000);
CHECK(mem2 != 0);
STRCMP_EQUAL(number_string, mem2);
cpputest_free(mem2);
}
#if CPPUTEST_USE_MEM_LEAK_DETECTION
TEST(TestHarness_c, macros)
{
void* mem1 = malloc(10);
void* mem2 = calloc(10, 20);
void* mem3 = realloc(mem2, 100);
free(mem1);
free(mem3);
}
TEST(TestHarness_c, callocInitializedToZero)
{
char* mem = (char*) calloc(20, sizeof(char));
for (int i = 0; i < 20; i++)
CHECK(mem[i] == 0);
free(mem);
}
#endif
| null |
280 | cpp | blalor-cpputest | SimpleStringFromStdintTest.cpp | tests/Extensions/SimpleStringFromStdintTest.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/Extensions/SimpleStringFromStdint.h"
#include <stdint.h>
TEST_GROUP(SimpleStringFromStdint)
{
};
using namespace std;
//uint64_t silently not supported in C++
TEST(SimpleStringFromStdint, Uint64_t)
{
//I'd like this test, but can't get it to pass
// uint64_t = 0xffffffffffffffff;
//
// SimpleString result = StringFrom(i);
// CHECK_EQUAL("18446744073709551615 (0xffffffffffffffff)", result);
uint64_t i = 10;
SimpleString result = StringFrom(i);
CHECK_EQUAL("uint64_t not supported", result);
}
TEST(SimpleStringFromStdint, Int64_t)
{
//I'd like this test, but can't get it to pass
// int64_t i = 0xffffffffffffffff>>1;
//
// SimpleString result = StringFrom(i);
// CHECK_EQUAL("something", result);
// TP: commented out as StringFrom(int64_t) is clashing with StringFrom(long) in 64-bit environment
/* int64_t i = 10;
SimpleString result = StringFrom(i);
CHECK_EQUAL("int64_t not supported", result);*/
}
TEST(SimpleStringFromStdint, Uint32_t)
{
uint32_t i = 0xffffffff;
SimpleString result = StringFrom(i);
CHECK_EQUAL("4294967295 (0xffffffff)", result);
}
TEST(SimpleStringFromStdint, Uint16_t)
{
uint16_t i = 0xffff;
SimpleString result = StringFrom(i);
CHECK_EQUAL("65535 (0xffff)", result);
}
TEST(SimpleStringFromStdint, Uint8_t)
{
uint8_t i = 0xff;
SimpleString result = StringFrom(i);
CHECK_EQUAL("255 (0xff)", result);
}
IGNORE_TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint64_t)
{
// uint64_t i = 0xffffffffffffffff;
// CHECK_EQUAL(i, i);
}
TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint32_t)
{
uint32_t i = 0xffffffff;
CHECK_EQUAL(i, i);
}
TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint16_t)
{
uint16_t i = 0xffff;
CHECK_EQUAL(i, i);
}
TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint8_t)
{
uint8_t i = 0xff;
CHECK_EQUAL(i, i);
}
| null |
281 | cpp | blalor-cpputest | SimpleStringExtensionsTest.cpp | tests/Extensions/SimpleStringExtensionsTest.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/Extensions/SimpleStringExtensions.h"
#include "CppUTest/TestHarness.h"
TEST_GROUP(SimpleStringExtensions)
{
};
using namespace std;
TEST(SimpleStringExtensions, fromStdString)
{
string s("hello");
SimpleString s1(StringFrom(s));
STRCMP_EQUAL("hello", s1.asCharString());
}
| null |
282 | cpp | blalor-cpputest | AllTests.h | tests/Extensions/AllTests.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.
*/
//Include this in the test main to execute these tests
IMPORT_TEST_GROUP( SimpleStringExtensions);
IMPORT_TEST_GROUP( TestOrderedTest);
| null |
283 | cpp | blalor-cpputest | TestOrderedTest.cpp | tests/Extensions/TestOrderedTest.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/TestRegistry.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTest/Extensions/OrderedTest.h"
TEST_GROUP(TestOrderedTest)
{ TestTestingFixture* fixture;
OrderedTest orderedTest;
OrderedTest orderedTest2;
OrderedTest orderedTest3;
ExecFunctionTest normalTest;
ExecFunctionTest normalTest2;
ExecFunctionTest normalTest3;
OrderedTest* orderedTestCache;
void setup()
{
orderedTestCache = OrderedTest::getOrderedTestHead();
OrderedTest::setOrderedTestHead(0);
fixture = new TestTestingFixture();
fixture->registry_->unDoLastAddTest();
}
void teardown()
{
delete fixture;
OrderedTest::setOrderedTestHead(orderedTestCache);
}
void InstallOrderedTest(OrderedTest* test, int level)
{
OrderedTestInstaller(test, "testgroup", "testname", __FILE__, __LINE__, level);
}
void InstallNormalTest(Utest* test)
{
TestInstaller(test, "testgroup", "testname", __FILE__, __LINE__);
}
Utest* firstTest()
{
return fixture->registry_->getFirstTest();
}
Utest* secondTest()
{
return fixture->registry_->getFirstTest()->getNext();
}
};
TEST(TestOrderedTest, TestInstallerSetsFields)
{
OrderedTestInstaller(&orderedTest, "testgroup", "testname", "this.cpp", 10,
5);
STRCMP_EQUAL("testgroup", orderedTest.getGroup().asCharString());
STRCMP_EQUAL("testname", orderedTest.getName().asCharString());
STRCMP_EQUAL("this.cpp", orderedTest.getFile().asCharString());
LONGS_EQUAL(10, orderedTest.getLineNumber());
LONGS_EQUAL(5, orderedTest.getLevel());
}
TEST(TestOrderedTest, InstallOneText)
{
InstallOrderedTest(&orderedTest, 5);
CHECK(firstTest() == &orderedTest);
}
TEST(TestOrderedTest, OrderedTestsAreLast)
{
InstallNormalTest(&normalTest);
InstallOrderedTest(&orderedTest, 5);
CHECK(firstTest() == &normalTest);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, TwoTestsAddedInReverseOrder)
{
InstallOrderedTest(&orderedTest, 5);
InstallOrderedTest(&orderedTest2, 3);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, TwoTestsAddedInOrder)
{
InstallOrderedTest(&orderedTest2, 3);
InstallOrderedTest(&orderedTest, 5);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, MultipleOrderedTests)
{
InstallNormalTest(&normalTest);
InstallOrderedTest(&orderedTest2, 3);
InstallNormalTest(&normalTest2);
InstallOrderedTest(&orderedTest, 5);
InstallNormalTest(&normalTest3);
InstallOrderedTest(&orderedTest3, 7);
Utest * firstOrderedTest = firstTest()->getNext()->getNext()->getNext();
CHECK(firstOrderedTest == &orderedTest2);
CHECK(firstOrderedTest->getNext() == &orderedTest);
CHECK(firstOrderedTest->getNext()->getNext() == &orderedTest3);
}
TEST(TestOrderedTest, MultipleOrderedTests2)
{
InstallOrderedTest(&orderedTest, 3);
InstallOrderedTest(&orderedTest2, 1);
InstallOrderedTest(&orderedTest3, 2);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest3);
CHECK(secondTest()->getNext() == &orderedTest);
}
TEST_GROUP_BASE(TestOrderedTestMacros, OrderedTest)
{};
static int testNumber = 0;
TEST(TestOrderedTestMacros, NormalTest)
{
CHECK(testNumber == 0);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test2, 2)
{
CHECK(testNumber == 2);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test1, 1)
{
CHECK(testNumber == 1);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test4, 4)
{
CHECK(testNumber == 4);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test3, 3)
{
CHECK(testNumber == 3);
testNumber++;
}
| null |
284 | cpp | blalor-cpputest | AllTests.cpp | tests/CppUTestExt/AllTests.cpp | null | /*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/CommandLineTestRunner.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTestExt/MemoryReporterPlugin.h"
#include "CppUTestExt/MockSupportPlugin.h"
int main(int ac, const char** av)
{
MemoryReporterPlugin plugin;
MockSupportPlugin mockPlugin;
TestRegistry::getCurrentRegistry()->installPlugin(&plugin);
TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin);
return CommandLineTestRunner::RunAllTests(ac, av);
}
| null |
285 | cpp | blalor-cpputest | TestMemoryReportFormatter.cpp | tests/CppUTestExt/TestMemoryReportFormatter.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 "CppUTestExt/MemoryReportAllocator.h"
#include "CppUTestExt/MemoryReportFormatter.h"
#define TESTOUPUT_EQUAL(a) STRCMP_EQUAL_LOCATION(a, testOutput.getOutput().asCharString(), __FILE__, __LINE__);
#define TESTOUPUT_CONTAINS(a) STRCMP_CONTAINS_LOCATION(a, testOutput.getOutput().asCharString(), __FILE__, __LINE__);
TEST_GROUP(NormalMemoryReportFormatter)
{
char* memory01;
StringBufferTestOutput testOutput;
TestResult* testResult;
NormalMemoryReportFormatter formatter;
void setup()
{
memory01 = (char*) 0x01;
testResult = new TestResult(testOutput);
}
void teardown()
{
delete testResult;
}
};
TEST(NormalMemoryReportFormatter, mallocCreatesAnMallocCall)
{
formatter.report_alloc_memory(testResult, StandardMallocAllocator::defaultAllocator(), 10, memory01, "file", 9);
TESTOUPUT_EQUAL(StringFromFormat("\tAllocation using malloc of size: 10 pointer: %p at file:9\n", memory01).asCharString());
}
TEST(NormalMemoryReportFormatter, freeCreatesAnFreeCall)
{
formatter.report_free_memory(testResult, StandardMallocAllocator::defaultAllocator(), memory01, "boo", 6);
TESTOUPUT_EQUAL(StringFromFormat("\tDeallocation using free of pointer: %p at boo:6\n", memory01).asCharString());
}
TEST(NormalMemoryReportFormatter, testStarts)
{
Utest test("groupName", "TestName", "file", 1);
formatter.report_test_start(testResult, test);
TESTOUPUT_EQUAL("TEST(groupName, TestName)\n");
}
TEST(NormalMemoryReportFormatter, testEnds)
{
Utest test("groupName", "TestName", "file", 1);
formatter.report_test_end(testResult, test);
TESTOUPUT_EQUAL("ENDTEST(groupName, TestName)\n");
}
TEST(NormalMemoryReportFormatter, testGroupStarts)
{
Utest test("groupName", "TestName", "file", 1);
formatter.report_testgroup_start(testResult, test);
TESTOUPUT_EQUAL("------------------------------TEST GROUP(groupName)-----------------------------\n");
}
| null |
286 | cpp | blalor-cpputest | TestMockExpectedFunctionsList.cpp | tests/CppUTestExt/TestMockExpectedFunctionsList.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"
#include "CppUTestExt/MockFailure.h"
#include "TestMockFailure.h"
TEST_GROUP(MockExpectedFunctionsList)
{
MockExpectedFunctionsList * list;
MockExpectedFunctionCall* call1;
MockExpectedFunctionCall* call2;
MockExpectedFunctionCall* call3;
MockExpectedFunctionCall* call4;
void setup()
{
list = new MockExpectedFunctionsList;
call1 = new MockExpectedFunctionCall;
call2 = new MockExpectedFunctionCall;
call3 = new MockExpectedFunctionCall;
call4 = new MockExpectedFunctionCall;
call1->withName("foo");
call2->withName("bar");
call3->withName("boo");
}
void teardown()
{
delete call1;
delete call2;
delete call3;
delete call4;
delete list;
CHECK_NO_MOCK_FAILURE();
}
};
TEST(MockExpectedFunctionsList, emptyList)
{
CHECK(! list->hasUnfullfilledExpectations());
CHECK(! list->hasFulfilledExpectations());
LONGS_EQUAL(0, list->size());
}
TEST(MockExpectedFunctionsList, addingCalls)
{
list->addExpectedCall(call1);
list->addExpectedCall(call2);
LONGS_EQUAL(2, list->size());
}
TEST(MockExpectedFunctionsList, listWithFulfilledExpectationHasNoUnfillfilledOnes)
{
call1->callWasMade(1);
call2->callWasMade(2);
list->addExpectedCall(call1);
list->addExpectedCall(call2);
CHECK(! list->hasUnfullfilledExpectations());
}
TEST(MockExpectedFunctionsList, listWithFulfilledExpectationButOutOfOrder)
{
call1->withCallOrder(1);
call2->withCallOrder(2);
list->addExpectedCall(call1);
list->addExpectedCall(call2);
call2->callWasMade(1);
call1->callWasMade(2);
CHECK(! list->hasUnfullfilledExpectations());
CHECK(list->hasCallsOutOfOrder());
}
TEST(MockExpectedFunctionsList, listWithUnFulfilledExpectationHasNoUnfillfilledOnes)
{
call1->callWasMade(1);
call3->callWasMade(2);
list->addExpectedCall(call1);
list->addExpectedCall(call2);
list->addExpectedCall(call3);
CHECK(list->hasUnfullfilledExpectations());
}
TEST(MockExpectedFunctionsList, deleteAllExpectationsAndClearList)
{
list->addExpectedCall(new MockExpectedFunctionCall);
list->addExpectedCall(new MockExpectedFunctionCall);
list->deleteAllExpectationsAndClearList();
}
TEST(MockExpectedFunctionsList, onlyKeepUnfulfilledExpectationsRelatedTo)
{
call1->withName("relate");
call2->withName("unrelate");
call3->withName("relate");
call3->callWasMade(1);
list->addExpectedCall(call1);
list->addExpectedCall(call2);
list->addExpectedCall(call3);
list->onlyKeepUnfulfilledExpectationsRelatedTo("relate");
LONGS_EQUAL(1, list->size());
}
TEST(MockExpectedFunctionsList, removeAllExpectationsExceptThisThatRelateToTheWoleList)
{
call1->withName("relate");
call2->withName("relate");
call3->withName("relate");
list->addExpectedCall(call1);
list->addExpectedCall(call2);
list->addExpectedCall(call3);
list->onlyKeepUnfulfilledExpectationsRelatedTo("unrelate");
LONGS_EQUAL(0, list->size());
}
TEST(MockExpectedFunctionsList, removeAllExpectationsExceptThisThatRelateToFirstOne)
{
call1->withName("relate");
call2->withName("unrelate");
list->addExpectedCall(call1);
list->addExpectedCall(call2);
list->onlyKeepUnfulfilledExpectationsRelatedTo("unrelate");
LONGS_EQUAL(1, list->size());
}
TEST(MockExpectedFunctionsList, removeAllExpectationsExceptThisThatRelateToLastOne)
{
call1->withName("unrelate");
call2->withName("relate");
list->addExpectedCall(call1);
list->addExpectedCall(call2);
list->onlyKeepUnfulfilledExpectationsRelatedTo("unrelate");
LONGS_EQUAL(1, list->size());
}
TEST(MockExpectedFunctionsList, onlyKeepExpectationsWithParameterName)
{
call1->withName("func").withParameter("param", 1);
call2->withName("func").withParameter("diffname", 1);
call3->withName("func").withParameter("diffname", 1);
list->addExpectedCall(call1);
list->addExpectedCall(call2);
list->addExpectedCall(call3);
list->onlyKeepExpectationsWithParameterName("diffname");
LONGS_EQUAL(2, list->size());
}
TEST(MockExpectedFunctionsList, onlyKeepUnfulfilledExpectationsWithParameter)
{
MockNamedValue parameter("diffname");
parameter.setValue(1);
call1->withName("func").withParameter("param", 1);
call2->withName("func").withParameter("diffname", 1);
call3->withName("func").withParameter("diffname", 1);
call4->withName("func").withParameter("diffname", 2);
call3->callWasMade(1);
call3->parameterWasPassed("diffname");
list->addExpectedCall(call1);
list->addExpectedCall(call2);
list->addExpectedCall(call3);
list->addExpectedCall(call4);
list->onlyKeepUnfulfilledExpectationsWithParameter(parameter);
LONGS_EQUAL(1, list->size());
}
TEST(MockExpectedFunctionsList, addUnfilfilledExpectationsWithEmptyList)
{
MockExpectedFunctionsList newList;
newList.addUnfilfilledExpectations(*list);
LONGS_EQUAL(0, newList.size());
}
TEST(MockExpectedFunctionsList, addUnfilfilledExpectationsMultipleUnfulfilledExpectations)
{
call2->callWasMade(1);
list->addExpectedCall(call1);
list->addExpectedCall(call2);
list->addExpectedCall(call3);
MockExpectedFunctionsList newList;
newList.addUnfilfilledExpectations(*list);
LONGS_EQUAL(2, newList.size());
}
TEST(MockExpectedFunctionsList, amountOfExpectationsFor)
{
call1->withName("foo");
call2->withName("bar");
list->addExpectedCall(call1);
list->addExpectedCall(call2);
LONGS_EQUAL(1, list->amountOfExpectationsFor("bar"));
}
TEST(MockExpectedFunctionsList, amountOfExpectationsForHasNone)
{
call1->withName("foo");
list->addExpectedCall(call1);
LONGS_EQUAL(0, list->amountOfExpectationsFor("bar"));
}
TEST(MockExpectedFunctionsList, callToStringForUnfulfilledFunctions)
{
call1->withName("foo");
call2->withName("bar");
call3->withName("blah");
call3->callWasMade(1);
list->addExpectedCall(call1);
list->addExpectedCall(call2);
list->addExpectedCall(call3);
SimpleString expectedString;
expectedString = StringFromFormat("%s\n%s", call1->callToString().asCharString(), call2->callToString().asCharString());
STRCMP_EQUAL(expectedString.asCharString(), list->unfulfilledFunctionsToString().asCharString());
}
TEST(MockExpectedFunctionsList, callToStringForFulfilledFunctions)
{
call1->withName("foo");
call2->withName("bar");
call2->callWasMade(1);
call1->callWasMade(2);
list->addExpectedCall(call1);
list->addExpectedCall(call2);
SimpleString expectedString;
expectedString = StringFromFormat("%s\n%s", call2->callToString().asCharString(), call1->callToString().asCharString());
STRCMP_EQUAL(expectedString.asCharString(), list->fulfilledFunctionsToString().asCharString());
}
TEST(MockExpectedFunctionsList, toStringOnEmptyList)
{
STRCMP_EQUAL("<none>", list->unfulfilledFunctionsToString().asCharString());
}
| null |
287 | cpp | blalor-cpputest | TestMemoryReportAllocator.cpp | tests/CppUTestExt/TestMemoryReportAllocator.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 "CppUTestExt/MemoryReportAllocator.h"
#include "CppUTestExt/MemoryReportFormatter.h"
TEST_GROUP(MemoryReportAllocator)
{
};
TEST(MemoryReportAllocator, FunctionsAreForwardedForMallocAllocator)
{
MemoryReportAllocator allocator;
allocator.setRealAllocator(StandardMallocAllocator::getCurrentMallocAllocator());
CHECK(StandardMallocAllocator::getCurrentMallocAllocator()->allocateMemoryLeakNodeSeparately() == allocator.allocateMemoryLeakNodeSeparately());
}
| null |
288 | cpp | blalor-cpputest | TestMockSupport_c.cpp | tests/CppUTestExt/TestMockSupport_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"
extern "C" {
#include "CppUTest/TestHarness_c.h"
#include "CppUTestExt/MockSupport_c.h"
#include "TestMockSupport_cCFile.h"
}
TEST_GROUP(MockSupport_c)
{
};
TEST(MockSupport_c, expectAndActualOneCall)
{
mock_c()->expectOneCall("boo");
mock_c()->actualCall("boo");
mock_c()->checkExpectations();
}
TEST(MockSupport_c, expectAndActualParameters)
{
mock_c()->expectOneCall("boo")->withIntParameters("integer", 1)->withDoubleParameters("doube", 1.0)->
withStringParameters("string", "string")->withPointerParameters("pointer", (void*) 1);
mock_c()->actualCall("boo")->withIntParameters("integer", 1)->withDoubleParameters("doube", 1.0)->
withStringParameters("string", "string")->withPointerParameters("pointer", (void*) 1);
}
int typeNameIsEqual(void* object1, void* object2)
{
return object1 == object2;
}
char* typeNameValueToString(void* PUNUSED(object))
{
return (char*) "valueToString";
}
TEST(MockSupport_c, expectAndActualParametersOnObject)
{
mock_c()->installComparator("typeName", typeNameIsEqual, typeNameValueToString);
mock_c()->expectOneCall("boo")->withParameterOfType("typeName", "name", (void*) 1);
mock_c()->actualCall("boo")->withParameterOfType("typeName", "name", (void*) 1);
mock_c()->checkExpectations();
mock_c()->removeAllComparators();
}
TEST(MockSupport_c, returnIntValue)
{
mock_c()->expectOneCall("boo")->andReturnIntValue(10);
LONGS_EQUAL(10, mock_c()->actualCall("boo")->returnValue().value.intValue);
LONGS_EQUAL(MOCKVALUETYPE_INTEGER, mock_c()->returnValue().type);
}
TEST(MockSupport_c, returnDoubleValue)
{
mock_c()->expectOneCall("boo")->andReturnDoubleValue(1.0);
DOUBLES_EQUAL(1.0, mock_c()->actualCall("boo")->returnValue().value.doubleValue, 0.005);
LONGS_EQUAL(MOCKVALUETYPE_DOUBLE, mock_c()->returnValue().type);
}
TEST(MockSupport_c, returnStringValue)
{
mock_c()->expectOneCall("boo")->andReturnStringValue("hello world");
STRCMP_EQUAL("hello world", mock_c()->actualCall("boo")->returnValue().value.stringValue);
LONGS_EQUAL(MOCKVALUETYPE_STRING, mock_c()->returnValue().type);
}
TEST(MockSupport_c, returnPointerValue)
{
mock_c()->expectOneCall("boo")->andReturnPointerValue((void*) 10);
POINTERS_EQUAL((void*) 10, mock_c()->actualCall("boo")->returnValue().value.pointerValue);
LONGS_EQUAL(MOCKVALUETYPE_POINTER, mock_c()->returnValue().type);
}
TEST(MockSupport_c, MockSupportWithScope)
{
mock_scope_c("scope")->expectOneCall("boo");
LONGS_EQUAL(0, mock_scope_c("other")->expectedCallsLeft());
LONGS_EQUAL(1, mock_scope_c("scope")->expectedCallsLeft());
mock_scope_c("scope")->actualCall("boo");
}
TEST(MockSupport_c, MockSupportSetIntData)
{
mock_c()->setIntData("integer", 10);
LONGS_EQUAL(10, mock_c()->getData("integer").value.intValue);
}
TEST(MockSupport_c, MockSupportSetDoubleData)
{
mock_c()->setDoubleData("double", 1.0);
DOUBLES_EQUAL(1.00, mock_c()->getData("double").value.doubleValue, 0.05);
}
TEST(MockSupport_c, MockSupportSetStringData)
{
mock_c()->setStringData("string", "hello world");
STRCMP_EQUAL("hello world", mock_c()->getData("string").value.stringValue);
}
TEST(MockSupport_c, MockSupportSetPointerData)
{
mock_c()->setPointerData("pointer", (void*) 1);
POINTERS_EQUAL((void*) 1, mock_c()->getData("pointer").value.pointerValue);
}
TEST(MockSupport_c, MockSupportSetDataObject)
{
mock_c()->setDataObject("name", "type", (void*) 1);
POINTERS_EQUAL((void*) 1, mock_c()->getData("name").value.objectValue);
}
TEST(MockSupport_c, WorksInCFile)
{
all_mock_support_c_calls();
}
| null |
289 | cpp | blalor-cpputest | TestMockFailure.cpp | tests/CppUTestExt/TestMockFailure.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"
#include "TestMockFailure.h"
TEST_GROUP(MockFailureTest)
{
MockFailureReporter reporter;
MockExpectedFunctionsList *list;
MockExpectedFunctionCall* call1;
MockExpectedFunctionCall* call2;
MockExpectedFunctionCall* call3;
void setup ()
{
list = new MockExpectedFunctionsList;
call1 = new MockExpectedFunctionCall;
call2 = new MockExpectedFunctionCall;
call3 = new MockExpectedFunctionCall;
}
void teardown ()
{
delete list;
delete call1;
delete call2;
delete call3;
CHECK_NO_MOCK_FAILURE();
}
void addAllToList()
{
list->addExpectedCall(call1);
list->addExpectedCall(call2);
list->addExpectedCall(call3);
}
};
TEST(MockFailureTest, noErrorFailureSomethingGoneWrong)
{
MockFailure failure(this);
STRCMP_EQUAL("Test failed with MockFailure without an error! Something went seriously wrong.", failure.getMessage().asCharString());
}
TEST(MockFailureTest, unexpectedCallHappened)
{
MockUnexpectedCallHappenedFailure failure(this, "foobar", *list);
STRCMP_EQUAL("Mock Failure: Unexpected call to function: foobar\n"
"\tEXPECTED calls that did NOT happen:\n"
"\t\t<none>\n"
"\tACTUAL calls that did happen (in call order):\n"
"\t\t<none>", failure.getMessage().asCharString());
}
TEST(MockFailureTest, expectedCallDidNotHappen)
{
call1->withName("foobar");
call2->withName("world").withParameter("boo", 2).withParameter("hello", "world");
call3->withName("haphaphap");
call3->callWasMade(1);
addAllToList();
MockExpectedCallsDidntHappenFailure failure(this, *list);
STRCMP_EQUAL("Mock Failure: Expected call did not happen.\n"
"\tEXPECTED calls that did NOT happen:\n"
"\t\tfoobar -> no parameters\n"
"\t\tworld -> int boo: <2>, char* hello: <world>\n"
"\tACTUAL calls that did happen (in call order):\n"
"\t\thaphaphap -> no parameters", failure.getMessage().asCharString());
}
TEST(MockFailureTest, MockUnexpectedAdditionalCallFailure)
{
call1->withName("bar");
call1->callWasMade(1);
list->addExpectedCall(call1);
MockUnexpectedCallHappenedFailure failure(this, "bar", *list);
STRCMP_CONTAINS("Mock Failure: Unexpected additional (2th) call to function: bar\n\tEXPECTED", failure.getMessage().asCharString());
}
TEST(MockFailureTest, MockUnexpectedParameterFailure)
{
call1->withName("foo").withParameter("boo", 2);
call2->withName("foo").withParameter("boo", 10);
call3->withName("unrelated");
addAllToList();
MockNamedValue actualParameter("bar");
actualParameter.setValue(2);
MockUnexpectedParameterFailure failure(this, "foo", actualParameter, *list);
STRCMP_EQUAL("Mock Failure: Unexpected parameter name to function \"foo\": bar\n"
"\tEXPECTED calls that DID NOT happen related to function: foo\n"
"\t\tfoo -> int boo: <2>\n"
"\t\tfoo -> int boo: <10>\n"
"\tACTUAL calls that DID happen related to function: foo\n"
"\t\t<none>\n"
"\tACTUAL unexpected parameter passed to function: foo\n"
"\t\tint bar: <2>", failure.getMessage().asCharString());
}
TEST(MockFailureTest, MockUnexpectedParameterValueFailure)
{
call1->withName("foo").withParameter("boo", 2);
call2->withName("foo").withParameter("boo", 10);
call3->withName("unrelated");
addAllToList();
MockNamedValue actualParameter("boo");
actualParameter.setValue(20);
MockUnexpectedParameterFailure failure(this, "foo", actualParameter, *list);
STRCMP_EQUAL("Mock Failure: Unexpected parameter value to parameter \"boo\" to function \"foo\": <20>\n"
"\tEXPECTED calls that DID NOT happen related to function: foo\n"
"\t\tfoo -> int boo: <2>\n"
"\t\tfoo -> int boo: <10>\n"
"\tACTUAL calls that DID happen related to function: foo\n"
"\t\t<none>\n"
"\tACTUAL unexpected parameter passed to function: foo\n"
"\t\tint boo: <20>", failure.getMessage().asCharString());
}
TEST(MockFailureTest, MockExpectedParameterDidntHappenFailure)
{
call1->withName("foo").withParameter("bar", 2).withParameter("boo", "str");
call2->withName("foo").withParameter("bar", 10).withParameter("boo", "bleh");
call2->callWasMade(1);
call2->parameterWasPassed("bar");
call2->parameterWasPassed("boo");
call3->withName("unrelated");
addAllToList();
MockExpectedParameterDidntHappenFailure failure(this, "foo", *list);
STRCMP_EQUAL("Mock Failure: Expected parameter for function \"foo\" did not happen.\n"
"\tEXPECTED calls that DID NOT happen related to function: foo\n"
"\t\tfoo -> int bar: <2>, char* boo: <str>\n"
"\tACTUAL calls that DID happen related to function: foo\n"
"\t\tfoo -> int bar: <10>, char* boo: <bleh>\n"
"\tMISSING parameters that didn't happen:\n"
"\t\tint bar, char* boo", failure.getMessage().asCharString());
}
TEST(MockFailureTest, MockNoWayToCompareCustomTypeFailure)
{
MockNoWayToCompareCustomTypeFailure failure(this, "myType");
STRCMP_EQUAL("MockFailure: No way to compare type <myType>. Please install a ParameterTypeComparator.", failure.getMessage().asCharString());
}
TEST(MockFailureTest, MockUnexpectedObjectFailure)
{
call1->withName("foo").onObject((void*) 0x02);
call2->withName("foo").onObject((void*) 0x03);
call2->callWasMade(1);
call2->wasPassedToObject();
call3->withName("unrelated");
addAllToList();
MockUnexpectedObjectFailure failure(this, "foo", (void*)0x1, *list);
STRCMP_EQUAL("MockFailure: Function called on a unexpected object: foo\n"
"\tActual object for call has address: <0x1>\n"
"\tEXPECTED calls that DID NOT happen related to function: foo\n"
"\t\t(object address: 0x2)::foo -> no parameters\n"
"\tACTUAL calls that DID happen related to function: foo\n"
"\t\t(object address: 0x3)::foo -> no parameters", failure.getMessage().asCharString());
}
TEST(MockFailureTest, MockExpectedObjectDidntHappenFailure)
{
call1->withName("foo").onObject((void*) 0x02);
call2->withName("foo").onObject((void*) 0x03);
call2->callWasMade(1);
call2->wasPassedToObject();
call3->withName("unrelated");
addAllToList();
MockExpectedObjectDidntHappenFailure failure(this, "foo", *list);
STRCMP_EQUAL("Mock Failure: Expected call on object for function \"foo\" but it did not happen.\n"
"\tEXPECTED calls that DID NOT happen related to function: foo\n"
"\t\t(object address: 0x2)::foo -> no parameters\n"
"\tACTUAL calls that DID happen related to function: foo\n"
"\t\t(object address: 0x3)::foo -> no parameters", failure.getMessage().asCharString());
}
| null |
290 | cpp | blalor-cpputest | TestMockFailure.h | tests/CppUTestExt/TestMockFailure.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_TestMockFailure_h
#define D_TestMockFailure_h
#define CHECK_EXPECTED_MOCK_FAILURE(expectedFailure) CHECK_EXPECTED_MOCK_FAILURE_LOCATION(expectedFailure, __FILE__, __LINE__)
#define CHECK_NO_MOCK_FAILURE() CHECK_NO_MOCK_FAILURE_LOCATION(__FILE__, __LINE__)
class MockFailureReporterForTest : public MockFailureReporter
{
public:
SimpleString mockFailureString;
virtual void failTest(const MockFailure& failure)
{
mockFailureString = failure.getMessage();
}
static MockFailureReporterForTest* getReporter()
{
static MockFailureReporterForTest reporter;
return &reporter;
}
};
inline Utest* mockFailureTest()
{
return MockFailureReporterForTest::getReporter()->getTestToFail();
}
inline SimpleString mockFailureString()
{
return MockFailureReporterForTest::getReporter()->mockFailureString;
}
inline void CHECK_EXPECTED_MOCK_FAILURE_LOCATION(const MockFailure& expectedFailure, const char* file, int line)
{
SimpleString expectedFailureString = expectedFailure.getMessage();
SimpleString actualFailureString = mockFailureString();
MockFailureReporterForTest::getReporter()->mockFailureString = "";
if (expectedFailureString != actualFailureString)
{
SimpleString error = "MockFailures are different.\n";
error += "Expected MockFailure:\n\t";
error += expectedFailureString;
error += "\nActual MockFailure:\n\t";
error += actualFailureString;
FAIL_LOCATION(error.asCharString(), file, line);
}
}
inline void CHECK_NO_MOCK_FAILURE_LOCATION(const char* file, int line)
{
if (mockFailureString() != "") {
SimpleString error = "Unexpected mock failure:\n";
error += mockFailureString();
MockFailureReporterForTest::getReporter()->mockFailureString = "";
FAIL_LOCATION(error.asCharString(), file, line);
}
MockFailureReporterForTest::getReporter()->mockFailureString = "";
}
#endif
| null |
291 | cpp | blalor-cpputest | TestMockPlugin.cpp | tests/CppUTestExt/TestMockPlugin.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 "CppUTestExt/MockSupport.h"
#include "CppUTestExt/MockSupportPlugin.h"
#include "TestMockFailure.h"
TEST_GROUP(MockPlugin)
{
Utest *test;
StringBufferTestOutput *output;
TestResult *result;
MockExpectedFunctionsList *expectationsList;
MockExpectedFunctionCall *call;
MockSupportPlugin *plugin;
void setup()
{
mock().setMockFailureReporter(MockFailureReporterForTest::getReporter());
test = new Utest("group", "name", "file", 1);
output = new StringBufferTestOutput;
result = new TestResult(*output);
expectationsList = new MockExpectedFunctionsList;
call = new MockExpectedFunctionCall;
expectationsList->addExpectedCall(call);
plugin = new MockSupportPlugin;;
}
void teardown()
{
delete test;
delete output;
delete result;
delete expectationsList;
delete call;
delete plugin;
CHECK_NO_MOCK_FAILURE();
mock().setMockFailureReporter(NULL);
}
};
TEST(MockPlugin, checkExpectationsAndClearAtEnd)
{
call->withName("foobar");
MockExpectedCallsDidntHappenFailure expectedFailure(test, *expectationsList);
mock().expectOneCall("foobar");
plugin->postTestAction(*test, *result);
STRCMP_CONTAINS(expectedFailure.getMessage().asCharString(), output->getOutput().asCharString())
LONGS_EQUAL(0, mock().expectedCallsLeft());
// clear makes sure there are no memory leaks.
}
TEST(MockPlugin, checkExpectationsWorksAlsoWithHierachicalObjects)
{
call->withName("foobar").onObject((void*) 1);
MockExpectedObjectDidntHappenFailure expectedFailure(test, "foobar", *expectationsList);
mock("differentScope").expectOneCall("foobar").onObject((void*) 1);
mock("differentScope").actualCall("foobar");
plugin->postTestAction(*test, *result);
STRCMP_CONTAINS(expectedFailure.getMessage().asCharString(), output->getOutput().asCharString())
}
class DummyComparator : public MockNamedValueComparator
{
public:
bool isEqual(void* object1, void* object2)
{
return object1 == object2;
}
SimpleString valueToString(void*)
{
return "string";
}
};
TEST(MockPlugin, installComparatorRecordsTheComparatorButNotInstallsItYet)
{
DummyComparator comparator;
plugin->installComparator("myType", comparator);
mock().expectOneCall("foo").withParameterOfType("myType", "name", &comparator);
mock().actualCall("foo").withParameterOfType("myType", "name", &comparator);
MockNoWayToCompareCustomTypeFailure failure(test, "myType");
CHECK_EXPECTED_MOCK_FAILURE(failure);
}
TEST(MockPlugin, preTestActionWillEnableMultipleComparatorsToTheGlobalMockSupportSpace)
{
DummyComparator comparator;
DummyComparator comparator2;
plugin->installComparator("myType", comparator);
plugin->installComparator("myOtherType", comparator2);
plugin->preTestAction(*test, *result);
mock().expectOneCall("foo").withParameterOfType("myType", "name", &comparator);
mock().expectOneCall("foo").withParameterOfType("myOtherType", "name", &comparator);
mock().actualCall("foo").withParameterOfType("myType", "name", &comparator);
mock().actualCall("foo").withParameterOfType("myOtherType", "name", &comparator);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
LONGS_EQUAL(0, result->getFailureCount());
}
| null |
292 | cpp | blalor-cpputest | TestMockActualFunctionCall.cpp | tests/CppUTestExt/TestMockActualFunctionCall.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/MockExpectedFunctionCall.h"
#include "CppUTestExt/MockExpectedFunctionsList.h"
#include "CppUTestExt/MockFailure.h"
#include "TestMockFailure.h"
TEST_GROUP(MockActualFunctionCall)
{
MockExpectedFunctionsList* emptyList;
MockExpectedFunctionsList* list;
MockFailureReporter* reporter;
void setup()
{
emptyList = new MockExpectedFunctionsList;
list = new MockExpectedFunctionsList;
reporter = MockFailureReporterForTest::getReporter();
}
void teardown()
{
CHECK_NO_MOCK_FAILURE();
delete emptyList;
delete list;
}
};
TEST(MockActualFunctionCall, unExpectedCall)
{
MockActualFunctionCall actualCall(1, reporter, *emptyList);
actualCall.withName("unexpected");
MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "unexpected", *list);
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockActualFunctionCall, unExpectedParameterName)
{
MockExpectedFunctionCall call1;
call1.withName("func");
list->addExpectedCall(&call1);
MockActualFunctionCall actualCall(1, reporter, *list);
actualCall.withName("func").withParameter("integer", 1);
MockNamedValue parameter("integer");
parameter.setValue(1);
MockUnexpectedParameterFailure expectedFailure(mockFailureTest(), "func", parameter, *list);
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockActualFunctionCall, multipleSameFunctionsExpectingAndHappenGradually)
{
MockExpectedFunctionCall* call1 = new MockExpectedFunctionCall();
MockExpectedFunctionCall* call2 = new MockExpectedFunctionCall();
call1->withName("func");
call2->withName("func");
list->addExpectedCall(call1);
list->addExpectedCall(call2);
MockActualFunctionCall actualCall1(1, reporter, *list);
MockActualFunctionCall actualCall2(2, reporter, *list);
LONGS_EQUAL(2, list->amountOfUnfulfilledExpectations());
actualCall1.withName("func");
LONGS_EQUAL(1, list->amountOfUnfulfilledExpectations());
actualCall2.withName("func");
LONGS_EQUAL(0, list->amountOfUnfulfilledExpectations());
list->deleteAllExpectationsAndClearList();
}
| null |
293 | cpp | blalor-cpputest | TestMockExpectedFunctionCall.cpp | tests/CppUTestExt/TestMockExpectedFunctionCall.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"
#include "CppUTestExt/MockFailure.h"
#include "TestMockFailure.h"
class TypeForTestingExpectedFunctionCall
{
public:
TypeForTestingExpectedFunctionCall(int val) : value(val) {};
int value;
};
class TypeForTestingExpectedFunctionCallComparator : public MockNamedValueComparator
{
public:
TypeForTestingExpectedFunctionCallComparator() {}
virtual ~TypeForTestingExpectedFunctionCallComparator() {};
virtual bool isEqual(void* object1, void* object2)
{
return ((TypeForTestingExpectedFunctionCall*)object1)->value == ((TypeForTestingExpectedFunctionCall*)object2)->value;
}
virtual SimpleString valueToString(void* object)
{
return StringFrom(((TypeForTestingExpectedFunctionCall*)object)->value);
}
};
TEST_GROUP(MockNamedValueComparatorRepository)
{
void teardown()
{
CHECK_NO_MOCK_FAILURE();
}
};
TEST(MockNamedValueComparatorRepository, getComparatorForNonExistingName)
{
MockNamedValueComparatorRepository repository;
POINTERS_EQUAL(NULL, repository.getComparatorForType("typeName"));
}
TEST(MockNamedValueComparatorRepository, installComparator)
{
TypeForTestingExpectedFunctionCallComparator comparator;
MockNamedValueComparatorRepository repository;
repository.installComparator("typeName", comparator);
POINTERS_EQUAL(&comparator, repository.getComparatorForType("typeName"));
}
TEST(MockNamedValueComparatorRepository, installMultipleComparator)
{
TypeForTestingExpectedFunctionCallComparator comparator1, comparator2, comparator3;
MockNamedValueComparatorRepository repository;
repository.installComparator("type1", comparator1);
repository.installComparator("type2", comparator2);
repository.installComparator("type3", comparator3);
POINTERS_EQUAL(&comparator3, repository.getComparatorForType("type3"));
POINTERS_EQUAL(&comparator2, repository.getComparatorForType("type2"));
POINTERS_EQUAL(&comparator1, repository.getComparatorForType("type1"));
}
TEST_GROUP(MockExpectedFunctionCall)
{
MockExpectedFunctionCall* call;
void setup ()
{
call = new MockExpectedFunctionCall;
}
void teardown()
{
delete call;
CHECK_NO_MOCK_FAILURE();
}
};
TEST(MockExpectedFunctionCall, callWithoutParameterSetOrNotFound)
{
STRCMP_EQUAL("", call->getParameterType("nonexisting").asCharString());
LONGS_EQUAL(0, call->getParameter("nonexisting").getIntValue());
CHECK(!call->hasParameterWithName("nonexisting"));
}
TEST(MockExpectedFunctionCall, callWithIntegerParameter)
{
call->withParameter("integer", 1);
STRCMP_EQUAL("int", call->getParameterType("integer").asCharString());
LONGS_EQUAL(1, call->getParameter("integer").getIntValue());
CHECK(call->hasParameterWithName("integer"));
}
TEST(MockExpectedFunctionCall, callWithDoubleParameter)
{
call->withParameter("double", 1.2);
STRCMP_EQUAL("double", call->getParameterType("double").asCharString());
DOUBLES_EQUAL(1.2, call->getParameter("double").getDoubleValue(), 0.05);
}
TEST(MockExpectedFunctionCall, callWithStringParameter)
{
call->withParameter("string", "hello world");
STRCMP_EQUAL("char*", call->getParameterType("string").asCharString());
STRCMP_EQUAL("hello world", call->getParameter("string").getStringValue());
}
TEST(MockExpectedFunctionCall, callWithPointerParameter)
{
void* ptr = (void*) 0x123;
call->withParameter("pointer", ptr);
STRCMP_EQUAL("void*", call->getParameterType("pointer").asCharString());
POINTERS_EQUAL(ptr, call->getParameter("pointer").getPointerValue());
}
TEST(MockExpectedFunctionCall, callWithObjectParameter)
{
void* ptr = (void*) 0x123;
call->withParameterOfType("class", "object", ptr);
POINTERS_EQUAL(ptr, call->getParameter("object").getObjectPointer());
STRCMP_EQUAL("class", call->getParameterType("object").asCharString());
}
TEST(MockExpectedFunctionCall, callWithObjectParameterUnequalComparison)
{
TypeForTestingExpectedFunctionCall type(1), unequalType(2);
MockNamedValue parameter ("name");
parameter.setObjectPointer("type", &unequalType);
call->withParameterOfType("type", "name", &type);
CHECK (!call->hasParameter(parameter));
}
TEST(MockExpectedFunctionCall, callWithObjectParameterEqualComparisonButFailsWithoutRepository)
{
TypeForTestingExpectedFunctionCall type(1), equalType(1);
MockNamedValue parameter ("name");
parameter.setObjectPointer("type", &equalType);
call->withParameterOfType("type", "name", &type);
CHECK (!call->hasParameter(parameter));
}
TEST(MockExpectedFunctionCall, callWithObjectParameterEqualComparisonButFailsWithoutComparator)
{
MockNamedValueComparatorRepository repository;
call->setComparatorRepository(&repository);
TypeForTestingExpectedFunctionCall type(1), equalType(1);
MockNamedValue parameter ("name");
parameter.setObjectPointer("type", &equalType);
call->withParameterOfType("type", "name", &type);
CHECK (!call->hasParameter(parameter));
}
TEST(MockExpectedFunctionCall, callWithObjectParameterEqualComparison)
{
TypeForTestingExpectedFunctionCallComparator comparator;
MockNamedValueComparatorRepository repository;
repository.installComparator("type", comparator);
TypeForTestingExpectedFunctionCall type(1), equalType(1);
MockNamedValue parameter ("name");
parameter.setObjectPointer("type", &equalType);
call->setComparatorRepository(&repository);
call->withParameterOfType("type", "name", &type);
CHECK (call->hasParameter(parameter));
}
TEST(MockExpectedFunctionCall, getParameterValueOfObjectType)
{
TypeForTestingExpectedFunctionCallComparator comparator;
MockNamedValueComparatorRepository repository;
repository.installComparator("type", comparator);
TypeForTestingExpectedFunctionCall type(1);
call->setComparatorRepository(&repository);
call->withParameterOfType("type", "name", &type);
POINTERS_EQUAL(&type, call->getParameter("name").getObjectPointer());
STRCMP_EQUAL("1", call->getParameterValueString("name").asCharString());
}
TEST(MockExpectedFunctionCall, getParameterValueOfObjectTypeWithoutRepository)
{
TypeForTestingExpectedFunctionCall type(1);
call->withParameterOfType("type", "name", &type);
STRCMP_EQUAL("No comparator found for type: \"type\"", call->getParameterValueString("name").asCharString());
}
TEST(MockExpectedFunctionCall, getParameterValueOfObjectTypeWithoutComparator)
{
TypeForTestingExpectedFunctionCall type(1);
MockNamedValueComparatorRepository repository;
call->setComparatorRepository(&repository);
call->withParameterOfType("type", "name", &type);
STRCMP_EQUAL("No comparator found for type: \"type\"", call->getParameterValueString("name").asCharString());
}
TEST(MockExpectedFunctionCall, callWithTwoIntegerParameter)
{
call->withParameter("integer1", 1);
call->withParameter("integer2", 2);
STRCMP_EQUAL("int", call->getParameterType("integer1").asCharString());
STRCMP_EQUAL("int", call->getParameterType("integer2").asCharString());
LONGS_EQUAL(1, call->getParameter("integer1").getIntValue());
LONGS_EQUAL(2, call->getParameter("integer2").getIntValue());
}
TEST(MockExpectedFunctionCall, callWithThreeDifferentParameter)
{
call->withParameter("integer", 1);
call->withParameter("string", "hello world");
call->withParameter("double", 0.12);
STRCMP_EQUAL("int", call->getParameterType("integer").asCharString());
STRCMP_EQUAL("char*", call->getParameterType("string").asCharString());
STRCMP_EQUAL("double", call->getParameterType("double").asCharString());
LONGS_EQUAL(1, call->getParameter("integer").getIntValue());
STRCMP_EQUAL("hello world", call->getParameter("string").getStringValue());
DOUBLES_EQUAL(0.12, call->getParameter("double").getDoubleValue(), 0.05);
}
TEST(MockExpectedFunctionCall, withoutANameItsFulfilled)
{
CHECK(call->isFulfilled());
}
TEST(MockExpectedFunctionCall, withANameItsNotFulfilled)
{
call->withName("name");
CHECK(!call->isFulfilled());
}
TEST(MockExpectedFunctionCall, afterSettingCallFulfilledItsFulFilled)
{
call->withName("name");
call->callWasMade(1);
CHECK(call->isFulfilled());
}
TEST(MockExpectedFunctionCall, calledButNotWithParameterIsNotFulFilled)
{
call->withName("name").withParameter("para", 1);
call->callWasMade(1);
CHECK(!call->isFulfilled());
}
TEST(MockExpectedFunctionCall, calledAndParametersAreFulfilled)
{
call->withName("name").withParameter("para", 1);
call->callWasMade(1);
call->parameterWasPassed("para");
CHECK(call->isFulfilled());
}
TEST(MockExpectedFunctionCall, calledButNotAllParametersAreFulfilled)
{
call->withName("name").withParameter("para", 1).withParameter("two", 2);
call->callWasMade(1);
call->parameterWasPassed("para");
CHECK(! call->isFulfilled());
}
TEST(MockExpectedFunctionCall, toStringForNoParameters)
{
call->withName("name");
STRCMP_EQUAL("name -> no parameters", call->callToString().asCharString());
}
TEST(MockExpectedFunctionCall, toStringForIgnoredParameters)
{
call->withName("name");
call->ignoreOtherParameters();
STRCMP_EQUAL("name -> all parameters ignored", call->callToString().asCharString());
}
TEST(MockExpectedFunctionCall, toStringForMultipleParameters)
{
call->withName("name");
call->withParameter("string", "value");
call->withParameter("integer", 10);
STRCMP_EQUAL("name -> char* string: <value>, int integer: <10>", call->callToString().asCharString());
}
TEST(MockExpectedFunctionCall, toStringForParameterAndIgnored)
{
call->withName("name");
call->withParameter("string", "value");
call->ignoreOtherParameters();
STRCMP_EQUAL("name -> char* string: <value>, other parameters are ignored", call->callToString().asCharString());
}
TEST(MockExpectedFunctionCall, toStringForCallOrder)
{
call->withName("name");
call->withCallOrder(2);
STRCMP_EQUAL("name -> expected call order: <2> -> no parameters", call->callToString().asCharString());
}
TEST(MockExpectedFunctionCall, callOrderIsNotFulfilledWithWrongOrder)
{
call->withName("name");
call->withCallOrder(2);
call->callWasMade(1);
CHECK(call->isFulfilled());
CHECK(call->isOutOfOrder());
}
TEST(MockExpectedFunctionCall, callOrderIsFulfilled)
{
call->withName("name");
call->withCallOrder(1);
call->callWasMade(1);
CHECK(call->isFulfilled());
CHECK_FALSE(call->isOutOfOrder());
}
| null |
294 | cpp | blalor-cpputest | AllTests.h | tests/CppUTestExt/AllTests.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.
*/
//Include this in the test main to execute these tests
IMPORT_TEST_GROUP( TestOrderedTest);
| null |
295 | cpp | blalor-cpputest | TestCodeMemoryReportFormatter.cpp | tests/CppUTestExt/TestCodeMemoryReportFormatter.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 "CppUTestExt/MemoryReportAllocator.h"
#include "CppUTestExt/CodeMemoryReportFormatter.h"
#define TESTOUPUT_EQUAL(a) STRCMP_EQUAL_LOCATION(a, testOutput.getOutput().asCharString(), __FILE__, __LINE__);
#define TESTOUPUT_CONTAINS(a) STRCMP_CONTAINS_LOCATION(a, testOutput.getOutput().asCharString(), __FILE__, __LINE__);
TEST_GROUP(CodeMemoryReportFormatter)
{
MemoryLeakAllocator* cAllocator;
MemoryLeakAllocator* newAllocator;
MemoryLeakAllocator* newArrayAllocator;
char* memory01;
char* memory02;
StringBufferTestOutput testOutput;
TestResult* testResult;
CodeMemoryReportFormatter* formatter;
void setup()
{
cAllocator = StandardMallocAllocator::defaultAllocator();
newAllocator = StandardNewAllocator::defaultAllocator();
newArrayAllocator= StandardNewArrayAllocator::defaultAllocator();
memory01 = (char*) 0x01;
memory02 = (char*) 0x02;
formatter = new CodeMemoryReportFormatter(cAllocator);
testResult = new TestResult(testOutput);
}
void teardown()
{
delete testResult;
delete formatter;
}
};
TEST(CodeMemoryReportFormatter, mallocCreatesAnMallocCall)
{
formatter->report_alloc_memory(testResult, cAllocator, 10, memory01, "file", 9);
TESTOUPUT_EQUAL("\tvoid* file_9_1 = malloc(10);\n");
}
TEST(CodeMemoryReportFormatter, freeCreatesAnFreeCall)
{
formatter->report_alloc_memory(testResult, cAllocator, 10, memory01, "file", 9);
testOutput.flush();
formatter->report_free_memory(testResult, cAllocator, memory01, "boo", 6);
TESTOUPUT_EQUAL("\tfree(file_9_1); /* at boo:6 */\n");
}
TEST(CodeMemoryReportFormatter, twoMallocAndTwoFree)
{
formatter->report_alloc_memory(testResult, cAllocator, 10, memory01, "file", 2);
formatter->report_alloc_memory(testResult, cAllocator, 10, memory02, "boo", 4);
testOutput.flush();
formatter->report_free_memory(testResult, cAllocator, memory01, "foo", 6);
formatter->report_free_memory(testResult, cAllocator, memory02, "bar", 8);
TESTOUPUT_CONTAINS("\tfree(file_2_1); /* at foo:6 */\n");
TESTOUPUT_CONTAINS("\tfree(boo_4_1); /* at bar:8 */\n");
}
TEST(CodeMemoryReportFormatter, variableNamesShouldNotContainSlahses)
{
formatter->report_alloc_memory(testResult, cAllocator, 10, memory01, "dir/file", 2);
TESTOUPUT_CONTAINS("\tvoid* file_2");
}
TEST(CodeMemoryReportFormatter, variableNamesShouldNotContainDotButUseUnderscore)
{
formatter->report_alloc_memory(testResult, cAllocator, 10, memory01, "foo.cpp", 2);
TESTOUPUT_CONTAINS("foo_cpp");
}
TEST(CodeMemoryReportFormatter, newArrayAllocatorGeneratesNewArrayCode)
{
formatter->report_alloc_memory(testResult, newArrayAllocator, 10, memory01, "file", 8);
TESTOUPUT_CONTAINS("char* file_8_1 = new char[10]; /* using new [] */");
}
TEST(CodeMemoryReportFormatter, newArrayGeneratesNewCode)
{
formatter->report_alloc_memory(testResult, newAllocator, 6, memory01, "file", 4);
TESTOUPUT_CONTAINS("new char[6]; /* using new */");
}
TEST(CodeMemoryReportFormatter, NewAllocatorGeneratesDeleteCode)
{
formatter->report_alloc_memory(testResult, newAllocator, 10, memory01, "file", 8);
testOutput.flush();
formatter->report_free_memory(testResult, newAllocator, memory01, "boo", 4);
TESTOUPUT_CONTAINS("delete [] file_8_1; /* using delete at boo:4 */");
}
TEST(CodeMemoryReportFormatter, DeleteNullWorksFine)
{
formatter->report_free_memory(testResult, newAllocator, NULL, "boo", 4);
TESTOUPUT_CONTAINS("delete [] NULL; /* using delete at boo:4 */");
}
TEST(CodeMemoryReportFormatter, NewArrayAllocatorGeneratesDeleteArrayCode)
{
formatter->report_alloc_memory(testResult, newArrayAllocator, 10, memory01, "file", 8);
testOutput.flush();
formatter->report_free_memory(testResult, newArrayAllocator, memory01, "boo", 4);
TESTOUPUT_CONTAINS("delete [] file_8_1; /* using delete [] at boo:4 */");
}
TEST(CodeMemoryReportFormatter, allocationUsingMallocOnTheSameLineDoesntGenerateTheSameVariableTwice)
{
formatter->report_alloc_memory(testResult, cAllocator, 10, memory01, "file", 8);
testOutput.flush();
formatter->report_alloc_memory(testResult, cAllocator, 10, memory02, "file", 8);
CHECK(testOutput.getOutput().contains("2"));
}
TEST(CodeMemoryReportFormatter, allocationUsingNewcOnTheSameLineDoesntGenerateTheSameVariableTwice)
{
formatter->report_alloc_memory(testResult, newAllocator, 10, memory01, "file", 8);
testOutput.flush();
formatter->report_alloc_memory(testResult, newAllocator, 10, memory01, "file", 8);
CHECK(testOutput.getOutput().contains("2"));
}
TEST(CodeMemoryReportFormatter, allocationUsingNewcOnTheSameLineDoesntGenerateVariableTwiceExceptWhenInANewTest)
{
formatter->report_alloc_memory(testResult, newAllocator, 10, memory01, "file", 8);
formatter->report_test_start(testResult, *this);
testOutput.flush();
formatter->report_alloc_memory(testResult, newAllocator, 10, memory01, "file", 8);
CHECK(testOutput.getOutput().contains("char*"));
}
TEST(CodeMemoryReportFormatter, testStartGeneratesTESTcode)
{
Utest test("groupName", "testName", "fileName", 1);
formatter->report_test_start(testResult, test);
TESTOUPUT_EQUAL("*/\nTEST(groupName_memoryReport, testName)\n{ /* at fileName:1 */\n");
}
TEST(CodeMemoryReportFormatter, testEndGeneratesTESTcode)
{
Utest test("groupName", "testName", "fileName", 1);
formatter->report_test_end(testResult, test);
TESTOUPUT_EQUAL("}/*");
}
TEST(CodeMemoryReportFormatter, TestGroupGeneratesTestGroupCode)
{
Utest test("groupName", "testName", "fileName", 1);
formatter->report_testgroup_start(testResult, test);
TESTOUPUT_EQUAL("*/TEST_GROUP(groupName_memoryReport)\n{\n};\n/*");
}
// TODO: do!
/* Dealloc without alloc */
/* Remove the ugly comments by controlling the output! */
/* Write tests for the variable name lengths */
| null |
296 | cpp | blalor-cpputest | TestMockSupport.cpp | tests/CppUTestExt/TestMockSupport.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/MockExpectedFunctionCall.h"
#include "CppUTestExt/MockFailure.h"
#include "TestMockFailure.h"
TEST_GROUP(MockSupportTest)
{
MockExpectedFunctionsList *expectationsList;
void setup()
{
mock().setMockFailureReporter(MockFailureReporterForTest::getReporter());
expectationsList = new MockExpectedFunctionsList;
}
void teardown()
{
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
expectationsList->deleteAllExpectationsAndClearList();
delete expectationsList;
mock().setMockFailureReporter(NULL);
}
MockExpectedFunctionCall* addFunctionToExpectationsList(const SimpleString& name)
{
MockExpectedFunctionCall* newCall = new MockExpectedFunctionCall;
newCall->withName(name);
expectationsList->addExpectedCall(newCall);
return newCall;
}
MockExpectedFunctionCall* addFunctionToExpectationsList(const SimpleString& name, int order)
{
MockExpectedFunctionCall* newCall = new MockExpectedFunctionCall;
newCall->withName(name);
newCall->withCallOrder(order);
expectationsList->addExpectedCall(newCall);
return newCall;
}
};
TEST(MockSupportTest, clear)
{
mock().expectOneCall("func");
mock().clear();
CHECK(! mock().expectedCallsLeft());
}
TEST(MockSupportTest, checkExpectationsDoesntFail)
{
mock().checkExpectations();
}
TEST(MockSupportTest, checkExpectationsClearsTheExpectations)
{
addFunctionToExpectationsList("foobar");
MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), *expectationsList);
mock().expectOneCall("foobar");
mock().checkExpectations();
CHECK(! mock().expectedCallsLeft());
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, exceptACallThatHappens)
{
mock().expectOneCall("func");
mock().actualCall("func");
CHECK(! mock().expectedCallsLeft());
}
TEST(MockSupportTest, exceptACallInceasesExpectedCallsLeft)
{
mock().expectOneCall("func");
CHECK(mock().expectedCallsLeft());
mock().clear();
}
TEST(MockSupportTest, unexpectedCallHappened)
{
MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "func", *expectationsList);
mock().actualCall("func");
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, ignoreOtherCallsExceptForTheExpectedOne)
{
mock().expectOneCall("foo");
mock().ignoreOtherCalls();
mock().actualCall("bar").withParameter("foo", 1);;
CHECK_NO_MOCK_FAILURE();
mock().clear();
}
TEST(MockSupportTest, ignoreOtherCallsDoesntIgnoreMultipleCallsOfTheSameFunction)
{
mock().expectOneCall("foo");
mock().ignoreOtherCalls();
mock().actualCall("bar");
mock().actualCall("foo");
mock().actualCall("foo");
addFunctionToExpectationsList("foo")->callWasMade(1);
MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "foo", *expectationsList);
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, ignoreOtherStillFailsIfExpectedOneDidntHappen)
{
mock().expectOneCall("foo");
mock().ignoreOtherCalls();
mock().checkExpectations();
addFunctionToExpectationsList("foo");
MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), *expectationsList);
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, expectMultipleCallsThatHappen)
{
mock().expectOneCall("foo");
mock().expectOneCall("foo");
mock().actualCall("foo");
mock().actualCall("foo");
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, strictOrderObserved)
{
mock().strictOrder();
mock().expectOneCall("foo1");
mock().expectOneCall("foo2");
mock().actualCall("foo1");
mock().actualCall("foo2");
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, someStrictOrderObserved)
{
mock().expectOneCall("foo3").withCallOrder(3);
mock().expectOneCall("foo1");
mock().expectOneCall("foo2");
mock().actualCall("foo2");
mock().actualCall("foo1");
mock().actualCall("foo3");
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, strictOrderViolated)
{
mock().strictOrder();
addFunctionToExpectationsList("foo1", 1)->callWasMade(1);
addFunctionToExpectationsList("foo1", 2)->callWasMade(3);
addFunctionToExpectationsList("foo2", 3)->callWasMade(2);
MockCallOrderFailure expectedFailure(mockFailureTest(), *expectationsList);
mock().expectOneCall("foo1");
mock().expectOneCall("foo1");
mock().expectOneCall("foo2");
mock().actualCall("foo1");
mock().actualCall("foo2");
mock().actualCall("foo1");
mock().checkExpectations();
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, strictOrderNotViolatedWithTwoMocks)
{
mock("mock1").strictOrder();
mock("mock2").strictOrder();
mock("mock1").expectOneCall("foo1");
mock("mock2").expectOneCall("foo2");
mock("mock1").actualCall("foo1");
mock("mock2").actualCall("foo2");
mock("mock1").checkExpectations();
mock("mock2").checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
IGNORE_TEST(MockSupportTest, strictOrderViolatedWithTwoMocks)
{
//this test and scenario needs a decent failure message.
mock("mock1").strictOrder();
mock("mock2").strictOrder();
mock("mock1").expectOneCall("foo1");
mock("mock2").expectOneCall("foo2");
mock("mock2").actualCall("foo2");
mock("mock1").actualCall("foo1");
mock("mock1").checkExpectations();
mock("mock2").checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, usingNCalls)
{
mock().strictOrder();
mock().expectOneCall("foo1");
mock().expectNCalls(2, "foo2");
mock().expectOneCall("foo1");
mock().actualCall("foo1");
mock().actualCall("foo2");
mock().actualCall("foo2");
mock().actualCall("foo1");
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, expectOneCallHoweverMultipleHappened)
{
addFunctionToExpectationsList("foo")->callWasMade(1);
addFunctionToExpectationsList("foo")->callWasMade(2);
MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "foo", *expectationsList);
mock().expectOneCall("foo");
mock().expectOneCall("foo");
mock().actualCall("foo");
mock().actualCall("foo");
mock().actualCall("foo");
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, expectOneIntegerParameterAndValue)
{
mock().expectOneCall("foo").withParameter("parameter", 10);
mock().actualCall("foo").withParameter("parameter", 10);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, expectOneDoubleParameterAndValue)
{
mock().expectOneCall("foo").withParameter("parameter", 1.0);
mock().actualCall("foo").withParameter("parameter", 1.0);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, expectOneStringParameterAndValue)
{
mock().expectOneCall("foo").withParameter("parameter", "string");
mock().actualCall("foo").withParameter("parameter", "string");
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, expectOnePointerParameterAndValue)
{
mock().expectOneCall("foo").withParameter("parameter", (void*) 0x01);
mock().actualCall("foo").withParameter("parameter", (void*) 0x01);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, expectOneStringParameterAndValueFails)
{
MockNamedValue parameter("parameter");
parameter.setValue("different");
addFunctionToExpectationsList("foo")->withParameter("parameter", "string");
MockUnexpectedParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, *expectationsList);
mock().expectOneCall("foo").withParameter("parameter", "string");
mock().actualCall("foo").withParameter("parameter", "different");
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, expectOneIntegerParameterAndFailsDueToParameterName)
{
MockNamedValue parameter("different");
parameter.setValue(10);
addFunctionToExpectationsList("foo")->withParameter("parameter", 10);
MockUnexpectedParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, *expectationsList);
mock().expectOneCall("foo").withParameter("parameter", 10);
mock().actualCall("foo").withParameter("different", 10);
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, expectOneIntegerParameterAndFailsDueToValue)
{
MockNamedValue parameter("parameter");
parameter.setValue(8);
addFunctionToExpectationsList("foo")->withParameter("parameter", 10);
MockUnexpectedParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, *expectationsList);
mock().expectOneCall("foo").withParameter("parameter", 10);
mock().actualCall("foo").withParameter("parameter", 8);
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, expectOneIntegerParameterAndFailsDueToTypes)
{
MockNamedValue parameter("parameter");
parameter.setValue("heh");
addFunctionToExpectationsList("foo")->withParameter("parameter", 10);
MockUnexpectedParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, *expectationsList);
mock().expectOneCall("foo").withParameter("parameter", 10);
mock().actualCall("foo").withParameter("parameter", "heh");
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, expectMultipleCallsWithDifferentParametersThatHappenOutOfOrder)
{
mock().expectOneCall("foo").withParameter("p1", 1);
mock().expectOneCall("foo").withParameter("p1", 2);
mock().actualCall("foo").withParameter("p1", 2);
mock().actualCall("foo").withParameter("p1", 1);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, expectMultipleCallsWithMultipleDifferentParametersThatHappenOutOfOrder)
{
mock().expectOneCall("foo").withParameter("p1", 1).withParameter("p2", 2);
mock().expectOneCall("foo").withParameter("p1", 1).withParameter("p2", 20);
mock().actualCall("foo").withParameter("p1", 1).withParameter("p2", 20);
mock().actualCall("foo").withParameter("p1", 1).withParameter("p2", 2);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, twiceCalledWithSameParameters)
{
mock().expectOneCall("foo").withParameter("p1", 1).withParameter("p2", 2);
mock().expectOneCall("foo").withParameter("p1", 1).withParameter("p2", 2);
mock().actualCall("foo").withParameter("p1", 1).withParameter("p2", 2);
mock().actualCall("foo").withParameter("p1", 1).withParameter("p2", 2);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, calledWithoutParameters)
{
addFunctionToExpectationsList("foo")->withParameter("p1", 1);
MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", *expectationsList);
mock().expectOneCall("foo").withParameter("p1", 1);
mock().actualCall("foo");
mock().checkExpectations();
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, ignoreOtherParameters)
{
mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters();
mock().actualCall("foo").withParameter("p1", 1).withParameter("p2", 2);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, ignoreOtherParametersButStillPassAll)
{
mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters();
mock().actualCall("foo").withParameter("p1", 1);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, ignoreOtherParametersButExpectedParameterDidntHappen)
{
addFunctionToExpectationsList("foo")->withParameter("p1", 1).ignoreOtherParameters();
MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", *expectationsList);
mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters();
mock().actualCall("foo").withParameter("p2", 2).withParameter("p3", 3).withParameter("p4", 4);
mock().checkExpectations();
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, ignoreOtherParametersMultipleCalls)
{
mock().expectOneCall("foo").ignoreOtherParameters();
mock().expectOneCall("foo").ignoreOtherParameters();
mock().actualCall("foo").withParameter("p2", 2).withParameter("p3", 3).withParameter("p4", 4);
LONGS_EQUAL(1, mock().expectedCallsLeft());
mock().actualCall("foo").withParameter("p2", 2).withParameter("p3", 3).withParameter("p4", 4);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, ignoreOtherParametersMultipleCallsButOneDidntHappen)
{
MockExpectedFunctionCall* call = addFunctionToExpectationsList("boo");
call->ignoreOtherParameters();
call->callWasMade(1);
call->parametersWereIgnored();
call->ignoreOtherParameters();
addFunctionToExpectationsList("boo")->ignoreOtherParameters();
mock().expectOneCall("boo").ignoreOtherParameters();
mock().expectOneCall("boo").ignoreOtherParameters();
mock().actualCall("boo");
mock().checkExpectations();
MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), *expectationsList);
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, newCallStartsWhileNotAllParametersWerePassed)
{
addFunctionToExpectationsList("foo")->withParameter("p1", 1);
MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", *expectationsList);
mock().expectOneCall("foo").withParameter("p1", 1);
mock().actualCall("foo");
mock().actualCall("foo").withParameter("p1", 1);;
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, threeExpectedAndActual)
{
mock().expectOneCall("function1");
mock().expectOneCall("function2");
mock().expectOneCall("function3");
mock().actualCall("function1");
mock().actualCall("function2");
mock().actualCall("function3");
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
class MyTypeForTesting
{
public:
MyTypeForTesting(int val) : value(val){};
int value;
};
class MyTypeForTestingComparator : public MockNamedValueComparator
{
public:
virtual bool isEqual(void* object1, void* object2)
{
return ((MyTypeForTesting*)object1)->value == ((MyTypeForTesting*)object2)->value;
}
virtual SimpleString valueToString(void* object)
{
return StringFrom(((MyTypeForTesting*)object)->value);
}
};
TEST(MockSupportTest, customObjectParameterFailsWhenNotHavingAComparisonRepository)
{
MyTypeForTesting object(1);
mock().expectOneCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock().actualCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
MockNoWayToCompareCustomTypeFailure expectedFailure(mockFailureTest(), "MyTypeForTesting");
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, customObjectParameterSucceeds)
{
MyTypeForTesting object(1);
MyTypeForTestingComparator comparator;
mock().installComparator("MyTypeForTesting", comparator);
mock().expectOneCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock().actualCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
mock().removeAllComparators();
}
bool myTypeIsEqual(void* object1, void* object2)
{
return ((MyTypeForTesting*)object1)->value == ((MyTypeForTesting*)object2)->value;
}
SimpleString myTypeValueToString(void* object)
{
return StringFrom(((MyTypeForTesting*)object)->value);
}
TEST(MockSupportTest, customObjectWithFunctionComparator)
{
MyTypeForTesting object(1);
MockFunctionComparator comparator(myTypeIsEqual, myTypeValueToString);
mock().installComparator("MyTypeForTesting", comparator);
mock().expectOneCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock().actualCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
mock().removeAllComparators();
}
TEST(MockSupportTest, disableEnable)
{
mock().disable();
mock().expectOneCall("function");
mock().actualCall("differenFunction");
CHECK(! mock().expectedCallsLeft());
mock().enable();
mock().expectOneCall("function");
CHECK(mock().expectedCallsLeft());
mock().actualCall("function");
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, setDataForIntegerValues)
{
mock().setData("data", 10);
LONGS_EQUAL(10, mock().getData("data").getIntValue());
}
TEST(MockSupportTest, hasDataBeenSet)
{
CHECK(!mock().hasData("data"));
mock().setData("data", 10);
CHECK(mock().hasData("data"));
}
TEST(MockSupportTest, dataCanBeChanged)
{
mock().setData("data", 10);
mock().setData("data", 15);
LONGS_EQUAL(15, mock().getData("data").getIntValue());
}
TEST(MockSupportTest, uninitializedData)
{
LONGS_EQUAL(0, mock().getData("nonexisting").getIntValue());
STRCMP_EQUAL("int", mock().getData("nonexisting").getType().asCharString());
}
TEST(MockSupportTest, setMultipleData)
{
mock().setData("data", 1);
mock().setData("data2", 10);
LONGS_EQUAL(1, mock().getData("data").getIntValue());
LONGS_EQUAL(10, mock().getData("data2").getIntValue());
}
TEST(MockSupportTest, setDataString)
{
mock().setData("data", "string");
STRCMP_EQUAL("string", mock().getData("data").getStringValue());
}
TEST(MockSupportTest, setDataDouble)
{
mock().setData("data", 1.0);
DOUBLES_EQUAL(1.0, mock().getData("data").getDoubleValue(), 0.05);
}
TEST(MockSupportTest, setDataPointer)
{
void * ptr = (void*) 0x001;
mock().setData("data", ptr);
POINTERS_EQUAL(ptr, mock().getData("data").getPointerValue());
}
TEST(MockSupportTest, setDataObject)
{
void * ptr = (void*) 0x001;
mock().setDataObject("data", "type", ptr);
POINTERS_EQUAL(ptr, mock().getData("data").getObjectPointer());
STRCMP_EQUAL("type", mock().getData("data").getType().asCharString());
}
TEST(MockSupportTest, getMockSupportScope)
{
MockSupport* mock1 = mock().getMockSupportScope("name");
MockSupport* mock2 = mock().getMockSupportScope("differentName");
CHECK(!mock().hasData("name"));
CHECK(mock1 != mock2);
POINTERS_EQUAL(mock1, mock().getMockSupportScope("name"));
CHECK(mock1 != &mock());
}
TEST(MockSupportTest, usingTwoMockSupportsByName)
{
mock("first").expectOneCall("boo");
LONGS_EQUAL(0, mock("other").expectedCallsLeft());
LONGS_EQUAL(1, mock("first").expectedCallsLeft());
mock("first").clear();
}
TEST(MockSupportTest, EnableDisableWorkHierarchically)
{
mock("first");
mock().disable();
mock("first").expectOneCall("boo");
LONGS_EQUAL(0, mock("first").expectedCallsLeft());
mock().enable();
mock("first").expectOneCall("boo");
LONGS_EQUAL(1, mock("first").expectedCallsLeft());
mock("first").clear();
}
TEST(MockSupportTest, EnableDisableWorkHierarchicallyWhenSupportIsDynamicallyCreated)
{
mock().disable();
mock("first").expectOneCall("boo");
LONGS_EQUAL(0, mock("first").expectedCallsLeft());
mock().enable();
mock("second").expectOneCall("boo");
LONGS_EQUAL(1, mock("second").expectedCallsLeft());
mock().clear();
}
TEST(MockSupportTest, ExpectedCallsLeftWorksHierarchically)
{
mock("first").expectOneCall("foobar");
LONGS_EQUAL(1, mock().expectedCallsLeft());
mock().clear();
}
TEST(MockSupportTest, checkExpectationsWorksHierarchically)
{
mock("first").expectOneCall("foobar");
mock("second").expectOneCall("helloworld");
addFunctionToExpectationsList("foobar");
addFunctionToExpectationsList("helloworld");
MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), *expectationsList);
mock().checkExpectations();
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, ignoreOtherCallsWorksHierarchically)
{
mock("first");
mock().ignoreOtherCalls();
mock("first").actualCall("boo");
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, ignoreOtherCallsWorksHierarchicallyWhenDynamicallyCreated)
{
mock().ignoreOtherCalls();
mock("first").actualCall("boo");
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, checkExpectationsWorksHierarchicallyForLastCallNotFinished)
{
mock("first").expectOneCall("foobar").withParameter("boo", 1);
mock("first").actualCall("foobar");
addFunctionToExpectationsList("foobar")->withParameter("boo", 1);
MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foobar", *expectationsList);
mock().checkExpectations();
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, reporterIsInheritedInHierarchicalMocks)
{
mock("differentScope").actualCall("foobar");
MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "foobar", *expectationsList);
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, installComparatorWorksHierarchicalOnBothExistingAndDynamicallyCreatedMockSupports)
{
MyTypeForTesting object(1);
MyTypeForTestingComparator comparator;
mock("existing");
mock().installComparator("MyTypeForTesting", comparator);
mock("existing").expectOneCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock("existing").actualCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock("dynamic").expectOneCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock("dynamic").actualCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
mock().removeAllComparators();
}
TEST(MockSupportTest, installComparatorsWorksHierarchical)
{
MyTypeForTesting object(1);
MyTypeForTestingComparator comparator;
MockNamedValueComparatorRepository repos;
repos.installComparator("MyTypeForTesting", comparator);
mock("existing");
mock().installComparators(repos);
mock("existing").expectOneCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock("existing").actualCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
mock().removeAllComparators();
}
TEST(MockSupportTest, removeComparatorsWorksHierachically)
{
MyTypeForTesting object(1);
MyTypeForTestingComparator comparator;
mock("scope").installComparator("MyTypeForTesting", comparator);
mock().removeAllComparators();
mock("scope").expectOneCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
mock("scope").actualCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object);
MockNoWayToCompareCustomTypeFailure expectedFailure(mockFailureTest(), "MyTypeForTesting");
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, hasReturnValue)
{
CHECK(!mock().hasReturnValue());
mock().expectOneCall("foo");
CHECK(!mock().actualCall("foo").hasReturnValue());
CHECK(!mock().hasReturnValue());
mock().expectOneCall("foo2").andReturnValue(1);
CHECK(mock().actualCall("foo2").hasReturnValue());
CHECK(mock().hasReturnValue());
}
TEST(MockSupportTest, IntegerReturnValue)
{
mock().expectOneCall("foo").andReturnValue(1);
LONGS_EQUAL(1, mock().actualCall("foo").returnValue().getIntValue());
LONGS_EQUAL(1, mock().returnValue().getIntValue());
LONGS_EQUAL(1, mock().intReturnValue());
}
TEST(MockSupportTest, IntegerReturnValueSetsDifferentValues)
{
mock().expectOneCall("foo").andReturnValue(1);
mock().expectOneCall("foo").andReturnValue(2);
LONGS_EQUAL(1, mock().actualCall("foo").returnValue().getIntValue());
LONGS_EQUAL(1, mock().returnValue().getIntValue());
LONGS_EQUAL(2, mock().actualCall("foo").returnValue().getIntValue());
LONGS_EQUAL(2, mock().returnValue().getIntValue());
}
TEST(MockSupportTest, IntegerReturnValueSetsDifferentValuesWhileParametersAreIgnored)
{
mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(1);
mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(2);
LONGS_EQUAL(1, mock().actualCall("foo").withParameter("p1", 1).returnValue().getIntValue());
LONGS_EQUAL(1, mock().returnValue().getIntValue());
LONGS_EQUAL(2, mock().actualCall("foo").withParameter("p1", 1).returnValue().getIntValue());
LONGS_EQUAL(2, mock().returnValue().getIntValue());
}
TEST(MockSupportTest, MatchingReturnValueOnWhileSignature)
{
mock().expectOneCall("foo").withParameter("p1", 1).andReturnValue(1);
mock().expectOneCall("foo").withParameter("p1", 2).andReturnValue(2);
mock().expectOneCall("foo").withParameter("p1", 3).andReturnValue(3);
mock().expectOneCall("foo").ignoreOtherParameters().andReturnValue(4);
LONGS_EQUAL(3, mock().actualCall("foo").withParameter("p1", 3).returnValue().getIntValue());
LONGS_EQUAL(4, mock().actualCall("foo").withParameter("p1", 4).returnValue().getIntValue());
LONGS_EQUAL(1, mock().actualCall("foo").withParameter("p1", 1).returnValue().getIntValue());
LONGS_EQUAL(2, mock().actualCall("foo").withParameter("p1", 2).returnValue().getIntValue());
}
TEST(MockSupportTest, StringReturnValue)
{
mock().expectOneCall("foo").andReturnValue("hello world");
STRCMP_EQUAL("hello world", mock().actualCall("foo").returnValue().getStringValue());
STRCMP_EQUAL("hello world", mock().stringReturnValue());
}
TEST(MockSupportTest, DoubleReturnValue)
{
mock().expectOneCall("foo").andReturnValue(1.0);
DOUBLES_EQUAL(1.0, mock().actualCall("foo").returnValue().getDoubleValue(), 0.05);
DOUBLES_EQUAL(1.0, mock().doubleReturnValue(), 0.05);
}
TEST(MockSupportTest, PointerReturnValue)
{
void* ptr = (void*) 0x001;
mock().expectOneCall("foo").andReturnValue(ptr);
POINTERS_EQUAL(ptr, mock().actualCall("foo").returnValue().getPointerValue());
POINTERS_EQUAL(ptr, mock().pointerReturnValue());
}
TEST(MockSupportTest, OnObject)
{
void* objectPtr = (void*) 0x001;
mock().expectOneCall("boo").onObject(objectPtr);
mock().actualCall("boo").onObject(objectPtr);
}
TEST(MockSupportTest, OnObjectFails)
{
void* objectPtr = (void*) 0x001;
void* objectPtr2 = (void*) 0x002;
addFunctionToExpectationsList("boo")->onObject(objectPtr);
mock().expectOneCall("boo").onObject(objectPtr);
mock().actualCall("boo").onObject(objectPtr2);
MockUnexpectedObjectFailure expectedFailure(mockFailureTest(), "boo", objectPtr2, *expectationsList);
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, OnObjectExpectedButNotCalled)
{
void* objectPtr = (void*) 0x001;
addFunctionToExpectationsList("boo")->onObject(objectPtr);
addFunctionToExpectationsList("boo")->onObject(objectPtr);
mock().expectOneCall("boo").onObject(objectPtr);
mock().expectOneCall("boo").onObject(objectPtr);
mock().actualCall("boo");
mock().actualCall("boo");
MockExpectedObjectDidntHappenFailure expectedFailure(mockFailureTest(), "boo", *expectationsList);
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
mock().checkExpectations();
CHECK_EXPECTED_MOCK_FAILURE(expectedFailure);
}
TEST(MockSupportTest, expectMultipleCalls)
{
mock().expectNCalls(2, "boo");
mock().actualCall("boo");
mock().actualCall("boo");
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, expectMultipleCallsWithParameters)
{
mock().expectNCalls(2, "boo").withParameter("double", 1.0).withParameter("int", 1).withParameter("string", "string");
mock().actualCall("boo").withParameter("double", 1.0).withParameter("int", 1).withParameter("string", "string");
mock().actualCall("boo").withParameter("double", 1.0).withParameter("int", 1).withParameter("string", "string");
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, expectMultipleMultipleCallsWithParameters)
{
mock().expectNCalls(2, "boo").withParameter("double", 1.0).ignoreOtherParameters();
mock().expectNCalls(2, "boo").withParameter("double", 1.0).ignoreOtherParameters();
mock().actualCall("boo").withParameter("double", 1.0).withParameter("int", 1).withParameter("string", "string");
mock().actualCall("boo").withParameter("double", 1.0).withParameter("int", 1).withParameter("string", "string");
mock().actualCall("boo").withParameter("double", 1.0).withParameter("int", 1).withParameter("string", "string");
mock().actualCall("boo").withParameter("double", 1.0).withParameter("int", 1).withParameter("string", "string");
mock().checkExpectations();
CHECK_NO_MOCK_FAILURE();
}
TEST(MockSupportTest, whenCallingDisabledOrIgnoredActualCallsThenTheyDontReturnPreviousCallsValues)
{
mock().expectOneCall("boo").ignoreOtherParameters().andReturnValue(10);
mock().ignoreOtherCalls();
mock().actualCall("boo");
mock().actualCall("An Ignored Call");
CHECK(!mock().hasReturnValue());
}
TEST(MockSupportTest, tracing)
{
mock().tracing(true);
mock().actualCall("boo").withParameter("double", 1.0).withParameter("int", 1).withParameter("string", "string");
mock("scope").actualCall("foo").withParameter("double", 1.0).withParameter("int", 1).withParameter("string", "string");
mock().checkExpectations();
STRCMP_CONTAINS("boo", mock().getTraceOutput());
STRCMP_CONTAINS("foo", mock().getTraceOutput());
}
| null |
297 | cpp | blalor-cpputest | TestMemoryReporterPlugin.cpp | tests/CppUTestExt/TestMemoryReporterPlugin.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 "CppUTestExt/MemoryReporterPlugin.h"
#include "CppUTestExt/MemoryReportFormatter.h"
#include "CppUTestExt/MockSupport.h"
#include "CppUTestExt/MockNamedValue.h"
static MemoryLeakAllocator* previousNewAllocator;
class TemporaryDefaultNewAllocator
{
MemoryLeakAllocator* newAllocator;
public:
TemporaryDefaultNewAllocator(MemoryLeakAllocator* oldAllocator)
{
newAllocator = MemoryLeakAllocator::getCurrentNewAllocator();
MemoryLeakAllocator::setCurrentNewAllocator(oldAllocator);
}
~TemporaryDefaultNewAllocator()
{
MemoryLeakAllocator::setCurrentNewAllocator(newAllocator);
}
};
class MockMemoryReportFormatter : public MemoryReportFormatter
{
public:
virtual void report_testgroup_start(TestResult* result, Utest& test)
{
TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator);
mock("formatter").actualCall("report_testgroup_start").withParameter("result", result).withParameter("test", &test);
}
virtual void report_testgroup_end(TestResult* result, Utest& test)
{
TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator);
mock("formatter").actualCall("report_testgroup_end").withParameter("result", result).withParameter("test", &test);
}
virtual void report_test_start(TestResult* result, Utest& test)
{
TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator);
mock("formatter").actualCall("report_test_start").withParameter("result", result).withParameter("test", &test);
}
virtual void report_test_end(TestResult* result, Utest& test)
{
TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator);
mock("formatter").actualCall("report_test_end").withParameter("result", result).withParameter("test", &test);
}
virtual void report_alloc_memory(TestResult* result, MemoryLeakAllocator* allocator, size_t, char* , const char* , int )
{
TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator);
mock("formatter").actualCall("report_alloc_memory").withParameter("result", result).withParameterOfType("MemoryLeakAllocator", "allocator", allocator);
}
virtual void report_free_memory(TestResult* result, MemoryLeakAllocator* allocator, char* , const char* , int )
{
TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator);
mock("formatter").actualCall("report_free_memory").withParameter("result", result).withParameterOfType("MemoryLeakAllocator", "allocator", allocator);
}
};
static MockMemoryReportFormatter formatterForPluginTest;
class MemoryReporterPluginUnderTest : public MemoryReporterPlugin
{
public:
MemoryReportFormatter* createMemoryFormatter(const SimpleString& type)
{
mock("reporter").actualCall("createMemoryFormatter").onObject(this).withParameter("type", type.asCharString());
return new MockMemoryReportFormatter;
}
};
class MemoryLeakAllocatorComparator : public MockNamedValueComparator
{
public:
bool isEqual(void* object1, void* object2)
{
return ((MemoryLeakAllocator*)object1)->name() == ((MemoryLeakAllocator*)object2)->name();
}
SimpleString valueToString(void* object)
{
return ((MemoryLeakAllocator*)object)->name();
}
};
TEST_GROUP(MemoryReporterPlugin)
{
MemoryReporterPluginUnderTest* reporter;
StringBufferTestOutput output;
MemoryLeakAllocatorComparator memLeakAllocatorComparator;
TestResult* result;
Utest* test;
void setup()
{
previousNewAllocator = MemoryLeakAllocator::getCurrentNewAllocator();
result = new TestResult(output);
test = new Utest("groupname", "testname", "filename", 1);
reporter = new MemoryReporterPluginUnderTest;
mock("formatter").installComparator("MemoryLeakAllocator", memLeakAllocatorComparator);
mock("reporter").disable();
const char *cmd_line[] = {"-pmemoryreport=normal"};
reporter->parseArguments(1, cmd_line, 0);
mock("reporter").enable();
// mock.crashOnFailure();
}
void teardown()
{
delete reporter;
delete test;
delete result;
}
};
TEST(MemoryReporterPlugin, offReportsNothing)
{
MemoryReporterPluginUnderTest freshReporter;
freshReporter.preTestAction(*test, *result);
char* memory = new char;
delete memory;
freshReporter.postTestAction(*test, *result);
}
TEST(MemoryReporterPlugin, meaninglessArgumentsAreIgnored)
{
const char *cmd_line[] = {"-nothing", "-pnotmemoryreport=normal", "alsomeaningless", "-pmemoryreportnonsensebutnotus"};
CHECK(reporter->parseArguments(3, cmd_line, 1) == false);
}
TEST(MemoryReporterPlugin, commandLineParameterTurnsOnNormalLogging)
{
mock("reporter").expectOneCall("createMemoryFormatter").onObject(reporter).withParameter("type", "normal");
const char *cmd_line[] = {"-nothing", "-pmemoryreport=normal", "alsomeaningless" };
CHECK(reporter->parseArguments(3, cmd_line, 1));
}
TEST(MemoryReporterPlugin, preTestActionReportsTest)
{
mock("formatter").expectOneCall("report_testgroup_start").withParameter("result", result).withParameter("test", test);
mock("formatter").expectOneCall("report_test_start").withParameter("result", result).withParameter("test", test);
reporter->preTestAction(*test, *result);
}
TEST(MemoryReporterPlugin, postTestActionReportsTest)
{
mock("formatter").expectOneCall("report_test_end").withParameter("result", result).withParameter("test", test);;
mock("formatter").expectOneCall("report_testgroup_end").withParameter("result", result).withParameter("test", test);;
reporter->postTestAction(*test, *result);
}
TEST(MemoryReporterPlugin, newAllocationsAreReportedTest)
{
mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("MemoryLeakAllocator", "allocator", StandardNewAllocator::defaultAllocator());
mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("MemoryLeakAllocator", "allocator", StandardNewAllocator::defaultAllocator());
mock("formatter").ignoreOtherCalls();
reporter->preTestAction(*test, *result);
char *memory = MemoryLeakAllocator::getCurrentNewAllocator()->allocMemoryLeakNode(100);
MemoryLeakAllocator::getCurrentNewAllocator()->free_memory(memory, "unknown", 1);
}
TEST(MemoryReporterPlugin, whenUsingOnlyMallocAllocatorNoOtherOfTheAllocatorsAreUsed)
{
mock("formatter").expectOneCall("report_test_start").withParameter("result", result).withParameter("test", test);
mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("MemoryLeakAllocator", "allocator", StandardMallocAllocator::defaultAllocator());
mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("MemoryLeakAllocator", "allocator", StandardMallocAllocator::defaultAllocator());
mock("formatter").ignoreOtherCalls();
reporter->preTestAction(*test, *result);
char *memory = MemoryLeakAllocator::getCurrentMallocAllocator()->allocMemoryLeakNode(100);
MemoryLeakAllocator::getCurrentMallocAllocator()->free_memory(memory, "unknown", 1);
}
TEST(MemoryReporterPlugin, newArrayAllocationsAreReportedTest)
{
mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("MemoryLeakAllocator", "allocator", StandardNewArrayAllocator::defaultAllocator());
mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("MemoryLeakAllocator", "allocator", StandardNewArrayAllocator::defaultAllocator());
mock("formatter").ignoreOtherCalls();
reporter->preTestAction(*test, *result);
char *memory = MemoryLeakAllocator::getCurrentNewArrayAllocator()->allocMemoryLeakNode(100);
MemoryLeakAllocator::getCurrentNewArrayAllocator()->free_memory(memory, "unknown", 1);
}
TEST(MemoryReporterPlugin, mallocAllocationsAreReportedTest)
{
mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("MemoryLeakAllocator", "allocator", StandardMallocAllocator::defaultAllocator());
mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("MemoryLeakAllocator", "allocator", StandardMallocAllocator::defaultAllocator());
mock("formatter").ignoreOtherCalls();
reporter->preTestAction(*test, *result);
char *memory = MemoryLeakAllocator::getCurrentMallocAllocator()->allocMemoryLeakNode(100);
MemoryLeakAllocator::getCurrentMallocAllocator()->free_memory(memory, "unknown", 1);
}
TEST(MemoryReporterPlugin, startOfANewTestWillReportTheTestGroupStart)
{
mock("formatter").expectOneCall("report_testgroup_start").withParameter("result", result).withParameter("test", test);
mock("formatter").expectOneCall("report_test_start").withParameter("result", result).withParameter("test", test);
mock("formatter").expectOneCall("report_test_end").withParameter("result", result).withParameter("test", test);
mock("formatter").expectOneCall("report_test_start").withParameter("result", result).withParameter("test", test);
mock("formatter").expectOneCall("report_test_end").withParameter("result", result).withParameter("test", test);
mock("formatter").ignoreOtherCalls();
reporter->preTestAction(*test, *result);
reporter->postTestAction(*test, *result);
reporter->preTestAction(*test, *result);
reporter->postTestAction(*test, *result);
}
class UtestForMemoryReportingPlugingTest : public Utest
{
public:
UtestForMemoryReportingPlugingTest(const char* groupname, Utest* test) : Utest(groupname, "testname", "filename", 1, test)
{
}
};
TEST(MemoryReporterPlugin, endOfaTestGroupWillReportSo)
{
UtestForMemoryReportingPlugingTest fourthTest("differentGroupName", NULL);
UtestForMemoryReportingPlugingTest thirdTest("differentGroupName", &fourthTest);
UtestForMemoryReportingPlugingTest secondTest("groupname", &thirdTest);
UtestForMemoryReportingPlugingTest firstTest("groupname", &secondTest);
mock("formatter").expectOneCall("report_testgroup_end").withParameter("result", result).withParameter("test", &secondTest);
mock("formatter").ignoreOtherCalls();
reporter->preTestAction(firstTest, *result);
reporter->postTestAction(firstTest, *result);
reporter->preTestAction(secondTest, *result);
reporter->postTestAction(secondTest, *result);
reporter->preTestAction(thirdTest, *result);
reporter->postTestAction(thirdTest, *result);
}
TEST(MemoryReporterPlugin, preActionReplacesAllocators)
{
mock("formatter").ignoreOtherCalls();
MemoryLeakAllocator* allocator = MemoryLeakAllocator::getCurrentMallocAllocator();
reporter->preTestAction(*test, *result);
CHECK(allocator != MemoryLeakAllocator::getCurrentMallocAllocator());
}
TEST(MemoryReporterPlugin, postActionRestoresAllocators)
{
mock("formatter").ignoreOtherCalls();
MemoryLeakAllocator* allocator = MemoryLeakAllocator::getCurrentMallocAllocator();
reporter->preTestAction(*test, *result);
reporter->postTestAction(*test, *result);
CHECK(allocator == MemoryLeakAllocator::getCurrentMallocAllocator());
}
| null |
298 | cpp | blalor-cpputest | TestMockCheatSheet.cpp | tests/CppUTestExt/TestMockCheatSheet.cpp | null |
/* Additional include from CppUTestExt */
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
/* Stubbed out product code using linker, function pointer, or overriding */
int foo(const char* param_string, int param_int)
{
/* Tell CppUTest Mocking what we mock. Also return recorded value */
return mock().actualCall("Foo")
.withParameter("param_string", param_string)
.withParameter("param_int", param_int)
.returnValue().getIntValue();
}
void bar(double param_double, const char* param_string)
{
mock().actualCall("Bar")
.withParameter("param_double", param_double)
.withParameter("param_string", param_string);
}
/* Production code calls to the methods we stubbed */
void productionCodeFooCalls()
{
int return_value;
return_value = foo("value_string", 10);
return_value = foo("value_string", 10);
}
void productionCodeBarCalls()
{
bar(1.5, "more");
bar(1.5, "more");
}
/* Actual test */
TEST_GROUP(MockCheatSheet)
{
void teardown()
{
/* Check expectations. Alternatively use MockSupportPlugin */
mock().checkExpectations();
}
};
TEST(MockCheatSheet, foo)
{
/* Record 2 calls to Foo. Return different values on each call */
mock().expectOneCall("Foo")
.withParameter("param_string", "value_string")
.withParameter("param_int", 10)
.andReturnValue(30);
mock().expectOneCall("Foo")
.ignoreOtherParameters()
.andReturnValue(50);
/* Call production code */
productionCodeFooCalls();
}
TEST(MockCheatSheet, bar)
{
/* Expect 2 calls on Bar. Check only one parameter */
mock().expectNCalls(2, "Bar")
.withParameter("param_double", 1.5)
.ignoreOtherParameters();
/* And the production code call */
productionCodeBarCalls();
}
| null |
299 | cpp | blalor-cpputest | TestMockSupport_cCFile.h | tests/CppUTestExt/TestMockSupport_cCFile.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 __TestMockSupportc_CFile__h
#define __TestMockSupportc_CFile__h
extern void all_mock_support_c_calls();
#endif
| null |
300 | cpp | blalor-cpputest | TestOrderedTest.cpp | tests/CppUTestExt/TestOrderedTest.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/TestRegistry.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTestExt/OrderedTest.h"
TEST_GROUP(TestOrderedTest)
{
TestTestingFixture* fixture;
OrderedTest orderedTest;
OrderedTest orderedTest2;
OrderedTest orderedTest3;
ExecFunctionTest normalTest;
ExecFunctionTest normalTest2;
ExecFunctionTest normalTest3;
OrderedTest* orderedTestCache;
void setup()
{
orderedTestCache = OrderedTest::getOrderedTestHead();
OrderedTest::setOrderedTestHead(0);
fixture = new TestTestingFixture();
fixture->registry_->unDoLastAddTest();
}
void teardown()
{
delete fixture;
OrderedTest::setOrderedTestHead(orderedTestCache);
}
void InstallOrderedTest(OrderedTest* test, int level)
{
OrderedTestInstaller(test, "testgroup", "testname", __FILE__, __LINE__, level);
}
void InstallNormalTest(Utest* test)
{
TestInstaller(test, "testgroup", "testname", __FILE__, __LINE__);
}
Utest* firstTest()
{
return fixture->registry_->getFirstTest();
}
Utest* secondTest()
{
return fixture->registry_->getFirstTest()->getNext();
}
};
TEST(TestOrderedTest, TestInstallerSetsFields)
{
OrderedTestInstaller(&orderedTest, "testgroup", "testname", "this.cpp", 10, 5);
STRCMP_EQUAL("testgroup", orderedTest.getGroup().asCharString());
STRCMP_EQUAL("testname", orderedTest.getName().asCharString());
STRCMP_EQUAL("this.cpp", orderedTest.getFile().asCharString());
LONGS_EQUAL(10, orderedTest.getLineNumber());
LONGS_EQUAL(5, orderedTest.getLevel());
}
TEST(TestOrderedTest, InstallOneText)
{
InstallOrderedTest(&orderedTest, 5);
CHECK(firstTest() == &orderedTest);
}
TEST(TestOrderedTest, OrderedTestsAreLast)
{
InstallNormalTest(&normalTest);
InstallOrderedTest(&orderedTest, 5);
CHECK(firstTest() == &normalTest);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, TwoTestsAddedInReverseOrder)
{
InstallOrderedTest(&orderedTest, 5);
InstallOrderedTest(&orderedTest2, 3);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, TwoTestsAddedInOrder)
{
InstallOrderedTest(&orderedTest2, 3);
InstallOrderedTest(&orderedTest, 5);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, MultipleOrderedTests)
{
InstallNormalTest(&normalTest);
InstallOrderedTest(&orderedTest2, 3);
InstallNormalTest(&normalTest2);
InstallOrderedTest(&orderedTest, 5);
InstallNormalTest(&normalTest3);
InstallOrderedTest(&orderedTest3, 7);
Utest * firstOrderedTest = firstTest()->getNext()->getNext()->getNext();
CHECK(firstOrderedTest == &orderedTest2);
CHECK(firstOrderedTest->getNext() == &orderedTest);
CHECK(firstOrderedTest->getNext()->getNext() == &orderedTest3);
}
TEST(TestOrderedTest, MultipleOrderedTests2)
{
InstallOrderedTest(&orderedTest, 3);
InstallOrderedTest(&orderedTest2, 1);
InstallOrderedTest(&orderedTest3, 2);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest3);
CHECK(secondTest()->getNext() == &orderedTest);
}
TEST_GROUP_BASE(TestOrderedTestMacros, OrderedTest)
{
};
static int testNumber = 0;
TEST(TestOrderedTestMacros, NormalTest)
{
CHECK(testNumber == 0);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test2, 2)
{
CHECK(testNumber == 2);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test1, 1)
{
CHECK(testNumber == 1);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test4, 4)
{
CHECK(testNumber == 4);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test3, 3)
{
CHECK(testNumber == 3);
testNumber++;
}
| null |
Subsets and Splits