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
1
cpp
cpputest
CommandLineArgumentsTest.cpp
tests/CppUTest/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() CPPUTEST_DESTRUCTOR_OVERRIDE { } bool parseArguments(int /*ac*/, const char *const * /*av*/, int /*index*/) CPPUTEST_OVERRIDE { return true; } }; TEST_GROUP(CommandLineArguments) { CommandLineArguments* args; OptionsPlugin* plugin; void setup() CPPUTEST_OVERRIDE { plugin = new OptionsPlugin("options"); args = NULLPTR; } void teardown() CPPUTEST_OVERRIDE { delete args; delete plugin; } bool newArgumentParser(int argc, const char *const *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, veryVerbose) { const char* argv[] = { "tests.exe", "-vv" }; CHECK(newArgumentParser(2, argv)); CHECK(args->isVeryVerbose()); } TEST(CommandLineArguments, setColor) { const char* argv[] = { "tests.exe", "-c" }; CHECK(newArgumentParser(2, argv)); CHECK(args->isColor()); } 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, repeatSetDefaultsToTwoAndShuffleDisabled) { int argc = 2; const char* argv[] = { "tests.exe", "-r" }; CHECK(newArgumentParser(argc, argv)); LONGS_EQUAL(2, args->getRepeatCount()); } TEST(CommandLineArguments, reverseEnabled) { int argc = 2; const char* argv[] = { "tests.exe", "-b" }; CHECK(newArgumentParser(argc, argv)); CHECK_TRUE(args->isReversing()); } TEST(CommandLineArguments, shuffleDisabledByDefault) { int argc = 1; const char* argv[] = { "tests.exe" }; CHECK(newArgumentParser(argc, argv)); CHECK_FALSE(args->isShuffling()); } TEST(CommandLineArguments, shuffleEnabled) { int argc = 2; const char* argv[] = { "tests.exe", "-s" }; CHECK(newArgumentParser(argc, argv)); CHECK_TRUE(args->isShuffling()); } TEST(CommandLineArguments, shuffleWithSeedZeroIsOk) { int argc = 2; const char* argv[] = { "tests.exe", "-s0" }; CHECK_FALSE(newArgumentParser(argc, argv)); CHECK_EQUAL(0, args->getShuffleSeed()); } TEST(CommandLineArguments, shuffleEnabledSpecificSeedCase1) { int argc = 2; const char* argv[] = { "tests.exe", "-s999"}; CHECK(newArgumentParser(argc, argv)); CHECK_EQUAL(999, args->getShuffleSeed()); } TEST(CommandLineArguments, shuffleEnabledSpecificSeedCase2) { int argc = 2; const char* argv[] = { "tests.exe", "-s 888"}; CHECK(newArgumentParser(argc, argv)); CHECK_EQUAL(888, args->getShuffleSeed()); } TEST(CommandLineArguments, shuffleEnabledSpecificSeedCase3) { int argc = 3; const char* argv[] = { "tests.exe", "-s", "777"}; CHECK(newArgumentParser(argc, argv)); CHECK_EQUAL(777, args->getShuffleSeed()); } TEST(CommandLineArguments, shuffleBeforeDoesNotDisturbOtherSwitch) { int argc = 4; const char* argv[] = { "tests.exe", "-s", "-sg", "group" }; CHECK(newArgumentParser(argc, argv)); TestFilter groupFilter("group"); groupFilter.strictMatching(); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); CHECK_TRUE(args->isShuffling()); } TEST(CommandLineArguments, runningTestsInSeperateProcesses) { int argc = 2; const char* argv[] = { "tests.exe", "-p" }; CHECK(newArgumentParser(argc, argv)); CHECK(args->runTestsInSeperateProcess()); } TEST(CommandLineArguments, setGroupFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-g", "group" }; CHECK(newArgumentParser(argc, argv)); CHECK_EQUAL(TestFilter("group"), *args->getGroupFilters()); } TEST(CommandLineArguments, setCompleteGroupDotNameFilterInvalidArgument) { int argc = 3; const char* argv[] = { "tests.exe", "-t", "groupname" }; CHECK_FALSE(newArgumentParser(argc, argv)); } TEST(CommandLineArguments, setCompleteGroupDotNameFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-t", "group.name" }; CHECK(newArgumentParser(argc, argv)); CHECK_EQUAL(TestFilter("group"), *args->getGroupFilters()); CHECK_EQUAL(TestFilter("name"), *args->getNameFilters()); } TEST(CommandLineArguments, setCompleteStrictGroupDotNameFilterInvalidArgument) { int argc = 3; const char* argv[] = { "tests.exe", "-st", "groupname" }; CHECK_FALSE(newArgumentParser(argc, argv)); } TEST(CommandLineArguments, setCompleteStrictGroupDotNameFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-st", "group.name" }; CHECK(newArgumentParser(argc, argv)); TestFilter groupFilter("group"); groupFilter.strictMatching(); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); TestFilter nameFilter("name"); nameFilter.strictMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()); } TEST(CommandLineArguments, setCompleteExcludeGroupDotNameFilterInvalidArgument) { int argc = 3; const char* argv[] = { "tests.exe", "-xt", "groupname" }; CHECK_FALSE(newArgumentParser(argc, argv)); } TEST(CommandLineArguments, setCompleteExcludeGroupDotNameFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-xt", "group.name" }; CHECK(newArgumentParser(argc, argv)); TestFilter groupFilter("group"); groupFilter.invertMatching(); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); TestFilter nameFilter("name"); nameFilter.invertMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()); } TEST(CommandLineArguments, setCompleteExcludeStrictGroupDotNameFilterInvalidArgument) { int argc = 3; const char* argv[] = { "tests.exe", "-xst", "groupname" }; CHECK_FALSE(newArgumentParser(argc, argv)); } TEST(CommandLineArguments, setCompleteExcludeStrictGroupDotNameFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-xst", "group.name" }; CHECK(newArgumentParser(argc, argv)); TestFilter groupFilter("group"); groupFilter.strictMatching(); groupFilter.invertMatching(); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); TestFilter nameFilter("name"); nameFilter.strictMatching(); nameFilter.invertMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()); } TEST(CommandLineArguments, setGroupFilterSameParameter) { int argc = 2; const char* argv[] = { "tests.exe", "-ggroup" }; CHECK(newArgumentParser(argc, argv)); CHECK_EQUAL(TestFilter("group"), *args->getGroupFilters()); } TEST(CommandLineArguments, setStrictGroupFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-sg", "group" }; CHECK(newArgumentParser(argc, argv)); TestFilter groupFilter("group"); groupFilter.strictMatching(); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); } TEST(CommandLineArguments, setStrictGroupFilterSameParameter) { int argc = 2; const char* argv[] = { "tests.exe", "-sggroup" }; CHECK(newArgumentParser(argc, argv)); TestFilter groupFilter("group"); groupFilter.strictMatching(); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); } TEST(CommandLineArguments, setExcludeGroupFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-xg", "group" }; CHECK(newArgumentParser(argc, argv)); TestFilter groupFilter("group"); groupFilter.invertMatching(); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); } TEST(CommandLineArguments, setExcludeGroupFilterSameParameter) { int argc = 2; const char* argv[] = { "tests.exe", "-xggroup" }; CHECK(newArgumentParser(argc, argv)); TestFilter groupFilter("group"); groupFilter.invertMatching(); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); } TEST(CommandLineArguments, setExcludeStrictGroupFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-xsg", "group" }; CHECK(newArgumentParser(argc, argv)); TestFilter groupFilter("group"); groupFilter.invertMatching(); groupFilter.strictMatching(); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); } TEST(CommandLineArguments, setExcludeStrictGroupFilterSameParameter) { int argc = 2; const char* argv[] = { "tests.exe", "-xsggroup" }; CHECK(newArgumentParser(argc, argv)); TestFilter groupFilter("group"); groupFilter.invertMatching(); groupFilter.strictMatching(); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); } TEST(CommandLineArguments, setNameFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-n", "name" }; CHECK(newArgumentParser(argc, argv)); CHECK_EQUAL(TestFilter("name"), *args->getNameFilters()); } TEST(CommandLineArguments, setNameFilterSameParameter) { int argc = 2; const char* argv[] = { "tests.exe", "-nname" }; CHECK(newArgumentParser(argc, argv)); CHECK_EQUAL(TestFilter("name"), *args->getNameFilters()); } TEST(CommandLineArguments, setStrictNameFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-sn", "name" }; CHECK(newArgumentParser(argc, argv)); TestFilter nameFilter("name"); nameFilter.strictMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()); } TEST(CommandLineArguments, setStrictNameFilterSameParameter) { int argc = 2; const char* argv[] = { "tests.exe", "-snname" }; CHECK(newArgumentParser(argc, argv)); TestFilter nameFilter("name"); nameFilter.strictMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()); } TEST(CommandLineArguments, setExcludeNameFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-xn", "name" }; CHECK(newArgumentParser(argc, argv)); TestFilter nameFilter("name"); nameFilter.invertMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()); } TEST(CommandLineArguments, setExcludeNameFilterSameParameter) { int argc = 2; const char* argv[] = { "tests.exe", "-xnname" }; CHECK(newArgumentParser(argc, argv)); TestFilter nameFilter("name"); nameFilter.invertMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()); } TEST(CommandLineArguments, setExcludeStrictNameFilter) { int argc = 3; const char* argv[] = { "tests.exe", "-xsn", "name" }; CHECK(newArgumentParser(argc, argv)); TestFilter nameFilter("name"); nameFilter.invertMatching(); nameFilter.strictMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()); } TEST(CommandLineArguments, setExcludeStrictNameFilterSameParameter) { int argc = 2; const char* argv[] = { "tests.exe", "-xsnname" }; CHECK(newArgumentParser(argc, argv)); TestFilter nameFilter("name"); nameFilter.invertMatching(); nameFilter.strictMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()); } TEST(CommandLineArguments, setTestToRunUsingVerboseOutput) { int argc = 2; const char* argv[] = { "tests.exe", "TEST(testgroup, testname) - stuff" }; CHECK(newArgumentParser(argc, argv)); TestFilter nameFilter("testname"); TestFilter groupFilter("testgroup"); nameFilter.strictMatching(); groupFilter.strictMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); } TEST(CommandLineArguments, setTestToRunUsingVerboseOutputOfIgnoreTest) { int argc = 2; const char* argv[] = { "tests.exe", "IGNORE_TEST(testgroup, testname) - stuff" }; CHECK(newArgumentParser(argc, argv)); TestFilter nameFilter("testname"); TestFilter groupFilter("testgroup"); nameFilter.strictMatching(); groupFilter.strictMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()); CHECK_EQUAL(groupFilter, *args->getGroupFilters()); } TEST(CommandLineArguments, setNormalOutput) { int argc = 2; const char* argv[] = { "tests.exe", "-onormal" }; CHECK(newArgumentParser(argc, argv)); CHECK(args->isEclipseOutput()); } TEST(CommandLineArguments, setEclipseOutput) { 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, setTeamCityOutputDifferentParameter) { int argc = 3; const char* argv[] = { "tests.exe", "-o", "teamcity" }; CHECK(newArgumentParser(argc, argv)); CHECK(args->isTeamCityOutput()); } TEST(CommandLineArguments, setOutputToGarbage) { int argc = 3; const char* argv[] = { "tests.exe", "-o", "garbage" }; CHECK(!newArgumentParser(argc, argv)); } TEST(CommandLineArguments, setPrintGroups) { int argc = 2; const char* argv[] = { "tests.exe", "-lg" }; CHECK(newArgumentParser(argc, argv)); CHECK(args->isListingTestGroupNames()); } TEST(CommandLineArguments, setPrintGroupsAndNames) { int argc = 2; const char* argv[] = { "tests.exe", "-ln" }; CHECK(newArgumentParser(argc, argv)); CHECK(args->isListingTestGroupAndCaseNames()); } TEST(CommandLineArguments, weirdParamatersReturnsFalse) { int argc = 2; const char* argv[] = { "tests.exe", "-SomethingWeird" }; CHECK(!newArgumentParser(argc, argv)); } TEST(CommandLineArguments, printUsage) { STRCMP_EQUAL( "use -h for more extensive help\n" "usage [-h] [-v] [-vv] [-c] [-p] [-lg] [-ln] [-ll] [-ri] [-r[<#>]] [-f] [-e] [-ci]\n" " [-g|sg|xg|xsg <groupName>]... [-n|sn|xn|xsn <testName>]... [-t|st|xt|xst <groupName>.<testName>]...\n" " [-b] [-s [<seed>]] [\"[IGNORE_]TEST(<groupName>, <testName>)\"]...\n" " [-o{normal|eclipse|junit|teamcity}] [-k <packageName>]\n", args->usage()); } TEST(CommandLineArguments, helpPrintsTheHelp) { int argc = 2; const char* argv[] = { "tests.exe", "-h" }; CHECK(!newArgumentParser(argc, argv)); CHECK(args->needHelp()); } TEST(CommandLineArguments, pluginKnowsOption) { int argc = 2; 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()); CHECK(NULLPTR == args->getGroupFilters()); CHECK(NULLPTR == args->getNameFilters()); CHECK(args->isEclipseOutput()); CHECK(SimpleString("") == args->getPackageName()); CHECK(!args->isCrashingOnFail()); CHECK(args->isRethrowingExceptions()); } TEST(CommandLineArguments, checkContinuousIntegrationMode) { int argc = 2; const char* argv[] = { "tests.exe", "-ci" }; CHECK(newArgumentParser(argc, argv)); CHECK(!args->isVerbose()); LONGS_EQUAL(1, args->getRepeatCount()); CHECK(NULLPTR == args->getGroupFilters()); CHECK(NULLPTR == args->getNameFilters()); CHECK(args->isEclipseOutput()); CHECK(SimpleString("") == args->getPackageName()); CHECK(!args->isCrashingOnFail()); CHECK_FALSE(args->isRethrowingExceptions()); } TEST(CommandLineArguments, setPackageName) { int argc = 3; const char* argv[] = { "tests.exe", "-k", "package" }; CHECK(newArgumentParser(argc, argv)); CHECK_EQUAL(SimpleString("package"), args->getPackageName()); } TEST(CommandLineArguments, lotsOfGroupsAndTests) { int argc = 10; const char* argv[] = { "tests.exe", "-sggroup1", "-xntest1", "-sggroup2", "-sntest2", "-sntest3", "-sggroup3", "-sntest4", "-sggroup4", "-sntest5" }; CHECK(newArgumentParser(argc, argv)); TestFilter nameFilter("test1"); nameFilter.invertMatching(); TestFilter groupFilter("group1"); groupFilter.strictMatching(); CHECK_EQUAL(nameFilter, *args->getNameFilters()->getNext()->getNext()->getNext()->getNext()); CHECK_EQUAL(groupFilter, *args->getGroupFilters()->getNext()->getNext()->getNext()); } TEST(CommandLineArguments, lastParameterFieldMissing) { int argc = 2; const char* argv[] = { "tests.exe", "-k"}; CHECK(newArgumentParser(argc, argv)); CHECK_EQUAL(SimpleString(""), args->getPackageName()); } TEST(CommandLineArguments, setOptRun) { int argc = 2; const char* argv[] = { "tests.exe", "-ri"}; CHECK(newArgumentParser(argc, argv)); CHECK(args->isRunIgnored()); } TEST(CommandLineArguments, setOptCrashOnFail) { int argc = 2; const char* argv[] = { "tests.exe", "-f"}; CHECK(newArgumentParser(argc, argv)); CHECK(args->isCrashingOnFail()); } TEST(CommandLineArguments, setOptRethrowExceptions) { int argc = 2; const char* argv[] = { "tests.exe", "-e"}; CHECK(newArgumentParser(argc, argv)); CHECK_FALSE(args->isRethrowingExceptions()); }
null
2
cpp
cpputest
AllTests.cpp
tests/CppUTest/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/TestMemoryAllocator.h" #include "CppUTest/SimpleStringInternalCache.h" #define SHOW_MEMORY_REPORT 0 int main(int ac, char **av) { int returnValue = 0; GlobalSimpleStringCache stringCache; { /* These checks are here to make sure assertions outside test runs don't crash */ CHECK(true); LONGS_EQUAL(1, 1); #if SHOW_MEMORY_REPORT GlobalMemoryAccountant accountant; accountant.start(); #endif returnValue = CommandLineTestRunner::RunAllTests(ac, av); /* cover alternate method */ #if SHOW_MEMORY_REPORT accountant.stop(); printf("%s", accountant.report().asCharString()); #endif } return returnValue; }
null
3
cpp
cpputest
TestRegistryTest.cpp
tests/CppUTest/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" #include "CppUTest/PlatformSpecificFunctions.h" namespace { const int testLineNumber = 1; } class MockTest: public UtestShell { public: MockTest(const char* group = "Group") : UtestShell(group, "Name", "File", testLineNumber), hasRun_(false) { } virtual void runOneTest(TestPlugin*, TestResult&) CPPUTEST_OVERRIDE { 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() CPPUTEST_DESTRUCTOR_OVERRIDE { } void resetCount() { countTestsStarted = 0; countTestsEnded = 0; countCurrentTestStarted = 0; countCurrentTestEnded = 0; countCurrentGroupStarted = 0; countCurrentGroupEnded = 0; } virtual void testsStarted() CPPUTEST_OVERRIDE { countTestsStarted++; } virtual void testsEnded() CPPUTEST_OVERRIDE { countTestsEnded++; } virtual void currentTestStarted(UtestShell* /*test*/) CPPUTEST_OVERRIDE { countCurrentTestStarted++; } virtual void currentTestEnded(UtestShell* /*test*/) CPPUTEST_OVERRIDE { countCurrentTestEnded++; } virtual void currentGroupStarted(UtestShell* /*test*/) CPPUTEST_OVERRIDE { countCurrentGroupStarted++; } virtual void currentGroupEnded(UtestShell* /*test*/) CPPUTEST_OVERRIDE { countCurrentGroupEnded++; } }; TEST_GROUP(TestRegistry) { TestRegistry* myRegistry; StringBufferTestOutput* output; MockTest* test1; MockTest* test2; MockTest* test3; MockTest* test4; TestResult *result; MockTestResult *mockResult; void setup() CPPUTEST_OVERRIDE { output = new StringBufferTestOutput(); mockResult = new MockTestResult(*output); result = mockResult; test1 = new MockTest(); test2 = new MockTest(); test3 = new MockTest("group2"); test4 = new MockTest(); myRegistry = new TestRegistry(); myRegistry->setCurrentRegistry(myRegistry); } void teardown() CPPUTEST_OVERRIDE { myRegistry->setCurrentRegistry(NULLPTR); delete myRegistry; delete test1; delete test2; delete test3; delete test4; delete result; delete output; } void addAndRunAllTests() { myRegistry->addTest(test1); myRegistry->addTest(test2); myRegistry->addTest(test3); myRegistry->runAllTests(*result); } }; TEST(TestRegistry, registryMyRegistryAndReset) { CHECK(myRegistry->getCurrentRegistry() == myRegistry); } TEST(TestRegistry, emptyRegistryIsEmpty) { CHECK(myRegistry->countTests() == 0); } TEST(TestRegistry, addOneTestIsNotEmpty) { myRegistry->addTest(test1); CHECK(myRegistry->countTests() == 1); } TEST(TestRegistry, addOneTwoTests) { myRegistry->addTest(test1); myRegistry->addTest(test2); CHECK(myRegistry->countTests() == 2); } TEST(TestRegistry, runTwoTests) { myRegistry->addTest(test1); myRegistry->addTest(test2); CHECK(!test1->hasRun_); CHECK(!test2->hasRun_); myRegistry->runAllTests(*result); CHECK(test1->hasRun_); CHECK(test2->hasRun_); } TEST(TestRegistry, runTwoTestsCheckResultFunctionsCalled) { myRegistry->addTest(test1); myRegistry->addTest(test2); myRegistry->runAllTests(*result); LONGS_EQUAL(1, mockResult->countTestsStarted); LONGS_EQUAL(1, mockResult->countTestsEnded); LONGS_EQUAL(1, mockResult->countCurrentGroupStarted); LONGS_EQUAL(1, mockResult->countCurrentGroupEnded); LONGS_EQUAL(2, mockResult->countCurrentTestStarted); LONGS_EQUAL(2, mockResult->countCurrentTestEnded); } TEST(TestRegistry, runThreeTestsandTwoGroupsCheckResultFunctionsCalled) { addAndRunAllTests(); LONGS_EQUAL(2, mockResult->countCurrentGroupStarted); LONGS_EQUAL(2, mockResult->countCurrentGroupEnded); LONGS_EQUAL(3, mockResult->countCurrentTestStarted); LONGS_EQUAL(3, mockResult->countCurrentTestEnded); } TEST(TestRegistry, unDoTest) { myRegistry->addTest(test1); CHECK(myRegistry->countTests() == 1); myRegistry->unDoLastAddTest(); CHECK(myRegistry->countTests() == 0); } TEST(TestRegistry, unDoButNoTest) { CHECK(myRegistry->countTests() == 0); myRegistry->unDoLastAddTest(); CHECK(myRegistry->countTests() == 0); } TEST(TestRegistry, reallyUndoLastTest) { myRegistry->addTest(test1); myRegistry->addTest(test2); CHECK(myRegistry->countTests() == 2); myRegistry->unDoLastAddTest(); CHECK(myRegistry->countTests() == 1); myRegistry->runAllTests(*result); CHECK(test1->hasRun_); CHECK(!test2->hasRun_); } TEST(TestRegistry, findTestWithNameDoesntExist) { CHECK(myRegistry->findTestWithName("ThisTestDoesntExists") == NULLPTR); } TEST(TestRegistry, findTestWithName) { test1->setTestName("NameOfATestThatDoesExist"); test2->setTestName("SomeOtherTest"); myRegistry->addTest(test1); myRegistry->addTest(test2); CHECK(myRegistry->findTestWithName("NameOfATestThatDoesExist") != NULLPTR); } TEST(TestRegistry, findTestWithGroupDoesntExist) { CHECK(myRegistry->findTestWithGroup("ThisTestGroupDoesntExists") == NULLPTR); } TEST(TestRegistry, findTestWithGroup) { test1->setGroupName("GroupOfATestThatDoesExist"); test2->setGroupName("SomeOtherGroup"); myRegistry->addTest(test1); myRegistry->addTest(test2); CHECK(myRegistry->findTestWithGroup("GroupOfATestThatDoesExist") != NULLPTR); } TEST(TestRegistry, nameFilterWorks) { test1->setTestName("testname"); test2->setTestName("noname"); TestFilter nameFilter("testname"); myRegistry->setNameFilters(&nameFilter); addAndRunAllTests(); CHECK(test1->hasRun_); CHECK(!test2->hasRun_); } TEST(TestRegistry, groupFilterWorks) { test1->setGroupName("groupname"); test2->setGroupName("noname"); TestFilter groupFilter("groupname"); myRegistry->setGroupFilters(&groupFilter); addAndRunAllTests(); CHECK(test1->hasRun_); CHECK(!test2->hasRun_); } TEST(TestRegistry, runTestInSeperateProcess) { myRegistry->setRunTestsInSeperateProcess(); myRegistry->addTest(test1); myRegistry->runAllTests(*result); CHECK(test1->isRunInSeperateProcess()); } TEST(TestRegistry, CurrentRepetitionIsCorrectNone) { CHECK(0 == myRegistry->getCurrentRepetition()); myRegistry->runAllTests(*result); LONGS_EQUAL(1, myRegistry->getCurrentRepetition()); } TEST(TestRegistry, CurrentRepetitionIsCorrectTwo) { CHECK(0 == myRegistry->getCurrentRepetition()); myRegistry->runAllTests(*result); myRegistry->runAllTests(*result); LONGS_EQUAL(2, myRegistry->getCurrentRepetition()); } class MyTestPluginDummy: public TestPlugin { public: MyTestPluginDummy(const SimpleString& name) : TestPlugin(name) {} virtual ~MyTestPluginDummy() CPPUTEST_DESTRUCTOR_OVERRIDE {} virtual void runAllPreTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE {} virtual void runAllPostTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE {} }; TEST(TestRegistry, ResetPluginsWorks) { MyTestPluginDummy plugin1("Plugin-1"); MyTestPluginDummy plugin2("Plugin-2"); myRegistry->installPlugin(&plugin1); myRegistry->installPlugin(&plugin2); LONGS_EQUAL(2, myRegistry->countPlugins()); myRegistry->resetPlugins(); LONGS_EQUAL(0, myRegistry->countPlugins()); } TEST(TestRegistry, listTestGroupNames_shouldListBackwardsGroup1AfterGroup11AndGroup2OnlyOnce) { test1->setGroupName("GROUP_1"); myRegistry->addTest(test1); test2->setGroupName("GROUP_2"); myRegistry->addTest(test2); test3->setGroupName("GROUP_11"); myRegistry->addTest(test3); test4->setGroupName("GROUP_2"); myRegistry->addTest(test4); myRegistry->listTestGroupNames(*result); SimpleString s = output->getOutput(); STRCMP_EQUAL("GROUP_2 GROUP_11 GROUP_1", s.asCharString()); } TEST(TestRegistry, listTestGroupAndCaseNames_shouldListBackwardsGroupATestaAfterGroupAtestaa) { test1->setGroupName("GROUP_A"); test1->setTestName("test_a"); myRegistry->addTest(test1); test2->setGroupName("GROUP_B"); test2->setTestName("test_b"); myRegistry->addTest(test2); test3->setGroupName("GROUP_A"); test3->setTestName("test_aa"); myRegistry->addTest(test3); myRegistry->listTestGroupAndCaseNames(*result); SimpleString s = output->getOutput(); STRCMP_EQUAL("GROUP_A.test_aa GROUP_B.test_b GROUP_A.test_a", s.asCharString()); } TEST(TestRegistry, listTestLocations_shouldListBackwardsGroupATestaAfterGroupAtestaa) { test1->setGroupName("GROUP_A"); test1->setTestName("test_a"); test1->setFileName("cpptest_simple/my_tests/testa.cpp"); test1->setLineNumber(100); myRegistry->addTest(test1); test2->setGroupName("GROUP_B"); test2->setTestName("test_b"); test2->setFileName("cpptest_simple/my tests/testb.cpp"); test2->setLineNumber(200); myRegistry->addTest(test2); test3->setGroupName("GROUP_A"); test3->setTestName("test_aa"); test3->setFileName("cpptest_simple/my_tests/testaa.cpp"); test3->setLineNumber(300); myRegistry->addTest(test3); myRegistry->listTestLocations(*result); SimpleString s = output->getOutput(); STRCMP_EQUAL("GROUP_A.test_aa.cpptest_simple/my_tests/testaa.cpp.300\nGROUP_B.test_b.cpptest_simple/my tests/testb.cpp.200\nGROUP_A.test_a.cpptest_simple/my_tests/testa.cpp.100\n", s.asCharString()); } TEST(TestRegistry, shuffleEmptyListIsNoOp) { CHECK_TRUE(myRegistry->getFirstTest() == NULLPTR); myRegistry->shuffleTests(0); CHECK_TRUE(myRegistry->getFirstTest() == NULLPTR); } TEST(TestRegistry, shuffleSingleTestIsNoOp) { myRegistry->addTest(test1); myRegistry->shuffleTests(0); CHECK_TRUE(myRegistry->getFirstTest() == test1); } static int getZero() { return 0; } IGNORE_TEST(TestRegistry, shuffleTestList) { UT_PTR_SET(PlatformSpecificRand, getZero); myRegistry->addTest(test3); myRegistry->addTest(test2); myRegistry->addTest(test1); UtestShell* first_before = myRegistry->getFirstTest(); UtestShell* second_before = first_before->getNext(); UtestShell* third_before = second_before->getNext(); CHECK_TRUE(first_before == test1); CHECK_TRUE(second_before == test2); CHECK_TRUE(third_before == test3); CHECK_TRUE(third_before->getNext() == NULLPTR); // shuffle always with element at index 0: [1] 2 [3] --> [3] [2] 1 --> 2 3 1 myRegistry->shuffleTests(0); UtestShell* first_after = myRegistry->getFirstTest(); UtestShell* second_after = first_after->getNext(); UtestShell* third_after = second_after->getNext(); CHECK_TRUE(first_after == test2); CHECK_TRUE(second_after == test3); CHECK_TRUE(third_after == test1); CHECK_TRUE(third_after->getNext() == NULLPTR); } TEST(TestRegistry, reverseTests) { myRegistry->addTest(test1); myRegistry->addTest(test2); myRegistry->reverseTests(); CHECK(test1 == myRegistry->getFirstTest()); } TEST(TestRegistry, reverseZeroTests) { myRegistry->reverseTests(); CHECK(NULLPTR == myRegistry->getFirstTest()); }
null
4
cpp
cpputest
SimpleStringTest.cpp
tests/CppUTest/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/TestMemoryAllocator.h" #include "CppUTest/MemoryLeakDetector.h" #include "CppUTest/TestTestingFixture.h" class JustUseNewStringAllocator : public TestMemoryAllocator { public: virtual ~JustUseNewStringAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE {} char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE { return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(getCurrentNewArrayAllocator(), size, file, line); } void free_memory(char* str, size_t, const char* file, size_t line) CPPUTEST_OVERRIDE { MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(getCurrentNewArrayAllocator(), str, file, line); } }; class GlobalSimpleStringMemoryAccountantExecFunction : public ExecFunction { public: void (*testFunction_)(GlobalSimpleStringMemoryAccountant*); GlobalSimpleStringMemoryAccountant* parameter_; virtual void exec() CPPUTEST_OVERRIDE { testFunction_(parameter_); } }; TEST_GROUP(GlobalSimpleStringMemoryAccountant) { GlobalSimpleStringAllocatorStash stash; GlobalSimpleStringMemoryAccountantExecFunction testFunction; TestTestingFixture fixture; GlobalSimpleStringMemoryAccountant accountant; void setup() CPPUTEST_OVERRIDE { stash.save(); testFunction.parameter_ = &accountant; fixture.setTestFunction(&testFunction); } void teardown() CPPUTEST_OVERRIDE { stash.restore(); } }; TEST(GlobalSimpleStringMemoryAccountant, start) { accountant.start(); POINTERS_EQUAL(accountant.getAllocator(), SimpleString::getStringAllocator()); } TEST(GlobalSimpleStringMemoryAccountant, startTwiceDoesNothing) { accountant.start(); TestMemoryAllocator* memoryAccountantAllocator = SimpleString::getStringAllocator(); accountant.start(); POINTERS_EQUAL(memoryAccountantAllocator, SimpleString::getStringAllocator()); accountant.stop(); } TEST(GlobalSimpleStringMemoryAccountant, stop) { TestMemoryAllocator* originalAllocator = SimpleString::getStringAllocator(); accountant.start(); accountant.stop(); POINTERS_EQUAL(originalAllocator, SimpleString::getStringAllocator()); } static void stopAccountant_(GlobalSimpleStringMemoryAccountant* accountant) { accountant->stop(); } TEST(GlobalSimpleStringMemoryAccountant, stopWithoutStartWillFail) { testFunction.testFunction_ = stopAccountant_; fixture.runAllTests(); fixture.assertPrintContains("Global SimpleString allocator stopped without starting"); } static void changeAllocatorBetweenStartAndStop_(GlobalSimpleStringMemoryAccountant* accountant) { TestMemoryAllocator* originalAllocator = SimpleString::getStringAllocator(); accountant->start(); SimpleString::setStringAllocator(originalAllocator); accountant->stop(); } TEST(GlobalSimpleStringMemoryAccountant, stopFailsWhenAllocatorWasChangedInBetween) { testFunction.testFunction_ = changeAllocatorBetweenStartAndStop_; fixture.runAllTests(); fixture.assertPrintContains("GlobalStrimpleStringMemoryAccountant: allocator has changed between start and stop!"); } TEST(GlobalSimpleStringMemoryAccountant, report) { SimpleString str; accountant.start(); str += "More"; accountant.stop(); STRCMP_CONTAINS(" 1 0 1", accountant.report().asCharString()); } TEST(GlobalSimpleStringMemoryAccountant, reportUseCaches) { size_t caches[] = {32}; accountant.useCacheSizes(caches, 1); SimpleString str; accountant.start(); str += "More"; accountant.stop(); STRCMP_CONTAINS("32 1 1 1", accountant.report().asCharString()); } TEST_GROUP(SimpleString) { JustUseNewStringAllocator justNewForSimpleStringTestAllocator; GlobalSimpleStringAllocatorStash stash; void setup() CPPUTEST_OVERRIDE { stash.save(); SimpleString::setStringAllocator(&justNewForSimpleStringTestAllocator); } void teardown() CPPUTEST_OVERRIDE { stash.restore(); } }; TEST(SimpleString, defaultAllocatorIsNewArrayAllocator) { SimpleString::setStringAllocator(NULLPTR); POINTERS_EQUAL(defaultNewArrayAllocator(), SimpleString::getStringAllocator()); } class MyOwnStringAllocator : public TestMemoryAllocator { public: MyOwnStringAllocator() : memoryWasAllocated(false) {} virtual ~MyOwnStringAllocator() CPPUTEST_DESTRUCTOR_OVERRIDE {} bool memoryWasAllocated; char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE { memoryWasAllocated = true; return TestMemoryAllocator::alloc_memory(size, file, line); } }; TEST(SimpleString, allocatorForSimpleStringCanBeReplaced) { MyOwnStringAllocator myOwnAllocator; SimpleString::setStringAllocator(&myOwnAllocator); SimpleString simpleString; CHECK(myOwnAllocator.memoryWasAllocated); SimpleString::setStringAllocator(NULLPTR); } 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, lowerCase) { SimpleString s1("AbCdEfG1234"); SimpleString s2(s1.lowerCase()); STRCMP_EQUAL("abcdefg1234", s2.asCharString()); STRCMP_EQUAL("AbCdEfG1234", s1.asCharString()); } TEST(SimpleString, printable) { SimpleString s1("ABC\01\06\a\n\r\b\t\v\f\x0E\x1F\x7F""abc"); SimpleString s2(s1.printable()); STRCMP_EQUAL("ABC\\x01\\x06\\a\\n\\r\\b\\t\\v\\f\\x0E\\x1F\\x7Fabc", s2.asCharString()); STRCMP_EQUAL("ABC\01\06\a\n\r\b\t\v\f\x0E\x1F\x7F""abc", s1.asCharString()); } TEST(SimpleString, Addition) { SimpleString s1("hello!"); 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, countEmptyString) { SimpleString str("hahahaha"); LONGS_EQUAL(8, str.count("")); } TEST(SimpleString, countEmptyStringInEmptyString) { SimpleString str; LONGS_EQUAL(0, str.count("")); } 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, replaceEmptyStringWithEmptyString) { SimpleString str; str.replace("", ""); STRCMP_EQUAL("", str.asCharString()); } TEST(SimpleString, replaceWholeString) { SimpleString str("boo"); str.replace("boo", ""); STRCMP_EQUAL("", 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, subStringFromPos6ToEndOfString) { SimpleString str("Hello World"); STRCMP_EQUAL("World", str.subString(6).asCharString()); } TEST(SimpleString, subStringBeginPosOutOfBounds) { SimpleString str("Hello World"); STRCMP_EQUAL("", str.subString(13, 5).asCharString()); } TEST(SimpleString, subStringFromTillNormal) { SimpleString str("Hello World"); STRCMP_EQUAL("Hello", str.subStringFromTill('H', ' ').asCharString()); } TEST(SimpleString, subStringFromTillOutOfBounds) { SimpleString str("Hello World"); STRCMP_EQUAL("World", str.subStringFromTill('W', '!').asCharString()); } TEST(SimpleString, subStringFromTillStartDoesntExist) { SimpleString str("Hello World"); STRCMP_EQUAL("", str.subStringFromTill('!', ' ').asCharString()); } TEST(SimpleString, subStringFromTillWhenTheEndAppearsBeforeTheStart) { SimpleString str("Hello World"); STRCMP_EQUAL("World", str.subStringFromTill('W', 'H').asCharString()); } TEST(SimpleString, findNormal) { SimpleString str("Hello World"); LONGS_EQUAL(0, str.find('H')); LONGS_EQUAL(1, str.find('e')); LONGS_EQUAL(SimpleString::npos, str.find('!')); } TEST(SimpleString, at) { SimpleString str("Hello World"); BYTES_EQUAL('H', str.at(0)); } TEST(SimpleString, copyInBufferNormal) { SimpleString str("Hello World"); size_t bufferSize = str.size()+1; char* buffer = (char*) PlatformSpecificMalloc(bufferSize); str.copyToBuffer(buffer, bufferSize); STRCMP_EQUAL(str.asCharString(), buffer); PlatformSpecificFree(buffer); } TEST(SimpleString, copyInBufferWithEmptyBuffer) { SimpleString str("Hello World"); char* buffer= NULLPTR; str.copyToBuffer(buffer, 0); POINTERS_EQUAL(NULLPTR, buffer); } TEST(SimpleString, copyInBufferWithBiggerBufferThanNeeded) { SimpleString str("Hello"); size_t bufferSize = 20; char* buffer= (char*) PlatformSpecificMalloc(bufferSize); str.copyToBuffer(buffer, bufferSize); STRCMP_EQUAL(str.asCharString(), buffer); PlatformSpecificFree(buffer); } TEST(SimpleString, copyInBufferWithSmallerBufferThanNeeded) { SimpleString str("Hello"); size_t bufferSize = str.size(); char* buffer= (char*) PlatformSpecificMalloc(bufferSize); str.copyToBuffer(buffer, bufferSize); STRNCMP_EQUAL(str.asCharString(), buffer, (bufferSize-1)); LONGS_EQUAL(0, buffer[bufferSize-1]); PlatformSpecificFree(buffer); } TEST(SimpleString, ContainsNull) { SimpleString s(NULLPTR); STRCMP_EQUAL("", s.asCharString()); } TEST(SimpleString, NULLReportsNullString) { STRCMP_EQUAL("(null)", StringFromOrNull((char*) NULLPTR).asCharString()); } TEST(SimpleString, NULLReportsNullStringPrintable) { STRCMP_EQUAL("(null)", PrintableStringFromOrNull((char*) NULLPTR).asCharString()); } TEST(SimpleString, Booleans) { SimpleString s1(StringFrom(true)); SimpleString s2(StringFrom(false)); CHECK(s1 == "true"); CHECK(s2 == "false"); } TEST(SimpleString, Pointers) { SimpleString s(StringFrom((void *)0x1234)); STRCMP_EQUAL("0x1234", s.asCharString()); } TEST(SimpleString, FunctionPointers) { SimpleString s(StringFrom((void (*)())0x1234)); STRCMP_EQUAL("0x1234", s.asCharString()); } TEST(SimpleString, Characters) { SimpleString s(StringFrom('a')); STRCMP_EQUAL("a", s.asCharString()); } TEST(SimpleString, NegativeSignedBytes) { STRCMP_EQUAL("-15", StringFrom((signed char)-15).asCharString()); } TEST(SimpleString, PositiveSignedBytes) { STRCMP_EQUAL("4", StringFrom(4).asCharString()); } TEST(SimpleString, LongInts) { SimpleString s(StringFrom((long)1)); CHECK(s == "1"); } TEST(SimpleString, UnsignedLongInts) { SimpleString s(StringFrom((unsigned long)1)); SimpleString s2(StringFrom((unsigned long)1)); CHECK(s == s2); } #if CPPUTEST_USE_LONG_LONG TEST(SimpleString, LongLongInts) { SimpleString s(StringFrom((long long)1)); CHECK(s == "1"); } TEST(SimpleString, UnsignedLongLongInts) { SimpleString s(StringFrom((unsigned long long)1)); SimpleString s2(StringFrom((unsigned long long)1)); CHECK(s == s2); } #endif /* CPPUTEST_USE_LONG_LONG */ TEST(SimpleString, Doubles) { SimpleString s(StringFrom(1.2)); STRCMP_EQUAL("1.2", s.asCharString()); } extern "C" { static int alwaysTrue(double) { return true; } } TEST(SimpleString, NaN) { UT_PTR_SET(PlatformSpecificIsNan, alwaysTrue); SimpleString s(StringFrom(0.0)); STRCMP_EQUAL("Nan - Not a number", s.asCharString()); } TEST(SimpleString, Inf) { UT_PTR_SET(PlatformSpecificIsInf, alwaysTrue); SimpleString s(StringFrom(0.0)); STRCMP_EQUAL("Inf - Infinity", s.asCharString()); } TEST(SimpleString, SmallDoubles) { SimpleString s(StringFrom(1.2e-10)); STRCMP_CONTAINS("1.2e", s.asCharString()); } TEST(SimpleString, Sizes) { size_t size = 10; STRCMP_EQUAL("10", StringFrom((int) size).asCharString()); } #if __cplusplus > 199711L && !defined __arm__ && CPPUTEST_USE_STD_CPP_LIB TEST(SimpleString, nullptr_type) { SimpleString s(StringFrom(NULLPTR)); STRCMP_EQUAL("(null)", s.asCharString()); } #endif TEST(SimpleString, HexStrings) { STRCMP_EQUAL("f3", HexStringFrom((signed char)-13).asCharString()); SimpleString h1 = HexStringFrom(0xffffL); STRCMP_EQUAL("ffff", h1.asCharString()); #if CPPUTEST_USE_LONG_LONG SimpleString h15 = HexStringFrom(0xffffLL); STRCMP_EQUAL("ffff", h15.asCharString()); #endif SimpleString h2 = HexStringFrom((void *)0xfffeL); STRCMP_EQUAL("fffe", h2.asCharString()); SimpleString h3 = HexStringFrom((void (*)())0xfffdL); STRCMP_EQUAL("fffd", h3.asCharString()); } TEST(SimpleString, StringFromFormat) { SimpleString h1 = StringFromFormat("%s %s! %d", "Hello", "World", 2009); STRCMP_EQUAL("Hello World! 2009", h1.asCharString()); } TEST(SimpleString, StringFromFormatpointer) { //this is not a great test. but %p is odd on mingw and even more odd on Solaris. SimpleString h1 = StringFromFormat("%p", (void*) 1); if (h1.size() == 3) STRCMP_EQUAL("0x1", h1.asCharString()); else if (h1.size() == 8) STRCMP_EQUAL("00000001", h1.asCharString()); else if (h1.size() == 9) STRCMP_EQUAL("0000:0001", h1.asCharString()); else if (h1.size() == 16) STRCMP_EQUAL("0000000000000001", h1.asCharString()); else if (h1.size() == 1) STRCMP_EQUAL("1", h1.asCharString()); else FAIL("Off %p behavior"); } TEST(SimpleString, StringFromFormatLarge) { const char* s = "ThisIsAPrettyLargeStringAndIfWeAddThisManyTimesToABufferItWillbeFull"; SimpleString h1 = StringFromFormat("%s%s%s%s%s%s%s%s%s%s", s, s, s, s, s, s, s, s, s, s); LONGS_EQUAL(10, h1.count(s)); } TEST(SimpleString, StringFromConstSimpleString) { STRCMP_EQUAL("bla", StringFrom(SimpleString("bla")).asCharString()); } static int WrappedUpVSNPrintf(char* buf, size_t n, const char* format, ...) { va_list arguments; va_start(arguments, format); int result = PlatformSpecificVSNprintf(buf, n, format, arguments); va_end(arguments); return result; } TEST(SimpleString, PlatformSpecificSprintf_fits) { char buf[10]; int count = WrappedUpVSNPrintf(buf, sizeof(buf), "%s", "12345"); STRCMP_EQUAL("12345", buf); LONGS_EQUAL(5, count); } TEST(SimpleString, PlatformSpecificSprintf_doesNotFit) { char buf[10]; int count = WrappedUpVSNPrintf(buf, sizeof(buf), "%s", "12345678901"); STRCMP_EQUAL("123456789", buf); LONGS_EQUAL(11, count); } TEST(SimpleString, PadStringsToSameLengthString1Larger) { SimpleString str1("1"); SimpleString str2("222"); SimpleString::padStringsToSameLength(str1, str2, '4'); STRCMP_EQUAL("441", str1.asCharString()); STRCMP_EQUAL("222", str2.asCharString()); } TEST(SimpleString, PadStringsToSameLengthString2Larger) { SimpleString str1(" "); SimpleString str2(""); SimpleString::padStringsToSameLength(str1, str2, ' '); STRCMP_EQUAL(" ", str1.asCharString()); STRCMP_EQUAL(" ", str2.asCharString()); } TEST(SimpleString, PadStringsToSameLengthWithSameLengthStrings) { SimpleString str1("123"); SimpleString str2("123"); SimpleString::padStringsToSameLength(str1, str2, ' '); STRCMP_EQUAL("123", str1.asCharString()); STRCMP_EQUAL("123", str2.asCharString()); } TEST(SimpleString, NullParameters2) { SimpleString* arr = new SimpleString[100]; delete[] arr; } TEST(SimpleString, CollectionMultipleAllocateNoLeaksMemory) { SimpleStringCollection col; col.allocate(5); col.allocate(5); // CHECK no memory leak } TEST(SimpleString, CollectionReadOutOfBoundsReturnsEmptyString) { SimpleStringCollection col; col.allocate(3); STRCMP_EQUAL("", col[3].asCharString()); } TEST(SimpleString, CollectionWritingToEmptyString) { SimpleStringCollection col; col.allocate(3); col[3] = SimpleString("HAH"); STRCMP_EQUAL("", col[3].asCharString()); } #ifdef CPPUTEST_64BIT TEST(SimpleString, 64BitAddressPrintsCorrectly) { char* p = (char*) 0x0012345678901234; SimpleString expected("0x12345678901234"); SimpleString actual = StringFrom((void*)p); STRCMP_EQUAL(expected.asCharString(), actual.asCharString()); } #ifndef CPPUTEST_64BIT_32BIT_LONGS TEST(SimpleString, BracketsFormattedHexStringFromForLongOnDifferentPlatform) { long value = -1; STRCMP_EQUAL("(0xffffffffffffffff)", BracketsFormattedHexStringFrom(value).asCharString()); } #else TEST(SimpleString, BracketsFormattedHexStringFromForLongOnDifferentPlatform) { long value = -1; STRCMP_EQUAL("(0xffffffff)", BracketsFormattedHexStringFrom(value).asCharString()); } #endif #else /* * This test case cannot pass on 32 bit systems. */ IGNORE_TEST(SimpleString, 64BitAddressPrintsCorrectly) { } TEST(SimpleString, BracketsFormattedHexStringFromForLongOnDifferentPlatform) { long value = -1; STRCMP_EQUAL("(0xffffffff)", BracketsFormattedHexStringFrom(value).asCharString()); } #endif TEST(SimpleString, BuildStringFromUnsignedLongInteger) { unsigned long int i = 0xffffffff; SimpleString result = StringFrom(i); const char* expected_string = "4294967295"; CHECK_EQUAL(expected_string, result); } TEST(SimpleString, BuildStringFromUnsignedInteger) { unsigned int i = 0xff; SimpleString result = StringFrom(i); const char* expected_string = "255"; CHECK_EQUAL(expected_string, result); } #if CPPUTEST_USE_STD_CPP_LIB TEST(SimpleString, fromStdString) { std::string s("hello"); SimpleString s1(StringFrom(s)); STRCMP_EQUAL("hello", s1.asCharString()); } TEST(SimpleString, CHECK_EQUAL_unsigned_long) { unsigned long i = 0xffffffffUL; CHECK_EQUAL(i, i); } TEST(SimpleString, unsigned_long) { unsigned long i = 0xffffffffUL; SimpleString result = StringFrom(i); const char* expected_string = "4294967295"; CHECK_EQUAL(expected_string, result); } #endif TEST(SimpleString, StrCmp) { char empty[] = ""; char blabla[] = "blabla"; char bla[] = "bla"; CHECK(SimpleString::StrCmp(empty, empty) == 0); CHECK(SimpleString::StrCmp(bla, blabla) == -(int)'b'); CHECK(SimpleString::StrCmp(blabla, bla) == 'b'); CHECK(SimpleString::StrCmp(bla, empty) == 'b'); CHECK(SimpleString::StrCmp(empty, bla) == -(int)'b'); CHECK(SimpleString::StrCmp(bla, bla) == 0); } TEST(SimpleString, StrNCpy_no_zero_termination) { char str[] = "XXXXXXXXXX"; STRCMP_EQUAL("womanXXXXX", SimpleString::StrNCpy(str, "woman", 5)); } TEST(SimpleString, StrNCpy_zero_termination) { char str[] = "XXXXXXXXXX"; STRCMP_EQUAL("woman", SimpleString::StrNCpy(str, "woman", 6)); } TEST(SimpleString, StrNCpy_null_proof) { POINTERS_EQUAL(NULLPTR, SimpleString::StrNCpy(NULLPTR, "woman", 6)); } TEST(SimpleString, StrNCpy_stops_at_end_of_string) { char str[] = "XXXXXXXXXX"; STRCMP_EQUAL("woman", SimpleString::StrNCpy(str, "woman", 8)); } TEST(SimpleString, StrNCpy_nothing_to_do) { char str[] = "XXXXXXXXXX"; STRCMP_EQUAL("XXXXXXXXXX", SimpleString::StrNCpy(str, "woman", 0)); } TEST(SimpleString, StrNCpy_write_into_the_middle) { char str[] = "womanXXXXX"; SimpleString::StrNCpy(str+3, "e", 1); STRCMP_EQUAL("womenXXXXX", str); } TEST(SimpleString, StrNCmp_equal) { int result = SimpleString::StrNCmp("teststring", "tests", 5); LONGS_EQUAL(0, result); } TEST(SimpleString, StrNCmp_should_always_return_0_when_n_is_0) { int result = SimpleString::StrNCmp("a", "b", 0); LONGS_EQUAL(0, result); } TEST(SimpleString, StrNCmp_s1_smaller) { int result = SimpleString::StrNCmp("testing", "tests", 7); LONGS_EQUAL('i' - 's', result); } TEST(SimpleString, StrNCmp_s1_larger) { int result = SimpleString::StrNCmp("teststring", "tester", 7); LONGS_EQUAL('s' - 'e', result); } TEST(SimpleString, StrNCmp_n_too_large) { int result = SimpleString::StrNCmp("teststring", "teststring", 20); LONGS_EQUAL(0, result); } TEST(SimpleString, StrNCmp_s1_empty) { int result = SimpleString::StrNCmp("", "foo", 2); LONGS_EQUAL(0 - 'f', result); } TEST(SimpleString, StrNCmp_s2_empty) { int result = SimpleString::StrNCmp("foo", "", 2); LONGS_EQUAL('f', result); } TEST(SimpleString, StrNCmp_s1_and_s2_empty) { int result = SimpleString::StrNCmp("", "", 2); LONGS_EQUAL(0, result); } TEST(SimpleString, StrStr) { char foo[] = "foo"; char empty[] = ""; char foobarfoo[] = "foobarfoo"; char barf[] = "barf"; CHECK(SimpleString::StrStr(foo, empty) == foo); CHECK(SimpleString::StrStr(empty, foo) == NULLPTR); CHECK(SimpleString::StrStr(foobarfoo, barf) == foobarfoo+3); CHECK(SimpleString::StrStr(barf, foobarfoo) == NULLPTR); CHECK(SimpleString::StrStr(foo, foo) == foo); } TEST(SimpleString, AtoI) { char max_short_str[] = "32767"; char min_short_str[] = "-32768"; CHECK(12345 == SimpleString::AtoI("012345")); CHECK(6789 == SimpleString::AtoI("6789")); CHECK(12345 == SimpleString::AtoI("12345/")); CHECK(12345 == SimpleString::AtoI("12345:")); CHECK(-12345 == SimpleString::AtoI("-12345")); CHECK(123 == SimpleString::AtoI("\t \r\n123")); CHECK(123 == SimpleString::AtoI("123-foo")); CHECK(0 == SimpleString::AtoI("-foo")); CHECK(-32768 == SimpleString::AtoI(min_short_str)); CHECK(32767 == SimpleString::AtoI(max_short_str)); } TEST(SimpleString, AtoU) { char max_short_str[] = "65535"; CHECK(12345 == SimpleString::AtoU("012345")); CHECK(6789 == SimpleString::AtoU("6789")); CHECK(12345 == SimpleString::AtoU("12345/")); CHECK(12345 == SimpleString::AtoU("12345:")); CHECK(123 == SimpleString::AtoU("\t \r\n123")); CHECK(123 == SimpleString::AtoU("123-foo")); CHECK(65535 == SimpleString::AtoU(max_short_str)); CHECK(0 == SimpleString::AtoU("foo")); CHECK(0 == SimpleString::AtoU("-foo")); CHECK(0 == SimpleString::AtoU("+1")); CHECK(0 == SimpleString::AtoU("-1")); CHECK(0 == SimpleString::AtoU("0")); } TEST(SimpleString, Binary) { const unsigned char value[] = { 0x00, 0x01, 0x2A, 0xFF }; const char expectedString[] = "00 01 2A FF"; STRCMP_EQUAL(expectedString, StringFromBinary(value, sizeof(value)).asCharString()); STRCMP_EQUAL(expectedString, StringFromBinaryOrNull(value, sizeof(value)).asCharString()); STRCMP_EQUAL("", StringFromBinary(value, 0).asCharString()); STRCMP_EQUAL("(null)", StringFromBinaryOrNull(NULLPTR, 0).asCharString()); } TEST(SimpleString, BinaryWithSize) { const unsigned char value[] = { 0x12, 0xFE, 0xA1 }; const char expectedString[] = "Size = 3 | HexContents = 12 FE A1"; STRCMP_EQUAL(expectedString, StringFromBinaryWithSize(value, sizeof(value)).asCharString()); STRCMP_EQUAL(expectedString, StringFromBinaryWithSizeOrNull(value, sizeof(value)).asCharString()); STRCMP_EQUAL("Size = 0 | HexContents = ", StringFromBinaryWithSize(value, 0).asCharString()); STRCMP_EQUAL("(null)", StringFromBinaryWithSizeOrNull(NULLPTR, 0).asCharString()); } TEST(SimpleString, BinaryWithSizeLargerThan128) { unsigned char value[129]; value[127] = 0x00; value[128] = 0xff; STRCMP_CONTAINS("00 ...", StringFromBinaryWithSize(value, sizeof(value)).asCharString()); } TEST(SimpleString, MemCmp) { unsigned char smaller[] = { 0x00, 0x01, 0x2A, 0xFF }; unsigned char greater[] = { 0x00, 0x01, 0xFF, 0xFF }; LONGS_EQUAL(0, SimpleString::MemCmp(smaller, smaller, sizeof(smaller))); CHECK(SimpleString::MemCmp(smaller, greater, sizeof(smaller)) < 0); CHECK(SimpleString::MemCmp(greater, smaller, sizeof(smaller)) > 0); LONGS_EQUAL(0, SimpleString::MemCmp(NULLPTR, NULLPTR, 0)); } TEST(SimpleString, MemCmpFirstLastNotMatching) { unsigned char base[] = { 0x00, 0x01, 0x2A, 0xFF }; unsigned char firstNotMatching[] = { 0x01, 0x01, 0x2A, 0xFF }; unsigned char lastNotMatching[] = { 0x00, 0x01, 0x2A, 0x00 }; CHECK(0 != SimpleString::MemCmp(base, firstNotMatching, sizeof(base))); CHECK(0 != SimpleString::MemCmp(base, lastNotMatching, sizeof(base))); } #if (CPPUTEST_CHAR_BIT == 16) TEST(SimpleString, MaskedBitsChar) { STRCMP_EQUAL("xxxxxxxx xxxxxxxx", StringFromMaskedBits(0x00, 0x00, 1).asCharString()); STRCMP_EQUAL("xxxxxxxx 00000000", StringFromMaskedBits(0x00, 0xFF, 1).asCharString()); STRCMP_EQUAL("xxxxxxxx 11111111", StringFromMaskedBits(0xFF, 0xFF, 1).asCharString()); STRCMP_EQUAL("xxxxxxxx 1xxxxxxx", StringFromMaskedBits(0x80, 0x80, 1).asCharString()); STRCMP_EQUAL("xxxxxxxx xxxxxxx1", StringFromMaskedBits(0x01, 0x01, 1).asCharString()); STRCMP_EQUAL("xxxxxxxx 11xx11xx", StringFromMaskedBits(0xFF, 0xCC, 1).asCharString()); } #elif (CPPUTEST_CHAR_BIT == 8) TEST(SimpleString, MaskedBitsChar) { STRCMP_EQUAL("xxxxxxxx", StringFromMaskedBits(0x00, 0x00, 1).asCharString()); STRCMP_EQUAL("00000000", StringFromMaskedBits(0x00, 0xFF, 1).asCharString()); STRCMP_EQUAL("11111111", StringFromMaskedBits(0xFF, 0xFF, 1).asCharString()); STRCMP_EQUAL("1xxxxxxx", StringFromMaskedBits(0x80, 0x80, 1).asCharString()); STRCMP_EQUAL("xxxxxxx1", StringFromMaskedBits(0x01, 0x01, 1).asCharString()); STRCMP_EQUAL("11xx11xx", StringFromMaskedBits(0xFF, 0xCC, 1).asCharString()); } #endif TEST(SimpleString, MaskedBits16Bit) { STRCMP_EQUAL("xxxxxxxx xxxxxxxx", StringFromMaskedBits(0x0000, 0x0000, 2*8/CPPUTEST_CHAR_BIT).asCharString()); STRCMP_EQUAL("00000000 00000000", StringFromMaskedBits(0x0000, 0xFFFF, 2*8/CPPUTEST_CHAR_BIT).asCharString()); STRCMP_EQUAL("11111111 11111111", StringFromMaskedBits(0xFFFF, 0xFFFF, 2*8/CPPUTEST_CHAR_BIT).asCharString()); STRCMP_EQUAL("1xxxxxxx xxxxxxxx", StringFromMaskedBits(0x8000, 0x8000, 2*8/CPPUTEST_CHAR_BIT).asCharString()); STRCMP_EQUAL("xxxxxxxx xxxxxxx1", StringFromMaskedBits(0x0001, 0x0001, 2*8/CPPUTEST_CHAR_BIT).asCharString()); STRCMP_EQUAL("11xx11xx 11xx11xx", StringFromMaskedBits(0xFFFF, 0xCCCC, 2*8/CPPUTEST_CHAR_BIT).asCharString()); } TEST(SimpleString, MaskedBits32Bit) { STRCMP_EQUAL("xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx", StringFromMaskedBits(0x00000000, 0x00000000, 4*8/CPPUTEST_CHAR_BIT).asCharString()); STRCMP_EQUAL("00000000 00000000 00000000 00000000", StringFromMaskedBits(0x00000000, 0xFFFFFFFF, 4*8/CPPUTEST_CHAR_BIT).asCharString()); STRCMP_EQUAL("11111111 11111111 11111111 11111111", StringFromMaskedBits(0xFFFFFFFF, 0xFFFFFFFF, 4*8/CPPUTEST_CHAR_BIT).asCharString()); STRCMP_EQUAL("1xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx", StringFromMaskedBits(0x80000000, 0x80000000, 4*8/CPPUTEST_CHAR_BIT).asCharString()); STRCMP_EQUAL("xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxx1", StringFromMaskedBits(0x00000001, 0x00000001, 4*8/CPPUTEST_CHAR_BIT).asCharString()); STRCMP_EQUAL("11xx11xx 11xx11xx 11xx11xx 11xx11xx", StringFromMaskedBits(0xFFFFFFFF, 0xCCCCCCCC, 4*8/CPPUTEST_CHAR_BIT).asCharString()); } TEST(SimpleString, StringFromOrdinalNumberOnes) { STRCMP_EQUAL("2nd", StringFromOrdinalNumber(2).asCharString()); STRCMP_EQUAL("3rd", StringFromOrdinalNumber(3).asCharString()); STRCMP_EQUAL("4th", StringFromOrdinalNumber(4).asCharString()); STRCMP_EQUAL("5th", StringFromOrdinalNumber(5).asCharString()); STRCMP_EQUAL("6th", StringFromOrdinalNumber(6).asCharString()); STRCMP_EQUAL("7th", StringFromOrdinalNumber(7).asCharString()); } TEST(SimpleString, StringFromOrdinalNumberTens) { STRCMP_EQUAL("10th", StringFromOrdinalNumber(10).asCharString()); STRCMP_EQUAL("11th", StringFromOrdinalNumber(11).asCharString()); STRCMP_EQUAL("12th", StringFromOrdinalNumber(12).asCharString()); STRCMP_EQUAL("13th", StringFromOrdinalNumber(13).asCharString()); STRCMP_EQUAL("14th", StringFromOrdinalNumber(14).asCharString()); STRCMP_EQUAL("18th", StringFromOrdinalNumber(18).asCharString()); } TEST(SimpleString, StringFromOrdinalNumberOthers) { STRCMP_EQUAL("21st", StringFromOrdinalNumber(21).asCharString()); STRCMP_EQUAL("22nd", StringFromOrdinalNumber(22).asCharString()); STRCMP_EQUAL("23rd", StringFromOrdinalNumber(23).asCharString()); STRCMP_EQUAL("24th", StringFromOrdinalNumber(24).asCharString()); STRCMP_EQUAL("32nd", StringFromOrdinalNumber(32).asCharString()); STRCMP_EQUAL("100th", StringFromOrdinalNumber(100).asCharString()); STRCMP_EQUAL("101st", StringFromOrdinalNumber(101).asCharString()); } TEST(SimpleString, BracketsFormattedHexStringFromForSignedChar) { signed char value = 'c'; STRCMP_EQUAL("(0x63)", BracketsFormattedHexStringFrom(value).asCharString()); } TEST(SimpleString, BracketsFormattedHexStringFromForUnsignedInt) { unsigned int value = 1; STRCMP_EQUAL("(0x1)", BracketsFormattedHexStringFrom(value).asCharString()); } TEST(SimpleString, BracketsFormattedHexStringFromForUnsignedLong) { unsigned long value = 1; STRCMP_EQUAL("(0x1)", BracketsFormattedHexStringFrom(value).asCharString()); } #ifdef CPPUTEST_16BIT_INTS TEST(SimpleString, BracketsFormattedHexStringFromForInt) { int value = -1; STRCMP_EQUAL("(0xffff)", BracketsFormattedHexStringFrom(value).asCharString()); } #else TEST(SimpleString, BracketsFormattedHexStringFromForInt) { int value = -1; STRCMP_EQUAL("(0xffffffff)", BracketsFormattedHexStringFrom(value).asCharString()); } #endif TEST(SimpleString, BracketsFormattedHexStringFromForLong) { long value = 1; STRCMP_EQUAL("(0x1)", BracketsFormattedHexStringFrom(value).asCharString()); } #if CPPUTEST_USE_LONG_LONG TEST(SimpleString, BracketsFormattedHexStringFromForLongLong) { cpputest_longlong value = 1; STRCMP_EQUAL("(0x1)", BracketsFormattedHexStringFrom(value).asCharString()); } TEST(SimpleString, BracketsFormattedHexStringFromForULongLong) { cpputest_ulonglong value = 1; STRCMP_EQUAL("(0x1)", BracketsFormattedHexStringFrom(value).asCharString()); } #else TEST(SimpleString, BracketsFormattedHexStringFromForLongLong) { cpputest_longlong value; STRCMP_EQUAL("", BracketsFormattedHexStringFrom(value).asCharString()); } TEST(SimpleString, BracketsFormattedHexStringFromForULongLong) { cpputest_ulonglong value; STRCMP_EQUAL("", BracketsFormattedHexStringFrom(value).asCharString()); } #endif
null
5
cpp
cpputest
CommandLineTestRunnerTest.cpp
tests/CppUTest/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" #include "CppUTest/JUnitTestOutput.h" #include "CppUTest/PlatformSpecificFunctions.h" class DummyPluginWhichCountsThePlugins : public TestPlugin { public: bool returnValue; int amountOfPlugins; DummyPluginWhichCountsThePlugins(const SimpleString& name, TestRegistry* registry) : TestPlugin(name), returnValue(true), amountOfPlugins(0), registry_(registry) { } virtual bool parseArguments(int, const char *const *, int) CPPUTEST_OVERRIDE { /* Remove ourselves from the count */ amountOfPlugins = registry_->countPlugins() - 1; return returnValue; } private: TestRegistry* registry_; }; class CommandLineTestRunnerWithStringBufferOutput : public CommandLineTestRunner { public: StringBufferTestOutput* fakeJUnitOutputWhichIsReallyABuffer_; StringBufferTestOutput* fakeConsoleOutputWhichIsReallyABuffer; StringBufferTestOutput* fakeTCOutputWhichIsReallyABuffer; CommandLineTestRunnerWithStringBufferOutput(int argc, const char *const *argv, TestRegistry* registry) : CommandLineTestRunner(argc, argv, registry), fakeJUnitOutputWhichIsReallyABuffer_(NULLPTR), fakeConsoleOutputWhichIsReallyABuffer(NULLPTR), fakeTCOutputWhichIsReallyABuffer(NULLPTR) {} TestOutput* createConsoleOutput() CPPUTEST_OVERRIDE { fakeConsoleOutputWhichIsReallyABuffer = new StringBufferTestOutput; return fakeConsoleOutputWhichIsReallyABuffer; } TestOutput* createJUnitOutput(const SimpleString&) CPPUTEST_OVERRIDE { fakeJUnitOutputWhichIsReallyABuffer_ = new StringBufferTestOutput; return fakeJUnitOutputWhichIsReallyABuffer_; } TestOutput* createTeamCityOutput() CPPUTEST_OVERRIDE { fakeTCOutputWhichIsReallyABuffer = new StringBufferTestOutput; return fakeTCOutputWhichIsReallyABuffer; } }; TEST_GROUP(CommandLineTestRunner) { TestRegistry registry; UtestShell *test1; UtestShell *test2; DummyPluginWhichCountsThePlugins* pluginCountingPlugin; void setup() CPPUTEST_OVERRIDE { test1 = new UtestShell("group1", "test1", "file1", 1); test2 = new UtestShell("group2", "test2", "file2", 2); registry.addTest(test1); pluginCountingPlugin = new DummyPluginWhichCountsThePlugins("PluginCountingPlugin", &registry); } void teardown() CPPUTEST_OVERRIDE { delete pluginCountingPlugin; delete test2; delete test1; } SimpleString runAndGetOutput(const int argc, const char* argv[]) { CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(argc, argv, &registry); commandLineTestRunner.runAllTestsMain(); return commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput(); } }; TEST(CommandLineTestRunner, OnePluginGetsInstalledDuringTheRunningTheTests) { const char* argv[] = { "tests.exe", "-psomething"}; registry.installPlugin(pluginCountingPlugin); CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); commandLineTestRunner.runAllTestsMain(); registry.removePluginByName("PluginCountingPlugin"); LONGS_EQUAL(0, registry.countPlugins()); LONGS_EQUAL(1, pluginCountingPlugin->amountOfPlugins); } TEST(CommandLineTestRunner, NoPluginsAreInstalledAtTheEndOfARunWhenTheArgumentsAreInvalid) { const char* argv[] = { "tests.exe", "-fdskjnfkds"}; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); commandLineTestRunner.runAllTestsMain(); LONGS_EQUAL(0, registry.countPlugins()); } TEST(CommandLineTestRunner, ReturnsOneWhenTheArgumentsAreInvalid) { const char* argv[] = { "tests.exe", "-some-invalid=parameter" }; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); int returned = commandLineTestRunner.runAllTestsMain(); LONGS_EQUAL(1, returned); } TEST(CommandLineTestRunner, ReturnsOnePrintsHelpOnHelp) { const char* argv[] = { "tests.exe", "-h" }; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); int returned = commandLineTestRunner.runAllTestsMain(); LONGS_EQUAL(1, returned); STRCMP_CONTAINS("Thanks for using CppUTest.", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); } TEST(CommandLineTestRunner, ReturnsZeroWhenNoErrors) { const char* argv[] = { "tests.exe" }; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(1, argv, &registry); int returned = commandLineTestRunner.runAllTestsMain(); LONGS_EQUAL(0, returned); } TEST(CommandLineTestRunner, ReturnsOneWhenNoTestsMatchProvidedFilter) { const char* argv[] = { "tests.exe", "-g", "NoSuchGroup"}; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(3, argv, &registry); int returned = commandLineTestRunner.runAllTestsMain(); LONGS_EQUAL(1, returned); } TEST(CommandLineTestRunner, TeamcityOutputEnabled) { const char* argv[] = {"tests.exe", "-oteamcity"}; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); commandLineTestRunner.runAllTestsMain(); CHECK(commandLineTestRunner.fakeTCOutputWhichIsReallyABuffer != NULLPTR); } TEST(CommandLineTestRunner, JunitOutputEnabled) { const char* argv[] = { "tests.exe", "-ojunit"}; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); commandLineTestRunner.runAllTestsMain(); CHECK(commandLineTestRunner.fakeJUnitOutputWhichIsReallyABuffer_ != NULLPTR); } TEST(CommandLineTestRunner, JunitOutputAndVerboseEnabled) { const char* argv[] = { "tests.exe", "-ojunit", "-v"}; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(3, argv, &registry); commandLineTestRunner.runAllTestsMain(); STRCMP_CONTAINS("TEST(group1, test1)", commandLineTestRunner.fakeJUnitOutputWhichIsReallyABuffer_->getOutput().asCharString()); STRCMP_CONTAINS("TEST(group1, test1)", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); } TEST(CommandLineTestRunner, veryVerboseSetOnOutput) { const char* argv[] = { "tests.exe", "-vv"}; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); commandLineTestRunner.runAllTestsMain(); STRCMP_CONTAINS("TEST(group1, test1)", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); STRCMP_CONTAINS("destroyTest", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); } TEST(CommandLineTestRunner, defaultTestsAreRunInOrderTheyAreInRepository) { const char* argv[] = { "tests.exe", "-v"}; registry.addTest(test2); CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); commandLineTestRunner.runAllTestsMain(); SimpleStringCollection stringCollection; commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().split("\n", stringCollection); STRCMP_CONTAINS("test2", stringCollection[0].asCharString()); STRCMP_CONTAINS("test1", stringCollection[1].asCharString()); } TEST(CommandLineTestRunner, testsCanBeRunInReverseOrder) { const char* argv[] = { "tests.exe", "-v", "-b"}; registry.addTest(test2); CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(3, argv, &registry); commandLineTestRunner.runAllTestsMain(); SimpleStringCollection stringCollection; commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().split("\n", stringCollection); STRCMP_CONTAINS("test1", stringCollection[0].asCharString()); STRCMP_CONTAINS("test2", stringCollection[1].asCharString()); } TEST(CommandLineTestRunner, listTestGroupNamesShouldWorkProperly) { const char* argv[] = { "tests.exe", "-lg" }; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); commandLineTestRunner.runAllTestsMain(); STRCMP_CONTAINS("group", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); } TEST(CommandLineTestRunner, listTestGroupAndCaseNamesShouldWorkProperly) { const char* argv[] = { "tests.exe", "-ln" }; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); commandLineTestRunner.runAllTestsMain(); STRCMP_CONTAINS("group1.test1", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); } TEST(CommandLineTestRunner, listTestLocationsShouldWorkProperly) { const char* argv[] = { "tests.exe", "-ll" }; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); commandLineTestRunner.runAllTestsMain(); STRCMP_CONTAINS("group1.test1", commandLineTestRunner.fakeConsoleOutputWhichIsReallyABuffer->getOutput().asCharString()); } TEST(CommandLineTestRunner, randomShuffleSeedIsPrintedAndRandFuncIsExercised) { // more than 1 item in test list ensures that shuffle algorithm calls rand_() UtestShell *anotherTest = new UtestShell("group", "test2", "file", 1); registry.addTest(anotherTest); const char* argv[] = { "tests.exe", "-s"}; SimpleString text = runAndGetOutput(2, argv); STRCMP_CONTAINS("shuffling enabled with seed:", text.asCharString()); delete anotherTest; } TEST(CommandLineTestRunner, specificShuffleSeedIsPrintedVerbose) { const char* argv[] = { "tests.exe", "-s2", "-v"}; SimpleString text = runAndGetOutput(3, argv); STRCMP_CONTAINS("shuffling enabled with seed: 2", text.asCharString()); } extern "C" { typedef PlatformSpecificFile (*FOpenFunc)(const char*, const char*); typedef void (*FPutsFunc)(const char*, PlatformSpecificFile); typedef void (*FCloseFunc)(PlatformSpecificFile); } struct FakeOutput { FakeOutput() : SaveFOpen(PlatformSpecificFOpen), SaveFPuts(PlatformSpecificFPuts), SaveFClose(PlatformSpecificFClose) { installFakes(); currentFake = this; } ~FakeOutput() { currentFake = NULLPTR; restoreOriginals(); } void installFakes() { PlatformSpecificFOpen = (FOpenFunc)fopen_fake; PlatformSpecificFPuts = (FPutsFunc)fputs_fake; PlatformSpecificFClose = (FCloseFunc)fclose_fake; } void restoreOriginals() { PlatformSpecificFOpen = SaveFOpen; PlatformSpecificFPuts = SaveFPuts; PlatformSpecificFClose = SaveFClose; } static PlatformSpecificFile fopen_fake(const char*, const char*) { return (PlatformSpecificFile) NULLPTR; } static void fputs_fake(const char* str, PlatformSpecificFile f) { if (f == PlatformSpecificStdOut) { currentFake->console += str; } else { currentFake->file += str; } } static void fclose_fake(PlatformSpecificFile) { } SimpleString file; SimpleString console; static FakeOutput* currentFake; private: FOpenFunc SaveFOpen; FPutsFunc SaveFPuts; FCloseFunc SaveFClose; }; FakeOutput* FakeOutput::currentFake = NULLPTR; TEST(CommandLineTestRunner, realJunitOutputShouldBeCreatedAndWorkProperly) { const char* argv[] = { "tests.exe", "-ojunit", "-v", "-kpackage", }; FakeOutput fakeOutput; /* UT_PTR_SET() is not reentrant */ CommandLineTestRunner commandLineTestRunner(4, argv, &registry); commandLineTestRunner.runAllTestsMain(); fakeOutput.restoreOriginals(); STRCMP_CONTAINS("<testcase classname=\"package.group1\" name=\"test1\"", fakeOutput.file.asCharString()); STRCMP_CONTAINS("TEST(group1, test1)", fakeOutput.console.asCharString()); } TEST(CommandLineTestRunner, realTeamCityOutputShouldBeCreatedAndWorkProperly) { const char* argv[] = { "tests.exe", "-oteamcity", "-v", "-kpackage", }; FakeOutput fakeOutput; /* UT_PTR_SET() is not reentrant */ CommandLineTestRunner commandLineTestRunner(4, argv, &registry); commandLineTestRunner.runAllTestsMain(); fakeOutput.restoreOriginals(); STRCMP_CONTAINS("##teamcity[testSuiteStarted name='group1'", fakeOutput.console.asCharString()); STRCMP_CONTAINS("##teamcity[testStarted name='test1'", fakeOutput.console.asCharString()); STRCMP_CONTAINS("##teamcity[testFinished name='test1'", fakeOutput.console.asCharString()); STRCMP_CONTAINS("##teamcity[testSuiteFinished name='group1'", fakeOutput.console.asCharString()); } class RunIgnoredUtest : public Utest { public: static bool Checker; void testBody() CPPUTEST_OVERRIDE { Checker = true; } }; bool RunIgnoredUtest::Checker = false; class RunIgnoredUtestShell : public IgnoredUtestShell { public: RunIgnoredUtestShell(const char* groupName, const char* testName, const char* fileName, size_t lineNumber) : IgnoredUtestShell(groupName, testName, fileName, lineNumber) {} virtual Utest* createTest() CPPUTEST_OVERRIDE { return new RunIgnoredUtest; } }; TEST_GROUP(RunIgnoredTest) { TestRegistry registry; RunIgnoredUtestShell *runIgnoredTest; DummyPluginWhichCountsThePlugins* pluginCountingPlugin; void setup() CPPUTEST_OVERRIDE { runIgnoredTest = new RunIgnoredUtestShell("group", "test", "file", 1); registry.addTest(runIgnoredTest); pluginCountingPlugin = new DummyPluginWhichCountsThePlugins("PluginCountingPlugin", &registry); } void teardown() CPPUTEST_OVERRIDE { delete pluginCountingPlugin; delete runIgnoredTest; RunIgnoredUtest::Checker = false; } }; TEST(RunIgnoredTest, IgnoreTestWillBeIgnoredIfNoOptionSpecified) { const char* argv[] = { "tests.exe" }; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(1, argv, &registry); commandLineTestRunner.runAllTestsMain(); CHECK_FALSE( RunIgnoredUtest::Checker ); } TEST(RunIgnoredTest, IgnoreTestWillGetRunIfOptionSpecified) { const char* argv[] = { "tests.exe", "-ri" }; CommandLineTestRunnerWithStringBufferOutput commandLineTestRunner(2, argv, &registry); commandLineTestRunner.runAllTestsMain(); CHECK_TRUE( RunIgnoredUtest::Checker ); }
null
6
cpp
cpputest
MemoryOperatorOverloadTest.cpp
tests/CppUTest/MemoryOperatorOverloadTest.cpp
null
#include "CppUTest/TestHarness.h" #include "CppUTest/TestMemoryAllocator.h" #include "CppUTest/MemoryLeakDetector.h" #include "CppUTest/TestOutput.h" #include "CppUTest/TestRegistry.h" #include "CppUTest/PlatformSpecificFunctions.h" #include "CppUTest/TestTestingFixture.h" #include "AllocationInCppFile.h" #include "CppUTest/TestHarness_c.h" #include "AllocationInCFile.h" TEST_GROUP(BasicBehavior) { }; TEST(BasicBehavior, CanDeleteNullPointers) { delete (char*) NULLPTR; delete [] (char*) NULLPTR; } #if CPPUTEST_USE_MEM_LEAK_DETECTION #if __cplusplus >= 201402L TEST(BasicBehavior, DeleteWithSizeParameterWorks) { char* charMemory = new char; char* charArrayMemory = new char[10]; ::operator delete(charMemory, sizeof(char)); ::operator delete[](charArrayMemory, sizeof(char)* 10); } #endif #endif #ifdef CPPUTEST_USE_MALLOC_MACROS /* This include is added because *sometimes* the cstdlib does an #undef. This should have been prevented */ #if CPPUTEST_USE_STD_CPP_LIB #include <cstdlib> #endif TEST(BasicBehavior, bothMallocAndFreeAreOverloaded) { void* memory = cpputest_malloc_location(sizeof(char), "file", 10); free(memory); memory = malloc(sizeof(unsigned char)); cpputest_free_location(memory, "file", 10); } #endif TEST_GROUP(MemoryLeakOverridesToBeUsedInProductionCode) { MemoryLeakDetector* memLeakDetector; void setup() CPPUTEST_OVERRIDE { memLeakDetector = MemoryLeakWarningPlugin::getGlobalDetector(); } }; #if CPPUTEST_USE_MEM_LEAK_DETECTION #ifdef CPPUTEST_USE_NEW_MACROS #undef new #endif TEST(MemoryLeakOverridesToBeUsedInProductionCode, newDeleteOverloadsWithIntLineWorks) { const int line = 42; char* leak = new("TestFile.cpp", line) char; size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); STRCMP_NOCASE_CONTAINS("Allocated at: TestFile.cpp and line: 42.", memLeakDetector->report(mem_leak_period_checking)); ::operator delete (leak, "TestFile.cpp", line); LONGS_EQUAL(memLeaks-1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); } TEST(MemoryLeakOverridesToBeUsedInProductionCode, newDeleteOverloadsWithSizeTLineWorks) { const size_t line = 42; char* leak = new("TestFile.cpp", line) char; size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); STRCMP_NOCASE_CONTAINS("Allocated at: TestFile.cpp and line: 42.", memLeakDetector->report(mem_leak_period_checking)); ::operator delete (leak, "TestFile.cpp", line); LONGS_EQUAL(memLeaks-1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); } TEST(MemoryLeakOverridesToBeUsedInProductionCode, newDeleteArrayOverloadsWithIntLineWorks) { const int line = 42; char* leak = new("TestFile.cpp", line) char[10]; size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); STRCMP_NOCASE_CONTAINS("Allocated at: TestFile.cpp and line: 42.", memLeakDetector->report(mem_leak_period_checking)); ::operator delete [] (leak, "TestFile.cpp", line); LONGS_EQUAL(memLeaks-1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); } TEST(MemoryLeakOverridesToBeUsedInProductionCode, newDeleteArrayOverloadsWithSizeTLineWorks) { const size_t line = 42; char* leak = new("TestFile.cpp", line) char[10]; size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); STRCMP_NOCASE_CONTAINS("Allocated at: TestFile.cpp and line: 42.", memLeakDetector->report(mem_leak_period_checking)); ::operator delete [] (leak, "TestFile.cpp", line); LONGS_EQUAL(memLeaks-1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); } #ifdef CPPUTEST_USE_NEW_MACROS #include "CppUTest/MemoryLeakDetectorNewMacros.h" // redefine the 'new' macro #endif #endif #ifdef CPPUTEST_USE_MALLOC_MACROS TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocOverrideIsUsed) { size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); void* memory = malloc(10); LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); free (memory); } #ifdef CPPUTEST_USE_STRDUP_MACROS TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrdupOverrideIsUsed) { size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); char* memory = strdup("0123456789"); LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); free (memory); } TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrndupOverrideIsUsed) { size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); char* memory = strndup("0123456789", 10); LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); free (memory); } #endif #endif TEST(MemoryLeakOverridesToBeUsedInProductionCode, UseNativeMallocByTemporarlySwitchingOffMalloc) { size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); #ifdef CPPUTEST_USE_MALLOC_MACROS #undef malloc #undef free #endif #if CPPUTEST_USE_STD_C_LIB void* memory = malloc(10); LONGS_EQUAL(memLeaks, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); free (memory); #else void* memory = PlatformSpecificMalloc(10); LONGS_EQUAL(memLeaks, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); PlatformSpecificFree (memory); #endif #ifdef CPPUTEST_USE_MALLOC_MACROS #include "CppUTest/MemoryLeakDetectorMallocMacros.h" #endif } /* TEST... allowing for a new overload in a class */ class NewDummyClass { public: static bool overloaded_new_called; #ifdef CPPUTEST_USE_NEW_MACROS #undef new #endif void* operator new (size_t size) #ifdef CPPUTEST_USE_NEW_MACROS #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif { overloaded_new_called = true; return malloc(size); } void dummyFunction() { char* memory = new char; delete memory; } }; bool NewDummyClass::overloaded_new_called = false; TEST(MemoryLeakOverridesToBeUsedInProductionCode, NoSideEffectsFromTurningOffNewMacros) { /* * Interesting effect of wrapping the operator new around the macro is * that the actual new that is called is a different one than expected. * * The overloaded operator new doesn't actually ever get called. * * This might come as a surprise, so it is important to realize! */ NewDummyClass dummy; dummy.dummyFunction(); // CHECK(dummy.overloaded_new_called); } TEST(MemoryLeakOverridesToBeUsedInProductionCode, UseNativeNewByTemporarlySwitchingOffNew) { #ifdef CPPUTEST_USE_NEW_MACROS #undef new #undef delete #endif char* memory = new char[10]; delete [] memory; #ifdef 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); } #ifdef CPPUTEST_USE_STRDUP_MACROS TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrdupOverrideWorks) { char* leak = strdupAllocation(); STRCMP_NOCASE_CONTAINS("AllocationInCFile.c", memLeakDetector->report(mem_leak_period_checking)); freeAllocation(leak); } TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrndupOverrideWorks) { char* leak = strndupAllocation(); STRCMP_NOCASE_CONTAINS("AllocationInCFile.c", memLeakDetector->report(mem_leak_period_checking)); freeAllocation(leak); } #endif TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocWithButFreeWithoutLeakDetectionDoesntCrash) { char* leak = mallocAllocation(); freeAllocationWithoutMacro(leak); LONGS_EQUAL(2, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); memLeakDetector->removeMemoryLeakInformationWithoutCheckingOrDeallocatingTheMemoryButDeallocatingTheAccountInformation(getCurrentMallocAllocator(), leak, true); } 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) { TestMemoryAllocator* no_memory_allocator; GlobalMemoryAllocatorStash memoryAllocatorStash; void setup() CPPUTEST_OVERRIDE { memoryAllocatorStash.save(); no_memory_allocator = new NullUnknownAllocator; setCurrentNewAllocator(no_memory_allocator); setCurrentNewArrayAllocator(no_memory_allocator); } void teardown() CPPUTEST_OVERRIDE { memoryAllocatorStash.restore(); delete no_memory_allocator; } }; #if CPPUTEST_USE_MEM_LEAK_DETECTION #if CPPUTEST_HAVE_EXCEPTIONS TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorThrowsAnExceptionWhenUsingStdCppNew) { CHECK_THROWS(CPPUTEST_BAD_ALLOC, new char); } TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorThrowsAnExceptionWhenUsingStdCppNew) { CHECK_THROWS(CPPUTEST_BAD_ALLOC, new char[10]); } TEST_GROUP(TestForExceptionsInConstructor) { }; TEST(TestForExceptionsInConstructor,ConstructorThrowsAnException) { CHECK_THROWS(int, new ClassThatThrowsAnExceptionInTheConstructor); } TEST(TestForExceptionsInConstructor,ConstructorThrowsAnExceptionAllocatedAsArray) { CHECK_THROWS(int, new ClassThatThrowsAnExceptionInTheConstructor[10]); } #else TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNull) { POINTERS_EQUAL(NULLPTR, new char); } TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNull) { POINTERS_EQUAL(NULLPTR, new char[10]); } #endif #undef new #if CPPUTEST_HAVE_EXCEPTIONS /* * CLang 4.2 and memory allocation. * * Clang 4.2 has done some optimizations to their memory management that actually causes slightly different behavior than what the C++ Standard defines. * Usually this is not a problem... but in this case, it is a problem. * * More information about the optimization can be found at: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3433.html * We've done a bug-report to clang to fix some of this non-standard behavior, which is open at: http://llvm.org/bugs/show_bug.cgi?id=15541 * * I very much hope that nobody would actually ever hit this bug/optimization as it is hard to figure out what is going on. * * The original test simply did "new char". Because the memory wasn't assigned to anything and is local in context, the optimization *doesn't* call * the operator new overload. Because it doesn't call the operator new (optimizing away a call to operator new), therefore the method wouldn't throw an exception * and therefore this test failed. * * The first attempt to fix this is to create a local variable and assigned the memory to that. Also this doesn't work as it still detects the allocation is * local and optimizes away the memory call. * * Now, we assign the memory on some static global which fools the optimizer to believe that it isn't local and it stops optimizing the operator new call. * * We (Bas Vodde and Terry Yin) suspect that in a real product, you wouldn't be able to detect the optimization and it's breaking of Standard C++. Therefore, * for now, we keep this hack in the test to fool the optimizer and hope nobody will ever notice this 'optimizer behavior' in a real product. * * Update 2020: The gcc compiler implemented the same optimization, but it seems to be slightly smarter and discovered that we assign to a static variable. * Thus it still optimized away the call to operator new. Did another bug report, but it is unlikely to get fixed. You can find it at: * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94671 * * Changed the variable to be external so it would definitively be a mistake to optimize the call. * */ extern char* some_memory; char* some_memory; TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorThrowsAnExceptionWhenUsingStdCppNewWithoutOverride) { CHECK_THROWS(CPPUTEST_BAD_ALLOC, some_memory = new char); } TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorThrowsAnExceptionWhenUsingStdCppNewWithoutOverride) { CHECK_THROWS(CPPUTEST_BAD_ALLOC, some_memory = new char[10]); } #if CPPUTEST_USE_STD_CPP_LIB TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNullWithoutOverride) { POINTERS_EQUAL(NULLPTR, new (std::nothrow) char); } TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNullWithoutOverride) { POINTERS_EQUAL(NULLPTR, new (std::nothrow) char[10]); } #endif #else TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNullWithoutOverride) { POINTERS_EQUAL(NULLPTR, new char); } TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNullWithoutOverride) { POINTERS_EQUAL(NULLPTR, new char[10]); } #endif #endif
null
7
cpp
cpputest
AllocLetTestFree.h
tests/CppUTest/AllocLetTestFree.h
null
#ifndef D_AllocLetTestFree_H #define D_AllocLetTestFree_H #ifdef __cplusplus extern "C" { #endif typedef struct AllocLetTestFreeStruct * AllocLetTestFree; AllocLetTestFree AllocLetTestFree_Create(void); void AllocLetTestFree_Destroy(AllocLetTestFree); #ifdef __cplusplus } #endif #endif /* D_FakeAllocLetTestFree_H */
null
8
cpp
cpputest
TeamCityOutputTest.cpp
tests/CppUTest/TeamCityOutputTest.cpp
null
#include "CppUTest/TestHarness.h" #include "CppUTest/TeamCityTestOutput.h" #include "CppUTest/PlatformSpecificFunctions.h" class TeamCityOutputToBuffer : public TeamCityTestOutput { public: explicit TeamCityOutputToBuffer() { } virtual ~TeamCityOutputToBuffer() CPPUTEST_DESTRUCTOR_OVERRIDE { } void printBuffer(const char* s) CPPUTEST_OVERRIDE { output += s; } void flush() CPPUTEST_OVERRIDE { output = ""; } const SimpleString& getOutput() { return output; } private: SimpleString output; }; static unsigned long millisTime; extern "C" { static unsigned long MockGetPlatformSpecificTimeInMillis() { return millisTime; } } TEST_GROUP(TeamCityOutputTest) { TeamCityTestOutput* tcout; TeamCityOutputToBuffer* mock; UtestShell* tst; TestFailure *f, *f2, *f3; TestResult* result; void setup() CPPUTEST_OVERRIDE { mock = new TeamCityOutputToBuffer(); tcout = mock; tst = new UtestShell("group", "test", "file", 10); f = new TestFailure(tst, "failfile", 20, "failure message"); f2 = new TestFailure(tst, "file", 20, "message"); f3 = new TestFailure(tst, "file", 30, "apos' pipe| [brackets]\r\nCRLF"); result = new TestResult(*mock); result->setTotalExecutionTime(10); millisTime = 0; UT_PTR_SET(GetPlatformSpecificTimeInMillis, MockGetPlatformSpecificTimeInMillis); } void teardown() CPPUTEST_OVERRIDE { delete tcout; delete tst; delete f; delete f2; delete f3; delete result; } }; TEST(TeamCityOutputTest, PrintGroupStarted) { result->currentGroupStarted(tst); STRCMP_EQUAL("##teamcity[testSuiteStarted name='group']\n", mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, PrintGroupStartedAndEnded) { const char* expected = "##teamcity[testSuiteStarted name='group']\n" "##teamcity[testSuiteFinished name='group']\n"; result->currentGroupStarted(tst); result->currentGroupEnded(tst); STRCMP_EQUAL(expected, mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, PrintGroupEndedButNotStarted) { result->currentGroupEnded(tst); STRCMP_EQUAL("", mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, PrintTestStarted) { tcout->printCurrentTestStarted(*tst); STRCMP_EQUAL("##teamcity[testStarted name='test']\n", mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, PrintTestStartedAndEnded) { result->currentTestStarted(tst); millisTime = 42; result->currentTestEnded(tst); STRCMP_EQUAL("##teamcity[testStarted name='test']\n##teamcity[testFinished name='test' duration='42']\n", mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, PrintTestEndedButNotStarted) { result->currentTestEnded(tst); STRCMP_EQUAL("", mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, PrintTestIgnored) { const char* expected = "##teamcity[testStarted name='test']\n" "##teamcity[testIgnored name='test']\n" "##teamcity[testFinished name='test' duration='41']\n"; IgnoredUtestShell* itst = new IgnoredUtestShell("group", "test", "file", 10); result->currentTestStarted(itst); millisTime = 41; result->currentTestEnded(itst); STRCMP_EQUAL(expected, mock->getOutput().asCharString()); delete itst; } TEST(TeamCityOutputTest, PrintWithFailureInSameFile) { tcout->printFailure(*f2); const char* expected = "##teamcity[testFailed name='test' message='file:20' " "details='message']\n"; STRCMP_EQUAL(expected, mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, PrintWithEscapedCharacters) { tcout->printFailure(*f3); const char* expected = "##teamcity[testFailed name='test' message='file:30' " "details='apos|' pipe|| |[brackets|]" "|r|nCRLF']\n"; STRCMP_EQUAL(expected, mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, PrintFailureWithFailInDifferentFile) { tcout->printFailure(*f); const char* expected = "##teamcity[testFailed name='test' message='TEST failed (file:10): failfile:20' " "details='failure message']\n"; STRCMP_EQUAL(expected, mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, TestGroupEscaped_Start) { tst->setGroupName("'[]\n\r"); result->currentGroupStarted(tst); const char* expected = "##teamcity[testSuiteStarted name='|'|[|]|n|r']\n"; STRCMP_EQUAL(expected, mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, TestGroupEscaped_End) { tst->setGroupName("'[]\n\r"); result->currentGroupStarted(tst); result->currentGroupEnded(tst); const char* expected = "##teamcity[testSuiteStarted name='|'|[|]|n|r']\n" "##teamcity[testSuiteFinished name='|'|[|]|n|r']\n"; STRCMP_EQUAL(expected, mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, TestNameEscaped_Start) { tst->setTestName("'[]\n\r"); result->currentTestStarted(tst); const char* expected = "##teamcity[testStarted name='|'|[|]|n|r']\n"; STRCMP_EQUAL(expected, mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, TestNameEscaped_End) { tst->setTestName("'[]\n\r"); result->currentTestStarted(tst); result->currentTestEnded(tst); const char* expected = "##teamcity[testStarted name='|'|[|]|n|r']\n" "##teamcity[testFinished name='|'|[|]|n|r' duration='0']\n"; STRCMP_EQUAL(expected, mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, TestNameEscaped_Ignore) { IgnoredUtestShell itst("group", "'[]\n\r", "file", 10); result->currentTestStarted(&itst); const char* expected = "##teamcity[testStarted name='|'|[|]|n|r']\n" "##teamcity[testIgnored name='|'|[|]|n|r']\n"; STRCMP_EQUAL(expected, mock->getOutput().asCharString()); } TEST(TeamCityOutputTest, TestNameEscaped_Fail) { tst->setTestName("'[]\n\r"); TestFailure fail(tst, "failfile", 20, "failure message"); tcout->printFailure(fail); const char* expected = "##teamcity[testFailed name='|'|[|]|n|r' message='TEST failed (file:10): failfile:20' " "details='failure message']\n"; STRCMP_EQUAL(expected, mock->getOutput().asCharString()); } /* Todo: * -Detect when running in TeamCity and switch output to -o teamcity automatically */
null
9
cpp
cpputest
CompatabilityTests.cpp
tests/CppUTest/CompatabilityTests.cpp
null
#include "CppUTest/TestHarness.h" #if CPPUTEST_USE_STD_CPP_LIB #include <memory> TEST_GROUP(StandardCppLibrary) { }; #if defined(__cplusplus) && __cplusplus >= 201402L TEST(StandardCppLibrary, UniquePtrConversationToBool) { auto const aNull = std::unique_ptr<int>(NULLPTR); CHECK_FALSE(aNull); auto const notNull = std::make_unique<int>(1); CHECK_TRUE(notNull); } #endif #endif
null
10
cpp
cpputest
JUnitOutputTest.cpp
tests/CppUTest/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" #include "CppUTest/SimpleString.h" class FileForJUnitOutputTests { SimpleString name_; bool isOpen_; SimpleString buffer_; FileForJUnitOutputTests* next_; SimpleStringCollection linesOfFile_; public: FileForJUnitOutputTests(const SimpleString& filename, FileForJUnitOutputTests* next) : name_(filename), isOpen_(true), next_(next) {} FileForJUnitOutputTests* nextFile() { return next_; } SimpleString name() { return name_; } void write(const SimpleString& buffer) { buffer_ += buffer; } void close() { isOpen_ = false; } const char* line(size_t lineNumber) { buffer_.split("\n", linesOfFile_); return linesOfFile_[lineNumber-1].asCharString(); } const char* lineFromTheBack(size_t lineNumberFromTheBack) { return line(amountOfLines() - (lineNumberFromTheBack - 1)); } size_t amountOfLines() { buffer_.split("\n", linesOfFile_); return linesOfFile_.size(); } SimpleString content() { return buffer_; } }; class FileSystemForJUnitTestOutputTests { FileForJUnitOutputTests* firstFile_; public: FileSystemForJUnitTestOutputTests() : firstFile_(NULLPTR) {} ~FileSystemForJUnitTestOutputTests() { clear(); } void clear(void) { while (firstFile_) { FileForJUnitOutputTests* fileToBeDeleted = firstFile_; firstFile_ = firstFile_->nextFile(); delete fileToBeDeleted; } } FileForJUnitOutputTests* openFile(const SimpleString& filename) { firstFile_ = new FileForJUnitOutputTests(filename, firstFile_); return firstFile_; } int amountOfFiles() { int totalAmountOfFiles = 0; for (FileForJUnitOutputTests* current = firstFile_; current != NULLPTR; current = current->nextFile()) totalAmountOfFiles++; return totalAmountOfFiles; } bool fileExists(const char* filename) { FileForJUnitOutputTests *searchedFile = file(filename); return (searchedFile != NULLPTR); } FileForJUnitOutputTests* file(const char* filename) { for (FileForJUnitOutputTests* current = firstFile_; current != NULLPTR; current = current->nextFile()) if (current->name() == filename) return current; return NULLPTR; } }; extern "C" { static unsigned long millisTime = 0; static const char* theTime = ""; static unsigned long MockGetPlatformSpecificTimeInMillis() { return millisTime; } static const char* MockGetPlatformSpecificTimeString() { return theTime; } } class JUnitTestOutputTestRunner { TestResult result_; const char* currentGroupName_; UtestShell* currentTest_; bool firstTestInGroup_; unsigned int timeTheTestTakes_; unsigned int numberOfChecksInTest_; TestFailure* testFailure_; public: explicit JUnitTestOutputTestRunner(const TestResult& result) : result_(result), currentGroupName_(NULLPTR), currentTest_(NULLPTR), firstTestInGroup_(true), timeTheTestTakes_(0), numberOfChecksInTest_(0), testFailure_(NULLPTR) { millisTime = 0; theTime = "1978-10-03T00:00:00"; UT_PTR_SET(GetPlatformSpecificTimeInMillis, MockGetPlatformSpecificTimeInMillis); UT_PTR_SET(GetPlatformSpecificTimeString, MockGetPlatformSpecificTimeString); } JUnitTestOutputTestRunner& start() { result_.testsStarted(); return *this; } JUnitTestOutputTestRunner& end() { endOfPreviousTestGroup(); delete currentTest_; result_.testsEnded(); return *this; } JUnitTestOutputTestRunner& endGroupAndClearTest() { endOfPreviousTestGroup(); delete currentTest_; currentTest_ = NULLPTR; return *this; } void endOfPreviousTestGroup() { runPreviousTest(); if (currentTest_) { result_.currentGroupEnded(currentTest_); firstTestInGroup_ = true; } currentGroupName_ = NULLPTR; } JUnitTestOutputTestRunner& withGroup(const char* groupName) { runPreviousTest(); endOfPreviousTestGroup(); currentGroupName_ = groupName; return *this; } JUnitTestOutputTestRunner& withTest(const char* testName) { runPreviousTest(); delete currentTest_; currentTest_ = new UtestShell(currentGroupName_, testName, "file", 1); return *this; } JUnitTestOutputTestRunner& withIgnoredTest(const char* testName) { runPreviousTest(); delete currentTest_; currentTest_ = new IgnoredUtestShell(currentGroupName_, testName, "file", 1); return *this; } JUnitTestOutputTestRunner& inFile(const char* fileName) { if(currentTest_) { currentTest_->setFileName(fileName); } return *this; } JUnitTestOutputTestRunner& onLine(size_t lineNumber) { if(currentTest_) { currentTest_->setLineNumber(lineNumber); } return *this; } void runPreviousTest() { if (currentTest_ == NULLPTR) return; if (firstTestInGroup_) { result_.currentGroupStarted(currentTest_); firstTestInGroup_ = false; } result_.currentTestStarted(currentTest_); millisTime += timeTheTestTakes_; for(unsigned int i = 0; i < numberOfChecksInTest_; i++) { result_.countCheck(); } numberOfChecksInTest_ = 0; if (testFailure_) { result_.addFailure(*testFailure_); delete testFailure_; testFailure_ = NULLPTR; } result_.currentTestEnded(currentTest_); } JUnitTestOutputTestRunner& thatHasChecks(unsigned int numOfChecks) { numberOfChecksInTest_ = numOfChecks; return *this; } JUnitTestOutputTestRunner& thatTakes(unsigned int timeElapsed) { timeTheTestTakes_ = timeElapsed; return *this; } JUnitTestOutputTestRunner& seconds() { return *this; } JUnitTestOutputTestRunner& thatFails(const char* message, const char* file, size_t line) { testFailure_ = new TestFailure( currentTest_, file, line, message); return *this; } JUnitTestOutputTestRunner& atTime(const char* newTime) { theTime = newTime; return *this; } JUnitTestOutputTestRunner& thatPrints(const char* output) { runPreviousTest(); result_.print(output); return *this; } }; extern "C" { static FileSystemForJUnitTestOutputTests fileSystem; static FileForJUnitOutputTests* currentFile = NULLPTR; static PlatformSpecificFile mockFOpen(const char* filename, const char*) { currentFile = fileSystem.openFile(filename); return currentFile; } static void (*originalFPuts)(const char* str, PlatformSpecificFile file); static void mockFPuts(const char* str, PlatformSpecificFile file) { if (file == currentFile) { ((FileForJUnitOutputTests*)file)->write(str); } else { originalFPuts(str, file); } } static void mockFClose(PlatformSpecificFile file) { currentFile = NULLPTR; ((FileForJUnitOutputTests*)file)->close(); } } TEST_GROUP(JUnitOutputTest) { JUnitTestOutput *junitOutput; TestResult *result; JUnitTestOutputTestRunner *testCaseRunner; FileForJUnitOutputTests* outputFile; void setup() CPPUTEST_OVERRIDE { UT_PTR_SET(PlatformSpecificFOpen, mockFOpen); originalFPuts = PlatformSpecificFPuts; UT_PTR_SET(PlatformSpecificFPuts, mockFPuts); UT_PTR_SET(PlatformSpecificFClose, mockFClose); junitOutput = new JUnitTestOutput(); result = new TestResult(*junitOutput); testCaseRunner = new JUnitTestOutputTestRunner(*result); } void teardown() CPPUTEST_OVERRIDE { delete testCaseRunner; delete result; delete junitOutput; fileSystem.clear(); } }; TEST(JUnitOutputTest, withOneTestGroupAndOneTestOnlyWriteToOneFile) { testCaseRunner->start() .withGroup("groupname").withTest("testname") .end(); LONGS_EQUAL(1, fileSystem.amountOfFiles()); CHECK(fileSystem.fileExists("cpputest_groupname.xml")); } TEST(JUnitOutputTest, withReservedCharactersInPackageOrTestGroupUsesUnderscoresForFileName) { junitOutput->setPackageName("p/a\\c?k%a*g:e|n\"a<m>e."); testCaseRunner->start() .withGroup("g/r\\o?u%p*n:a|m\"e<h>ere").withTest("testname") .end(); CHECK(fileSystem.fileExists("cpputest_p_a_c_k_a_g_e_n_a_m_e._g_r_o_u_p_n_a_m_e_h_ere.xml")); } TEST(JUnitOutputTest, withOneTestGroupAndOneTestOutputsValidXMLFiles) { testCaseRunner->start() .withGroup("groupname").withTest("testname") .end(); outputFile = fileSystem.file("cpputest_groupname.xml"); STRCMP_EQUAL("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n", outputFile->line(1)); } TEST(JUnitOutputTest, withOneTestGroupAndOneTestOutputsTestSuiteStartAndEndBlocks) { testCaseRunner->start() .withGroup("groupname").withTest("testname") .end(); outputFile = fileSystem.file("cpputest_groupname.xml"); STRCMP_EQUAL("<testsuite errors=\"0\" failures=\"0\" hostname=\"localhost\" name=\"groupname\" tests=\"1\" time=\"0.000\" timestamp=\"1978-10-03T00:00:00\">\n", outputFile->line(2)); STRCMP_EQUAL("</testsuite>\n", outputFile->lineFromTheBack(1)); } TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainAnEmptyPropertiesBlock) { testCaseRunner->start() .withGroup("groupname").withTest("testname") .end(); outputFile = fileSystem.file("cpputest_groupname.xml"); STRCMP_EQUAL("<properties>\n", outputFile->line(3)); STRCMP_EQUAL("</properties>\n", outputFile->line(4)); } TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainAnEmptyStdoutBlock) { testCaseRunner->start() .withGroup("groupname").withTest("testname") .end(); outputFile = fileSystem.file("cpputest_groupname.xml"); STRCMP_EQUAL("<system-out></system-out>\n", outputFile->lineFromTheBack(3)); } TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainAnEmptyStderrBlock) { testCaseRunner->start() .withGroup("groupname").withTest("testname") .end(); outputFile = fileSystem.file("cpputest_groupname.xml"); STRCMP_EQUAL("<system-err></system-err>\n", outputFile->lineFromTheBack(2)); } TEST(JUnitOutputTest, withOneTestGroupAndOneTestFileShouldContainsATestCaseBlock) { testCaseRunner->start() .withGroup("groupname").withTest("testname") .end(); outputFile = fileSystem.file("cpputest_groupname.xml"); STRCMP_EQUAL("<testcase classname=\"groupname\" name=\"testname\" assertions=\"0\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(5)); STRCMP_EQUAL("</testcase>\n", outputFile->line(6)); } TEST(JUnitOutputTest, withOneTestGroupAndTwoTestCasesCreateCorrectTestgroupBlockAndCorrectTestCaseBlock) { testCaseRunner->start() .withGroup("twoTestsGroup").withTest("firstTestName").withTest("secondTestName") .end(); outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); STRCMP_EQUAL("<testsuite errors=\"0\" failures=\"0\" hostname=\"localhost\" name=\"twoTestsGroup\" tests=\"2\" time=\"0.000\" timestamp=\"1978-10-03T00:00:00\">\n", outputFile->line(2)); STRCMP_EQUAL("<testcase classname=\"twoTestsGroup\" name=\"firstTestName\" assertions=\"0\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(5)); STRCMP_EQUAL("</testcase>\n", outputFile->line(6)); STRCMP_EQUAL("<testcase classname=\"twoTestsGroup\" name=\"secondTestName\" assertions=\"0\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(7)); STRCMP_EQUAL("</testcase>\n", outputFile->line(8)); } TEST(JUnitOutputTest, withOneTestGroupAndTimeHasElapsedAndTimestampChanged) { testCaseRunner->start().atTime("2013-07-04T22:28:00") .withGroup("timeGroup").withTest("Dummy").thatTakes(10).seconds() .end(); outputFile = fileSystem.file("cpputest_timeGroup.xml"); STRCMP_EQUAL("<testsuite errors=\"0\" failures=\"0\" hostname=\"localhost\" name=\"timeGroup\" tests=\"1\" time=\"0.010\" timestamp=\"2013-07-04T22:28:00\">\n", outputFile->line(2)); } TEST(JUnitOutputTest, withOneTestGroupAndMultipleTestCasesWithElapsedTime) { testCaseRunner->start() .withGroup("twoTestsGroup") .withTest("firstTestName").thatTakes(10).seconds() .withTest("secondTestName").thatTakes(50).seconds() .end(); outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); STRCMP_EQUAL("<testsuite errors=\"0\" failures=\"0\" hostname=\"localhost\" name=\"twoTestsGroup\" tests=\"2\" time=\"0.060\" timestamp=\"1978-10-03T00:00:00\">\n", outputFile->line(2)); STRCMP_EQUAL("<testcase classname=\"twoTestsGroup\" name=\"firstTestName\" assertions=\"0\" time=\"0.010\" file=\"file\" line=\"1\">\n", outputFile->line(5)); STRCMP_EQUAL("</testcase>\n", outputFile->line(6)); STRCMP_EQUAL("<testcase classname=\"twoTestsGroup\" name=\"secondTestName\" assertions=\"0\" time=\"0.050\" file=\"file\" line=\"1\">\n", outputFile->line(7)); STRCMP_EQUAL("</testcase>\n", outputFile->line(8)); } TEST(JUnitOutputTest, withOneTestGroupAndOneFailingTest) { testCaseRunner->start() .withGroup("testGroupWithFailingTest") .withTest("FailingTestName").thatFails("Test failed", "thisfile", 10) .end(); outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); STRCMP_EQUAL("<testsuite errors=\"0\" failures=\"1\" hostname=\"localhost\" name=\"testGroupWithFailingTest\" tests=\"1\" time=\"0.000\" timestamp=\"1978-10-03T00:00:00\">\n", outputFile->line(2)); STRCMP_EQUAL("<testcase classname=\"testGroupWithFailingTest\" name=\"FailingTestName\" assertions=\"0\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(5)); STRCMP_EQUAL("<failure message=\"thisfile:10: Test failed\" type=\"AssertionFailedError\">\n", outputFile->line(6)); STRCMP_EQUAL("</failure>\n", outputFile->line(7)); STRCMP_EQUAL("</testcase>\n", outputFile->line(8)); } TEST(JUnitOutputTest, withTwoTestGroupAndOneFailingTest) { testCaseRunner->start() .withGroup("testGroupWithFailingTest") .withTest("FirstTest") .withTest("FailingTestName").thatFails("Test failed", "thisfile", 10) .end(); outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); STRCMP_EQUAL("<testsuite errors=\"0\" failures=\"1\" hostname=\"localhost\" name=\"testGroupWithFailingTest\" tests=\"2\" time=\"0.000\" timestamp=\"1978-10-03T00:00:00\">\n", outputFile->line(2)); STRCMP_EQUAL("<testcase classname=\"testGroupWithFailingTest\" name=\"FailingTestName\" assertions=\"0\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(7)); STRCMP_EQUAL("<failure message=\"thisfile:10: Test failed\" type=\"AssertionFailedError\">\n", outputFile->line(8)); } TEST(JUnitOutputTest, testFailureWithLessThanAndGreaterThanInsideIt) { testCaseRunner->start() .withGroup("testGroupWithFailingTest") .withTest("FailingTestName").thatFails("Test <failed>", "thisfile", 10) .end(); outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); STRCMP_EQUAL("<failure message=\"thisfile:10: Test &lt;failed&gt;\" type=\"AssertionFailedError\">\n", outputFile->line(6)); } TEST(JUnitOutputTest, testFailureWithQuotesInIt) { testCaseRunner->start() .withGroup("testGroupWithFailingTest") .withTest("FailingTestName").thatFails("Test \"failed\"", "thisfile", 10) .end(); outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); STRCMP_EQUAL("<failure message=\"thisfile:10: Test &quot;failed&quot;\" type=\"AssertionFailedError\">\n", outputFile->line(6)); } TEST(JUnitOutputTest, testFailureWithNewlineInIt) { testCaseRunner->start() .withGroup("testGroupWithFailingTest") .withTest("FailingTestName").thatFails("Test \nfailed", "thisfile", 10) .end(); outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); STRCMP_EQUAL("<failure message=\"thisfile:10: Test &#10;failed\" type=\"AssertionFailedError\">\n", outputFile->line(6)); } TEST(JUnitOutputTest, testFailureWithDifferentFileAndLine) { testCaseRunner->start() .withGroup("testGroupWithFailingTest") .withTest("FailingTestName").thatFails("Test failed", "importantFile", 999) .end(); outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); STRCMP_EQUAL("<failure message=\"importantFile:999: Test failed\" type=\"AssertionFailedError\">\n", outputFile->line(6)); } TEST(JUnitOutputTest, testFailureWithAmpersandsAndLessThan) { testCaseRunner->start() .withGroup("testGroupWithFailingTest") .withTest("FailingTestName").thatFails("&object1 < &object2", "importantFile", 999) .end(); outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); STRCMP_EQUAL("<failure message=\"importantFile:999: &amp;object1 &lt; &amp;object2\" type=\"AssertionFailedError\">\n", outputFile->line(6)); } TEST(JUnitOutputTest, testFailureWithAmpersands) { testCaseRunner->start() .withGroup("testGroupWithFailingTest") .withTest("FailingTestName").thatFails("&object1 != &object2", "importantFile", 999) .end(); outputFile = fileSystem.file("cpputest_testGroupWithFailingTest.xml"); STRCMP_EQUAL("<failure message=\"importantFile:999: &amp;object1 != &amp;object2\" type=\"AssertionFailedError\">\n", outputFile->line(6)); } TEST(JUnitOutputTest, aCoupleOfTestFailures) { testCaseRunner->start() .withGroup("testGroup") .withTest("passingOne") .withTest("FailingTest").thatFails("Failure", "file", 99) .withTest("passingTwo") .withTest("passingThree") .withTest("AnotherFailingTest").thatFails("otherFailure", "anotherFile", 10) .end(); outputFile = fileSystem.file("cpputest_testGroup.xml"); STRCMP_EQUAL("<failure message=\"file:99: Failure\" type=\"AssertionFailedError\">\n", outputFile->line(8)); STRCMP_EQUAL("<failure message=\"anotherFile:10: otherFailure\" type=\"AssertionFailedError\">\n", outputFile->line(16)); } TEST(JUnitOutputTest, testFailuresInSeparateGroups) { testCaseRunner->start() .withGroup("testGroup") .withTest("passingOne") .withTest("FailingTest").thatFails("Failure", "file", 99) .withGroup("AnotherGroup") .withTest("AnotherFailingTest").thatFails("otherFailure", "anotherFile", 10) .end(); outputFile = fileSystem.file("cpputest_testGroup.xml"); STRCMP_EQUAL("<failure message=\"file:99: Failure\" type=\"AssertionFailedError\">\n", outputFile->line(8)); outputFile = fileSystem.file("cpputest_AnotherGroup.xml"); STRCMP_EQUAL("<failure message=\"anotherFile:10: otherFailure\" type=\"AssertionFailedError\">\n", outputFile->line(8)); } TEST(JUnitOutputTest, twoTestGroupsWriteToTwoDifferentFiles) { testCaseRunner->start() .withGroup("firstTestGroup") .withTest("testName") .withGroup("secondTestGroup") .withTest("testName") .end(); CHECK(fileSystem.file("cpputest_firstTestGroup.xml") != NULLPTR); CHECK(fileSystem.file("cpputest_secondTestGroup.xml") != NULLPTR); } TEST(JUnitOutputTest, testGroupWithWeirdName) { STRCMP_EQUAL("cpputest_group_weird_name.xml", junitOutput->createFileName("group/weird/name").asCharString()); } TEST(JUnitOutputTest, TestCaseBlockWithAPackageName) { junitOutput->setPackageName("packagename"); testCaseRunner->start() .withGroup("groupname").withTest("testname") .end(); outputFile = fileSystem.file("cpputest_packagename_groupname.xml"); STRCMP_EQUAL("<testcase classname=\"packagename.groupname\" name=\"testname\" assertions=\"0\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(5)); STRCMP_EQUAL("</testcase>\n", outputFile->line(6)); } TEST(JUnitOutputTest, TestCaseBlockForIgnoredTest) { junitOutput->setPackageName("packagename"); testCaseRunner->start() .withGroup("groupname").withIgnoredTest("testname") .end(); outputFile = fileSystem.file("cpputest_packagename_groupname.xml"); STRCMP_EQUAL("<testcase classname=\"packagename.groupname\" name=\"testname\" assertions=\"0\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(5)); STRCMP_EQUAL("<skipped />\n", outputFile->line(6)); STRCMP_EQUAL("</testcase>\n", outputFile->line(7)); } TEST(JUnitOutputTest, TestCaseWithTestLocation) { junitOutput->setPackageName("packagename"); testCaseRunner->start() .withGroup("groupname") .withTest("testname").inFile("MySource.c").onLine(159) .end(); outputFile = fileSystem.file("cpputest_packagename_groupname.xml"); STRCMP_EQUAL("<testcase classname=\"packagename.groupname\" name=\"testname\" assertions=\"0\" time=\"0.000\" file=\"MySource.c\" line=\"159\">\n", outputFile->line(5)); } TEST(JUnitOutputTest, MultipleTestCaseWithTestLocations) { testCaseRunner->start() .withGroup("twoTestsGroup") .withTest("firstTestName").inFile("MyFirstSource.c").onLine(846) .withTest("secondTestName").inFile("MySecondSource.c").onLine(513) .end(); outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); STRCMP_EQUAL("<testcase classname=\"twoTestsGroup\" name=\"firstTestName\" assertions=\"0\" time=\"0.000\" file=\"MyFirstSource.c\" line=\"846\">\n", outputFile->line(5)); STRCMP_EQUAL("<testcase classname=\"twoTestsGroup\" name=\"secondTestName\" assertions=\"0\" time=\"0.000\" file=\"MySecondSource.c\" line=\"513\">\n", outputFile->line(7)); } TEST(JUnitOutputTest, TestCaseBlockWithAssertions) { junitOutput->setPackageName("packagename"); testCaseRunner->start() .withGroup("groupname") .withTest("testname") .thatHasChecks(24) .end(); outputFile = fileSystem.file("cpputest_packagename_groupname.xml"); STRCMP_EQUAL("<testcase classname=\"packagename.groupname\" name=\"testname\" assertions=\"24\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(5)); } TEST(JUnitOutputTest, MultipleTestCaseBlocksWithAssertions) { testCaseRunner->start() .withGroup("twoTestsGroup") .withTest("firstTestName").thatHasChecks(456) .withTest("secondTestName").thatHasChecks(567) .end(); outputFile = fileSystem.file("cpputest_twoTestsGroup.xml"); STRCMP_EQUAL("<testcase classname=\"twoTestsGroup\" name=\"firstTestName\" assertions=\"456\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(5)); STRCMP_EQUAL("<testcase classname=\"twoTestsGroup\" name=\"secondTestName\" assertions=\"567\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(7)); } TEST(JUnitOutputTest, MultipleTestCasesInDifferentGroupsWithAssertions) { testCaseRunner->start() .withGroup("groupOne") .withTest("testA").thatHasChecks(456) .endGroupAndClearTest() .withGroup("groupTwo") .withTest("testB").thatHasChecks(678) .end(); outputFile = fileSystem.file("cpputest_groupOne.xml"); STRCMP_EQUAL("<testcase classname=\"groupOne\" name=\"testA\" assertions=\"456\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(5)); outputFile = fileSystem.file("cpputest_groupTwo.xml"); STRCMP_EQUAL("<testcase classname=\"groupTwo\" name=\"testB\" assertions=\"678\" time=\"0.000\" file=\"file\" line=\"1\">\n", outputFile->line(5)); } TEST(JUnitOutputTest, UTPRINTOutputInJUnitOutput) { testCaseRunner->start() .withGroup("groupname") .withTest("testname").thatPrints("someoutput") .end(); outputFile = fileSystem.file("cpputest_groupname.xml"); STRCMP_EQUAL("<system-out>someoutput</system-out>\n", outputFile->lineFromTheBack(3)); } TEST(JUnitOutputTest, UTPRINTOutputInJUnitOutputWithSpecials) { testCaseRunner->start() .withGroup("groupname") .withTest("testname").thatPrints("The <rain> in \"Spain\"\nGoes\r \\mainly\\ down the Dr&in\n") .end(); outputFile = fileSystem.file("cpputest_groupname.xml"); STRCMP_EQUAL("<system-out>The &lt;rain&gt; in &quot;Spain&quot;&#10;Goes&#13; \\mainly\\ down the Dr&amp;in&#10;</system-out>\n", outputFile->lineFromTheBack(3)); }
null
11
cpp
cpputest
MemoryLeakDetectorTest.cpp
tests/CppUTest/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/TestMemoryAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" class MemoryLeakFailureForTest: public MemoryLeakFailure { public: virtual ~MemoryLeakFailureForTest() CPPUTEST_DESTRUCTOR_OVERRIDE { } virtual void fail(char* fail_string) CPPUTEST_OVERRIDE { *message = fail_string; } SimpleString *message; }; class NewAllocatorForMemoryLeakDetectionTest: public TestMemoryAllocator { public: NewAllocatorForMemoryLeakDetectionTest() : TestMemoryAllocator("Standard New Allocator", "new", "delete"), alloc_called(0), free_called(0) { } int alloc_called; int free_called; char* alloc_memory(size_t size, const char*, size_t) CPPUTEST_OVERRIDE { alloc_called++; return TestMemoryAllocator::alloc_memory(size, "file", 1); } void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE { free_called++; TestMemoryAllocator::free_memory(memory, size, file, line); } }; class AllocatorForMemoryLeakDetectionTest: public TestMemoryAllocator { public: AllocatorForMemoryLeakDetectionTest() : alloc_called(0), free_called(0), allocMemoryLeakNodeCalled(0), freeMemoryLeakNodeCalled(0) { } int alloc_called; int free_called; int allocMemoryLeakNodeCalled; int freeMemoryLeakNodeCalled; char* alloc_memory(size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE { alloc_called++; return TestMemoryAllocator::alloc_memory(size, file, line); } void free_memory(char* memory, size_t size, const char* file, size_t line) CPPUTEST_OVERRIDE { free_called++; TestMemoryAllocator::free_memory(memory, size, file, line); } char* allocMemoryLeakNode(size_t size) CPPUTEST_OVERRIDE { allocMemoryLeakNodeCalled++; return TestMemoryAllocator::alloc_memory(size, __FILE__, __LINE__); } void freeMemoryLeakNode(char* memory) CPPUTEST_OVERRIDE { freeMemoryLeakNodeCalled++; TestMemoryAllocator::free_memory(memory, 0, __FILE__, __LINE__); } }; TEST_GROUP(MemoryLeakDetectorTest) { MemoryLeakDetector* detector; MemoryLeakFailureForTest *reporter; AllocatorForMemoryLeakDetectionTest* testAllocator; void setup() CPPUTEST_OVERRIDE { reporter = new MemoryLeakFailureForTest; detector = new MemoryLeakDetector(reporter); testAllocator = new AllocatorForMemoryLeakDetectionTest; detector->enable(); detector->startChecking(); reporter->message = new SimpleString(); } void teardown() CPPUTEST_OVERRIDE { delete reporter->message; delete detector; delete reporter; delete testAllocator; } }; TEST(MemoryLeakDetectorTest, OneLeak) { char* mem = detector->allocMemory(testAllocator, 3); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); STRCMP_CONTAINS("Memory leak(s) found", output.asCharString()); STRCMP_CONTAINS("size: 3", output.asCharString()); STRCMP_CONTAINS("alloc", output.asCharString()); STRCMP_CONTAINS(StringFromFormat("%p", (void*) mem).asCharString(), output.asCharString()); STRCMP_CONTAINS("Total number of leaks", output.asCharString()); PlatformSpecificFree(mem); LONGS_EQUAL(1, testAllocator->alloc_called); LONGS_EQUAL(0, testAllocator->free_called); } TEST(MemoryLeakDetectorTest, sequenceNumbersOfMemoryLeaks) { char* mem = detector->allocMemory(defaultNewAllocator(), 1); char* mem2 = detector->allocMemory(defaultNewAllocator(), 2); char* mem3 = detector->allocMemory(defaultNewAllocator(), 3); SimpleString output = detector->report(mem_leak_period_checking); STRCMP_CONTAINS("Alloc num (1)", output.asCharString()); STRCMP_CONTAINS("Alloc num (2)", output.asCharString()); STRCMP_CONTAINS("Alloc num (3)", output.asCharString()); PlatformSpecificFree(mem); PlatformSpecificFree(mem2); PlatformSpecificFree(mem3); } TEST(MemoryLeakDetectorTest, memoryDumpOutput) { char* mem = detector->allocMemory(defaultNewAllocator(), 6); SimpleString::StrNCpy(mem, "test1", 6); SimpleString output = detector->report(mem_leak_period_checking); STRCMP_CONTAINS("Alloc num (1)", output.asCharString()); STRCMP_CONTAINS("Leak size: 6 Allocated at", output.asCharString()); STRCMP_CONTAINS("Content:", output.asCharString()); STRCMP_CONTAINS("0000: 74 65 73 74 31 00 |test1.|", output.asCharString()); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, OneHundredLeaks) { const int amount_alloc = 100; char *mem[amount_alloc]; for (int i = 0; i < amount_alloc; i++) mem[i] = detector->allocMemory(defaultMallocAllocator(), 3); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); STRCMP_CONTAINS("Memory leak(s) found", output.asCharString()); STRCMP_CONTAINS("Total number of leaks", output.asCharString()); STRCMP_CONTAINS("Memory leak reports about malloc and free", output.asCharString()); //don't reuse i for vc6 compatibility for (int j = 0; j < amount_alloc; j++) PlatformSpecificFree(mem[j]); } TEST(MemoryLeakDetectorTest, OneLeakOutsideCheckingPeriod) { detector->stopChecking(); char* mem = detector->allocMemory(defaultNewAllocator(), 4); SimpleString output = detector->report(mem_leak_period_all); CHECK(output.contains("Memory leak(s) found")); CHECK(output.contains("size: 4")); CHECK(output.contains("new")); CHECK(output.contains("Total number of leaks")); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, NoLeaksWhatsoever) { detector->stopChecking(); STRCMP_CONTAINS("No memory leaks", detector->report(mem_leak_period_checking)); STRCMP_CONTAINS("No memory leaks", detector->report(mem_leak_period_all)); } TEST(MemoryLeakDetectorTest, TwoLeaksUsingOperatorNew) { char* mem = detector->allocMemory(defaultNewAllocator(), 4); char* mem2 = detector->allocMemory(defaultNewAllocator(), 8); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); CHECK(output.contains("size: 8")); CHECK(output.contains("size: 4")); PlatformSpecificFree(mem); PlatformSpecificFree(mem2); } TEST(MemoryLeakDetectorTest, OneAllocButNoLeak) { char* mem = detector->allocMemory(testAllocator, 4); detector->deallocMemory(testAllocator, mem); detector->stopChecking(); STRCMP_CONTAINS("No memory leaks", detector->report(mem_leak_period_checking)); LONGS_EQUAL(1, testAllocator->alloc_called); LONGS_EQUAL(1, testAllocator->free_called); } TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeak) { char* mem = detector->allocMemory(testAllocator, 4); char* mem2 = detector->allocMemory(testAllocator, 12); detector->deallocMemory(testAllocator, mem); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); CHECK(output.contains("Leak size: 12")); CHECK(!output.contains("Leak size: 4")); PlatformSpecificFree(mem2); LONGS_EQUAL(2, testAllocator->alloc_called); LONGS_EQUAL(1, testAllocator->free_called); } TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeakReverseOrder) { char* mem = detector->allocMemory(defaultNewAllocator(), 4); char* mem2 = detector->allocMemory(defaultNewAllocator(), 12); detector->deallocMemory(defaultNewAllocator(), mem2); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); CHECK(!output.contains("size: 12")); CHECK(output.contains("size: 4")); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, DeleteNonAlocatedMemory) { char a; char* pa = &a; detector->deallocMemory(defaultMallocAllocator(), pa, "FREE.c", 100); detector->stopChecking(); CHECK(reporter->message->contains("Deallocating non-allocated memory")); CHECK(reporter->message->contains(" allocated at file: <unknown> line: 0 size: 0 type: unknown")); CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free")); } TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriod) { detector->stopChecking(); char* mem = detector->allocMemory(defaultNewAllocator(), 4); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); detector->deallocMemory(defaultNewAllocator(), mem); } TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriodComplicatedCase) { char* mem = detector->allocMemory(defaultNewAllocator(), 4); detector->stopChecking(); char* mem2 = detector->allocMemory(defaultNewAllocator(), 8); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->clearAllAccounting(mem_leak_period_checking); PlatformSpecificFree(mem); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); detector->startChecking(); char* mem3 = detector->allocMemory(defaultNewAllocator(), 4); detector->stopChecking(); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); detector->clearAllAccounting(mem_leak_period_checking); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); detector->clearAllAccounting(mem_leak_period_all); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); PlatformSpecificFree(mem2); PlatformSpecificFree(mem3); } TEST(MemoryLeakDetectorTest, OneLeakUsingOperatorNewWithFileLine) { char* mem = detector->allocMemory(defaultNewAllocator(), 4, "file.cpp", 1234); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("file.cpp")); CHECK(output.contains("1234")); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, OneAllocAndFreeUsingArrayNew) { char* mem = detector->allocMemory(defaultNewArrayAllocator(), 10, "file.cpp", 1234); char* mem2 = detector->allocMemory(defaultNewArrayAllocator(), 12); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("new []")); detector->deallocMemory(defaultNewArrayAllocator(), mem); detector->deallocMemory(defaultNewArrayAllocator(), mem2); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); detector->stopChecking(); } TEST(MemoryLeakDetectorTest, OneAllocAndFree) { char* mem = detector->allocMemory(defaultMallocAllocator(), 10, "file.cpp", 1234); char* mem2 = detector->allocMemory(defaultMallocAllocator(), 12); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("malloc")); detector->deallocMemory(defaultMallocAllocator(), mem); detector->deallocMemory(defaultMallocAllocator(), mem2, "file.c", 5678); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); detector->stopChecking(); } TEST(MemoryLeakDetectorTest, OneRealloc) { char* mem1 = detector->allocMemory(testAllocator, 10, "file.cpp", 1234, true); char* mem2 = detector->reallocMemory(testAllocator, mem1, 1000, "other.cpp", 5678, true); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("other.cpp")); detector->deallocMemory(testAllocator, mem2, true); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); detector->stopChecking(); LONGS_EQUAL(1, testAllocator->alloc_called); LONGS_EQUAL(1, testAllocator->free_called); LONGS_EQUAL(2, testAllocator->allocMemoryLeakNodeCalled); LONGS_EQUAL(2, testAllocator->freeMemoryLeakNodeCalled); } TEST(MemoryLeakDetectorTest, ReallocNonAllocatedMemory) { char mem1; char* mem2 = detector->reallocMemory(testAllocator, &mem1, 5, "other.cpp", 13, true); detector->deallocMemory(testAllocator, mem2, true); detector->stopChecking(); CHECK(reporter->message->contains("Deallocating non-allocated memory\n")); CHECK(reporter->message->contains(" deallocated at file: other.cpp line: 13")); } TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherType) { char* mem = detector->allocMemory(defaultNewArrayAllocator(), 100, "ALLOC.c", 10); detector->deallocMemory(defaultMallocAllocator(), mem, "FREE.c", 100); detector->stopChecking(); CHECK(reporter->message->contains("Allocation/deallocation type mismatch")); CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 100 type: new []")); CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free")); } TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherTypeWithCheckingDisabled) { detector->disableAllocationTypeChecking(); char* mem = detector->allocMemory(defaultNewArrayAllocator(), 100, "ALLOC.c", 10); detector->deallocMemory(defaultNewAllocator(), mem, "FREE.c", 100); detector->stopChecking(); STRCMP_EQUAL("", reporter->message->asCharString()); detector->enableAllocationTypeChecking(); } TEST(MemoryLeakDetectorTest, mallocLeakGivesAdditionalWarning) { char* mem = detector->allocMemory(defaultMallocAllocator(), 100, "ALLOC.c", 10); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); STRCMP_CONTAINS("Memory leak reports about malloc and free can be caused by allocating using the cpputest version of malloc", output.asCharString()); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, newLeakDoesNotGiveAdditionalWarning) { char* mem = detector->allocMemory(defaultNewAllocator(), 100, "ALLOC.c", 10); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); CHECK(! output.contains("Memory leak reports about malloc and free")); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, MarkCheckingPeriodLeaksAsNonCheckingPeriod) { char* mem = detector->allocMemory(defaultNewArrayAllocator(), 100); char* mem2 = detector->allocMemory(defaultNewArrayAllocator(), 100); detector->stopChecking(); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); detector->markCheckingPeriodLeaksAsNonCheckingPeriod(); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); PlatformSpecificFree(mem); PlatformSpecificFree(mem2); } TEST(MemoryLeakDetectorTest, memoryCorruption) { char* mem = detector->allocMemory(defaultMallocAllocator(), 10, "ALLOC.c", 10); mem[10] = 'O'; mem[11] = 'H'; detector->deallocMemory(defaultMallocAllocator(), mem, "FREE.c", 100); detector->stopChecking(); CHECK(reporter->message->contains("Memory corruption")); CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 10 type: malloc")); CHECK(reporter->message->contains(" deallocated at file: FREE.c line: 100 type: free")); } TEST(MemoryLeakDetectorTest, safelyDeleteNULL) { detector->deallocMemory(defaultNewAllocator(), NULLPTR); STRCMP_EQUAL("", reporter->message->asCharString()); } TEST(MemoryLeakDetectorTest, periodDisabled) { detector->disable(); char* mem = detector->allocMemory(defaultMallocAllocator(), 2); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_disabled)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_enabled)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->deallocMemory(defaultMallocAllocator(), mem); } TEST(MemoryLeakDetectorTest, periodEnabled) { detector->enable(); char* mem = detector->allocMemory(defaultMallocAllocator(), 2); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->deallocMemory(defaultMallocAllocator(), mem); } TEST(MemoryLeakDetectorTest, periodChecking) { char* mem = detector->allocMemory(defaultMallocAllocator(), 2); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->deallocMemory(defaultMallocAllocator(), mem); } TEST(MemoryLeakDetectorTest, defaultAllocationStageIsZero) { LONGS_EQUAL(0, detector->getCurrentAllocationStage()); } TEST(MemoryLeakDetectorTest, canFreeNoAllocations) { detector->deallocAllMemoryInCurrentAllocationStage(); LONGS_EQUAL(0, detector->getCurrentAllocationStage()); } TEST(MemoryLeakDetectorTest, increaseAllocationStage) { detector->increaseAllocationStage(); LONGS_EQUAL(1, detector->getCurrentAllocationStage()); } TEST(MemoryLeakDetectorTest, decreaseAllocationStage) { detector->increaseAllocationStage(); detector->decreaseAllocationStage(); LONGS_EQUAL(0, detector->getCurrentAllocationStage()); } TEST(MemoryLeakDetectorTest, freeAllMemoryInCurrentAllocationStage) { detector->increaseAllocationStage(); detector->allocMemory(defaultMallocAllocator(), 2); detector->allocMemory(defaultMallocAllocator(), 2); detector->deallocAllMemoryInCurrentAllocationStage(); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); } TEST(MemoryLeakDetectorTest, freeOnlyTheMemoryInTheAllocationStage) { char* mem = detector->allocMemory(defaultMallocAllocator(), 2); detector->increaseAllocationStage(); detector->allocMemory(defaultMallocAllocator(), 2); detector->deallocAllMemoryInCurrentAllocationStage(); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); detector->deallocMemory(defaultMallocAllocator(), mem); } TEST(MemoryLeakDetectorTest, allocateWithANullAllocatorCausesNoProblems) { char* mem = detector->allocMemory(NullUnknownAllocator::defaultAllocator(), 2); detector->deallocMemory(NullUnknownAllocator::defaultAllocator(), mem); } TEST(MemoryLeakDetectorTest, invalidateMemory) { unsigned char* mem = (unsigned char*)detector->allocMemory(defaultMallocAllocator(), 2); detector->invalidateMemory((char*)mem); CHECK(mem[0] == 0xCD); CHECK(mem[1] == 0xCD); detector->deallocMemory(defaultMallocAllocator(), mem); } TEST(MemoryLeakDetectorTest, invalidateMemoryNULLShouldWork) { detector->invalidateMemory(NULLPTR); } TEST_GROUP(MemoryLeakDetectorListTest) { }; TEST(MemoryLeakDetectorListTest, clearAllAccountingIsWorkingProperly) { MemoryLeakDetectorList listForTesting; MemoryLeakDetectorNode node1, node2, node3; node3.period_ = mem_leak_period_disabled; listForTesting.addNewNode(&node1); listForTesting.addNewNode(&node2); listForTesting.addNewNode(&node3); listForTesting.clearAllAccounting(mem_leak_period_enabled); POINTERS_EQUAL(NULLPTR, listForTesting.getFirstLeak(mem_leak_period_enabled)); CHECK(&node3 == listForTesting.getFirstLeak(mem_leak_period_disabled)); } TEST_GROUP(SimpleStringBuffer) { }; TEST(SimpleStringBuffer, initialStringIsEmpty) { SimpleStringBuffer buffer; STRCMP_EQUAL("", buffer.toString()); } TEST(SimpleStringBuffer, simpleTest) { SimpleStringBuffer buffer; buffer.add("Hello"); buffer.add(" World"); STRCMP_EQUAL("Hello World", buffer.toString()); } TEST(SimpleStringBuffer, writePastLimit) { SimpleStringBuffer buffer; for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN * 2; i++) buffer.add("h"); SimpleString str("h", SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN-1); STRCMP_EQUAL(str.asCharString(), buffer.toString()); } TEST(SimpleStringBuffer, setWriteLimit) { SimpleStringBuffer buffer; buffer.setWriteLimit(10); for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN ; i++) buffer.add("h"); SimpleString str("h", 10); STRCMP_EQUAL(str.asCharString(), buffer.toString()); } TEST(SimpleStringBuffer, setWriteLimitTooHighIsIgnored) { SimpleStringBuffer buffer; buffer.setWriteLimit(SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN+10); for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN+10; i++) buffer.add("h"); SimpleString str("h", SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN-1); STRCMP_EQUAL(str.asCharString(), buffer.toString()); } TEST(SimpleStringBuffer, resetWriteLimit) { SimpleStringBuffer buffer; buffer.setWriteLimit(10); for (int i = 0; i < SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN ; i++) buffer.add("h"); buffer.resetWriteLimit(); buffer.add("%s", SimpleString("h", 10).asCharString()); SimpleString str("h", 20); STRCMP_EQUAL(str.asCharString(), buffer.toString()); } TEST(SimpleStringBuffer, addMemoryDumpOneLinePlusOnePartial) { SimpleStringBuffer buffer; buffer.addMemoryDump("deadbeefdeadbeefhopsxx", 22); STRCMP_EQUAL(" 0000: 64 65 61 64 62 65 65 66 64 65 61 64 62 65 65 66 |deadbeefdeadbeef|\n" " 0010: 68 6f 70 73 78 78 |hopsxx|\n", buffer.toString()); } TEST(SimpleStringBuffer, addMemoryDumpNonPrintable) { SimpleStringBuffer buffer; // Ensure we test edge cases - NUL, 0x1F, 0x7F, 0xFF buffer.addMemoryDump("\x15\x7f\xff\x00\x1ftdd", 8); STRCMP_EQUAL(" 0000: 15 7f ff 00 1f 74 64 64 |.....tdd|\n", buffer.toString()); } TEST(SimpleStringBuffer, addMemoryDumpOneLine) { SimpleStringBuffer buffer; buffer.addMemoryDump("deadbeefdeadbeef", 16); STRCMP_EQUAL(" 0000: 64 65 61 64 62 65 65 66 64 65 61 64 62 65 65 66 |deadbeefdeadbeef|\n", buffer.toString()); } TEST(SimpleStringBuffer, addMemoryDumpOneHalfLine) { SimpleStringBuffer buffer; buffer.addMemoryDump("deadbeef", 8); STRCMP_EQUAL(" 0000: 64 65 61 64 62 65 65 66 |deadbeef|\n", buffer.toString()); } TEST(SimpleStringBuffer, addMemoryDumpOneByte) { SimpleStringBuffer buffer; buffer.addMemoryDump("Z", 1); STRCMP_EQUAL(" 0000: 5a |Z|\n", buffer.toString()); } TEST(SimpleStringBuffer, addMemoryDumpZeroBytes) { SimpleStringBuffer buffer; buffer.addMemoryDump("", 0); STRCMP_EQUAL("", buffer.toString()); } TEST_GROUP(ReallocBugReported) { MemoryLeakFailureForTest reporter; }; TEST(ReallocBugReported, CanSafelyDoAReallocWithANewAllocator) { MemoryLeakDetector detector(&reporter); char* mem = detector.allocMemory(defaultNewAllocator(), 5, "file", 1); mem = detector.reallocMemory(defaultNewAllocator(), mem, 19, "file", 1); detector.deallocMemory(defaultNewAllocator(), mem); } TEST(ReallocBugReported, CanSafelyDoAReallocWithAMallocAllocator) { MemoryLeakDetector detector(&reporter); char* mem = detector.allocMemory(defaultMallocAllocator(), 5, "file", 1, true); mem = detector.reallocMemory(defaultMallocAllocator(), mem, 19, "file", 1, true); detector.deallocMemory(defaultMallocAllocator(), mem, true); }
null
12
cpp
cpputest
TestFailureNaNTest.cpp
tests/CppUTest/TestFailureNaNTest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestOutput.h" #include "CppUTest/PlatformSpecificFunctions.h" #if CPPUTEST_USE_STD_C_LIB #include <math.h> #endif #if defined(NAN) && defined(INFINITY) namespace { const int failLineNumber = 2; const char* failFileName = "fail.cpp"; } TEST_GROUP(TestFailureNanAndInf) { UtestShell* test; void setup() CPPUTEST_OVERRIDE { test = new UtestShell("groupname", "testname", failFileName, failLineNumber-1); } void teardown() CPPUTEST_OVERRIDE { delete test; } }; #define FAILURE_EQUAL(a, b) STRCMP_EQUAL_LOCATION(a, (b).getMessage().asCharString(), "", __FILE__, __LINE__) TEST(TestFailureNanAndInf, DoublesEqualExpectedIsNaN) { DoublesEqualFailure f(test, failFileName, failLineNumber, (double)NAN, 2.0, 3.0, ""); FAILURE_EQUAL("expected <Nan - Not a number>\n" "\tbut was <2> threshold used was <3>\n" "\tCannot make comparisons with Nan", f); } TEST(TestFailureNanAndInf, DoublesEqualActualIsNaN) { DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, (double)NAN, 3.0, ""); FAILURE_EQUAL("expected <1>\n" "\tbut was <Nan - Not a number> threshold used was <3>\n" "\tCannot make comparisons with Nan", f); } TEST(TestFailureNanAndInf, DoublesEqualThresholdIsNaN) { DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, 2.0, (double)NAN, ""); FAILURE_EQUAL("expected <1>\n" "\tbut was <2> threshold used was <Nan - Not a number>\n" "\tCannot make comparisons with Nan", f); } TEST(TestFailureNanAndInf, DoublesEqualExpectedIsInf) { DoublesEqualFailure f(test, failFileName, failLineNumber, (double)INFINITY, 2.0, 3.0, ""); FAILURE_EQUAL("expected <Inf - Infinity>\n" "\tbut was <2> threshold used was <3>", f); } TEST(TestFailureNanAndInf, DoublesEqualActualIsInf) { DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, (double)INFINITY, 3.0, ""); FAILURE_EQUAL("expected <1>\n" "\tbut was <Inf - Infinity> threshold used was <3>", f); } TEST(TestFailureNanAndInf, DoublesEqualThresholdIsInf) { DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, (double)NAN, (double)INFINITY, ""); FAILURE_EQUAL("expected <1>\n" "\tbut was <Nan - Not a number> threshold used was <Inf - Infinity>\n" "\tCannot make comparisons with Nan", f); } #endif
null
13
cpp
cpputest
DummyMemoryLeakDetector.h
tests/CppUTest/DummyMemoryLeakDetector.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 DUMMYMEMORYLEAKDETECTOR_H #define DUMMYMEMORYLEAKDETECTOR_H class DummyMemoryLeakDetector : public MemoryLeakDetector { public: DummyMemoryLeakDetector(MemoryLeakFailure* reporter); virtual ~DummyMemoryLeakDetector() CPPUTEST_DESTRUCTOR_OVERRIDE; static bool wasDeleted(); private: static bool memoryLeakDetectorWasDeleted; }; class DummyMemoryLeakFailure : public MemoryLeakFailure { public: DummyMemoryLeakFailure(); virtual ~DummyMemoryLeakFailure() CPPUTEST_DESTRUCTOR_OVERRIDE; static bool wasDeleted(); virtual void fail(char*) CPPUTEST_OVERRIDE; private: static bool memoryLeakFailureWasDelete; }; #endif /* DUMMYMEMORYLEAKDETECTOR_H */
null
14
cpp
cpputest
AllocationInCppFile.h
tests/CppUTest/AllocationInCppFile.h
null
#ifndef ALLOCATIONINCPPFILE_H #define ALLOCATIONINCPPFILE_H char* newAllocation(); char* newArrayAllocation(); char* newAllocationWithoutMacro(); char* newArrayAllocationWithoutMacro(); #if CPPUTEST_HAVE_EXCEPTIONS class ClassThatThrowsAnExceptionInTheConstructor { public: CPPUTEST_NORETURN ClassThatThrowsAnExceptionInTheConstructor(); }; #endif #endif
null
15
cpp
cpputest
TestFailureTest.cpp
tests/CppUTest/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"; } TEST_GROUP(TestFailure) { UtestShell* test; void setup() CPPUTEST_OVERRIDE { test = new UtestShell("groupname", "testname", failFileName, failLineNumber-1); } void teardown() CPPUTEST_OVERRIDE { delete test; } }; #define FAILURE_EQUAL(a, b) STRCMP_EQUAL_LOCATION(a, (b).getMessage().asCharString(), "", __FILE__, __LINE__) TEST(TestFailure, CreateFailure) { TestFailure f1(test, failFileName, failLineNumber, "the failure message"); TestFailure f2(test, "the failure message"); TestFailure f3(test, failFileName, failLineNumber); } TEST(TestFailure, GetTestFileAndLineFromFailure) { TestFailure f1(test, failFileName, failLineNumber, "the failure message"); STRCMP_EQUAL(failFileName, f1.getTestFileName().asCharString()); LONGS_EQUAL(1, f1.getTestLineNumber()); } TEST(TestFailure, EqualsFailureWithText) { EqualsFailure f(test, failFileName, failLineNumber, "expected", "actual", "text"); FAILURE_EQUAL("Message: text\n" "\texpected <expected>\n\tbut was <actual>", f); } TEST(TestFailure, EqualsFailure) { 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", NULLPTR, ""); FAILURE_EQUAL("expected <expected>\n\tbut was <(null)>", f); } TEST(TestFailure, EqualsFailureWithNullAsExpected) { EqualsFailure f(test, failFileName, failLineNumber, NULLPTR, "actual", ""); FAILURE_EQUAL("expected <(null)>\n\tbut was <actual>", f); } TEST(TestFailure, CheckEqualFailureWithText) { CheckEqualFailure f(test, failFileName, failLineNumber, "expected", "actual", "text"); FAILURE_EQUAL("Message: text\n" "\texpected <expected>\n" "\tbut was <actual>\n" "\tdifference starts at position 0 at: < actual >\n" "\t ^", 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, CheckFailureWithText) { CheckFailure f(test, failFileName, failLineNumber, "CHECK", "chk", "text"); FAILURE_EQUAL("Message: text\n" "\tCHECK(chk) failed", f); } TEST(TestFailure, FailFailure) { FailFailure f(test, failFileName, failLineNumber, "chk"); FAILURE_EQUAL("chk", f); } TEST(TestFailure, LongsEqualFailureWithText) { LongsEqualFailure f(test, failFileName, failLineNumber, 1, 2, "text"); FAILURE_EQUAL("Message: text\n" "\texpected <1 (0x1)>\n\tbut was <2 (0x2)>", f); } TEST(TestFailure, LongsEqualFailure) { LongsEqualFailure f(test, failFileName, failLineNumber, 1, 2, ""); FAILURE_EQUAL("expected <1 (0x1)>\n\tbut was <2 (0x2)>", f); } TEST(TestFailure, LongLongsEqualFailure) { #if CPPUTEST_USE_LONG_LONG LongLongsEqualFailure f(test, failFileName, failLineNumber, 1, 2, ""); FAILURE_EQUAL("expected <1 (0x1)>\n\tbut was <2 (0x2)>", f); #else cpputest_longlong dummy_longlong; LongLongsEqualFailure f(test, failFileName, failLineNumber, dummy_longlong, dummy_longlong, ""); FAILURE_EQUAL("expected <<longlong_unsupported> >\n\tbut was <<longlong_unsupported> >", f); #endif } TEST(TestFailure, UnsignedLongLongsEqualFailure) { #if CPPUTEST_USE_LONG_LONG UnsignedLongLongsEqualFailure f(test, failFileName, failLineNumber, 1, 2, ""); FAILURE_EQUAL("expected <1 (0x1)>\n\tbut was <2 (0x2)>", f); #else cpputest_ulonglong dummy_ulonglong; UnsignedLongLongsEqualFailure f(test, failFileName, failLineNumber, dummy_ulonglong, dummy_ulonglong, ""); FAILURE_EQUAL("expected <<ulonglong_unsupported> >\n\tbut was <<ulonglong_unsupported> >", f); #endif } TEST(TestFailure, SignedBytesEqualFailure) { SignedBytesEqualFailure f(test, failFileName, failLineNumber, (signed char)-1, (signed char)2, ""); FAILURE_EQUAL("expected <-1 (0xff)>\n\tbut was < 2 (0x2)>", f); } TEST(TestFailure, StringsEqualFailureWithText) { StringEqualFailure f(test, failFileName, failLineNumber, "abc", "abd", "text"); FAILURE_EQUAL("Message: text\n" "\texpected <abc>\n" "\tbut was <abd>\n" "\tdifference starts at position 2 at: < abd >\n" "\t ^", 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: <ngWith\\t\\ndifferentS>\n" "\t ^", 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, StringsEqualFailureWithNullAsActual) { StringEqualFailure f(test, failFileName, failLineNumber, "abc", NULLPTR, ""); FAILURE_EQUAL("expected <abc>\n" "\tbut was <(null)>", f); } TEST(TestFailure, StringsEqualFailureWithNullAsExpected) { StringEqualFailure f(test, failFileName, failLineNumber, NULLPTR, "abd", ""); FAILURE_EQUAL("expected <(null)>\n" "\tbut was <abd>", f); } TEST(TestFailure, StringsEqualNoCaseFailureWithText) { StringEqualNoCaseFailure f(test, failFileName, failLineNumber, "ABC", "abd", "text"); FAILURE_EQUAL("Message: text\n" "\texpected <ABC>\n" "\tbut was <abd>\n" "\tdifference starts at position 2 at: < abd >\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, StringsEqualNoCaseFailureWithActualAsNull) { StringEqualNoCaseFailure f(test, failFileName, failLineNumber, "ABC", NULLPTR, ""); FAILURE_EQUAL("expected <ABC>\n" "\tbut was <(null)>", f); } TEST(TestFailure, StringsEqualNoCaseFailureWithExpectedAsNull) { StringEqualNoCaseFailure f(test, failFileName, failLineNumber, NULLPTR, "abd", ""); FAILURE_EQUAL("expected <(null)>\n" "\tbut was <abd>", 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, DoublesEqualNormalWithText) { DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, 2.0, 3.0, "text"); FAILURE_EQUAL("Message: text\n" "\texpected <1>\n" "\tbut was <2> threshold used was <3>", f); } TEST(TestFailure, DoublesEqualNormal) { DoublesEqualFailure f(test, failFileName, failLineNumber, 1.0, 2.0, 3.0, ""); FAILURE_EQUAL("expected <1>\n" "\tbut was <2> threshold used was <3>", f); } TEST(TestFailure, BinaryEqualWithText) { const unsigned char expectedData[] = { 0x00 }; const unsigned char actualData[] = { 0x01 }; BinaryEqualFailure f(test, failFileName, failLineNumber, expectedData, actualData, sizeof(expectedData), "text"); FAILURE_EQUAL("Message: text\n" "\texpected <00>\n" "\tbut was <01>\n" "\tdifference starts at position 0 at: < 01 >\n" "\t ^", f); } TEST(TestFailure, BinaryEqualOneByte) { const unsigned char expectedData[] = { 0x00 }; const unsigned char actualData[] = { 0x01 }; BinaryEqualFailure f(test, failFileName, failLineNumber, expectedData, actualData, sizeof(expectedData), ""); FAILURE_EQUAL("expected <00>\n" "\tbut was <01>\n" "\tdifference starts at position 0 at: < 01 >\n" "\t ^", f); } TEST(TestFailure, BinaryEqualTwoBytes) { const unsigned char expectedData[] = {0x00, 0x01}; const unsigned char actualData[] = {0x00, 0x02}; BinaryEqualFailure f(test, failFileName, failLineNumber, expectedData, actualData, sizeof(expectedData), ""); FAILURE_EQUAL("expected <00 01>\n" "\tbut was <00 02>\n" "\tdifference starts at position 1 at: < 00 02 >\n" "\t ^", f); } TEST(TestFailure, BinaryEqualThreeBytes) { const unsigned char expectedData[] = {0x00, 0x01, 0x00}; const unsigned char actualData[] = {0x00, 0x02, 0x00}; BinaryEqualFailure f(test, failFileName, failLineNumber, expectedData, actualData, sizeof(expectedData), ""); FAILURE_EQUAL("expected <00 01 00>\n" "\tbut was <00 02 00>\n" "\tdifference starts at position 1 at: < 00 02 00 >\n" "\t ^", f); } TEST(TestFailure, BinaryEqualFullWidth) { const unsigned char expectedData[] = {0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00}; const unsigned char actualData[] = {0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00}; BinaryEqualFailure f(test, failFileName, failLineNumber, expectedData, actualData, sizeof(expectedData), ""); FAILURE_EQUAL("expected <00 00 00 01 00 00 00>\n" "\tbut was <00 00 00 02 00 00 00>\n" "\tdifference starts at position 3 at: <00 00 00 02 00 00 00>\n" "\t ^", f); } TEST(TestFailure, BinaryEqualLast) { const unsigned char expectedData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; const unsigned char actualData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; BinaryEqualFailure f(test, failFileName, failLineNumber, expectedData, actualData, sizeof(expectedData), ""); FAILURE_EQUAL("expected <00 00 00 00 00 00 00>\n" "\tbut was <00 00 00 00 00 00 01>\n" "\tdifference starts at position 6 at: <00 00 00 01 >\n" "\t ^", f); } TEST(TestFailure, BinaryEqualActualNull) { const unsigned char expectedData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; BinaryEqualFailure f(test, failFileName, failLineNumber, expectedData, NULLPTR, sizeof(expectedData), ""); FAILURE_EQUAL("expected <00 00 00 00 00 00 00>\n\tbut was <(null)>", f); } TEST(TestFailure, BinaryEqualExpectedNull) { const unsigned char actualData[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; BinaryEqualFailure f(test, failFileName, failLineNumber, NULLPTR, actualData, sizeof(actualData), ""); FAILURE_EQUAL("expected <(null)>\n\tbut was <00 00 00 00 00 00 01>", f); } TEST(TestFailure, BitsEqualWithText) { BitsEqualFailure f(test, failFileName, failLineNumber, 0x0001, 0x0003, 0x00FF, 2*8/CPPUTEST_CHAR_BIT, "text"); FAILURE_EQUAL("Message: text\n" "\texpected <xxxxxxxx 00000001>\n\tbut was <xxxxxxxx 00000011>", f); } #if (CPPUTEST_CHAR_BIT == 16) TEST(TestFailure, BitsEqualChar) { BitsEqualFailure f(test, failFileName, failLineNumber, 0x01, 0x03, 0xFF, sizeof(char), ""); FAILURE_EQUAL("expected <xxxxxxxx 00000001>\n\tbut was <xxxxxxxx 00000011>", f); } #elif (CPPUTEST_CHAR_BIT == 8) TEST(TestFailure, BitsEqualChar) { BitsEqualFailure f(test, failFileName, failLineNumber, 0x01, 0x03, 0xFF, sizeof(char), ""); FAILURE_EQUAL("expected <00000001>\n\tbut was <00000011>", f); } #endif TEST(TestFailure, BitsEqual16Bit) { BitsEqualFailure f(test, failFileName, failLineNumber, 0x0001, 0x0003, 0xFFFF, 2*8/CPPUTEST_CHAR_BIT, ""); FAILURE_EQUAL("expected <00000000 00000001>\n\tbut was <00000000 00000011>", f); } TEST(TestFailure, BitsEqual32Bit) { BitsEqualFailure f(test, failFileName, failLineNumber, 0x00000001, 0x00000003, 0xFFFFFFFF, 4*8/CPPUTEST_CHAR_BIT, ""); FAILURE_EQUAL("expected <00000000 00000000 00000000 00000001>\n\tbut was <00000000 00000000 00000000 00000011>", f); } TEST(TestFailure, FeatureUnsupported) { FeatureUnsupportedFailure f(test, failFileName, failLineNumber, "SOME_FEATURE", ""); FAILURE_EQUAL("The feature \"SOME_FEATURE\" is not supported in this environment or with the feature set selected when building the library.", f); } #if CPPUTEST_HAVE_EXCEPTIONS TEST(TestFailure, UnexpectedExceptionFailure_UnknownException) { UnexpectedExceptionFailure f(test); FAILURE_EQUAL("Unexpected exception of unknown type was thrown.", f); } #endif #if CPPUTEST_HAVE_EXCEPTIONS && CPPUTEST_USE_STD_CPP_LIB TEST(TestFailure, UnexpectedExceptionFailure_StandardException) { std::runtime_error e("Some error"); UnexpectedExceptionFailure f(test, e); #if CPPUTEST_HAVE_RTTI STRCMP_CONTAINS("Unexpected exception of type '", f.getMessage().asCharString()); STRCMP_CONTAINS("runtime_error", f.getMessage().asCharString()); STRCMP_CONTAINS("' was thrown: Some error", f.getMessage().asCharString()); #else FAILURE_EQUAL("Unexpected exception of unknown type was thrown.", f); #endif } #endif
null
16
cpp
cpputest
CheatSheetTest.cpp
tests/CppUTest/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() CPPUTEST_OVERRIDE { /* Set method real_one to stub. Automatically restore in teardown */ UT_PTR_SET(real_one, stub); } /* Declare a teardown method for the test group. Optional */ void teardown() CPPUTEST_OVERRIDE { } }; /* 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
17
cpp
cpputest
AllocationInCFile.h
tests/CppUTest/AllocationInCFile.h
null
#ifndef ALLOCATIONINCFILE_H #define ALLOCATIONINCFILE_H #ifdef __cplusplus extern "C" { #endif extern char* mallocAllocation(void); extern char* strdupAllocation(void); extern char* strndupAllocation(void); extern void freeAllocation(void* memory); extern void freeAllocationWithoutMacro(void* memory); #ifdef __cplusplus } #endif #endif
null
18
cpp
cpputest
TestUTestMacro.cpp
tests/CppUTest/TestUTestMacro.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/TestTestingFixture.h" #define CHECK_TEST_FAILS_PROPER_WITH_TEXT(text) fixture.checkTestFailsWithProperTestLocation(text, __FILE__, __LINE__) // Mainly this is for Visual C++, but we'll define it for any system that has the same behavior // of a 32-bit long on a 64-bit system #if defined(CPPUTEST_64BIT) && defined(CPPUTEST_64BIT_32BIT_LONGS) // Forcing the value to be unsigned long long means that there's no sign-extension to perform #define to_void_pointer(x) ((void *)x##ULL) #define to_func_pointer(x) ((void (*)())x##ULL) #else // Probably not needed, but let's guarantee that the value is an unsigned long #define to_void_pointer(x) ((void *)x##UL) #define to_func_pointer(x) ((void (*)())x##UL) #endif TEST_GROUP(UnitTestMacros) { TestTestingFixture fixture; }; static void failingTestMethodWithFAIL_() { FAIL("This test fails"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FAILMakesTheTestFailPrintsTheRightResultAndStopsExecuting) { fixture.runTestWithMethod(failingTestMethodWithFAIL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("This test fails"); } TEST(UnitTestMacros, FAILWillPrintTheFileThatItFailed) { fixture.runTestWithMethod(failingTestMethodWithFAIL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT(__FILE__); } TEST(UnitTestMacros, FAILBehavesAsAProperMacro) { if (false) FAIL(""); else CHECK(true); if (true) CHECK(true); else FAIL(""); } IGNORE_TEST(UnitTestMacros, FAILworksInAnIgnoredTest) { FAIL("die!"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void UNSIGNED_LONGS_EQUALTestMethod_() { UNSIGNED_LONGS_EQUAL(1, 1); UNSIGNED_LONGS_EQUAL(1, 0); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestUNSIGNED_LONGS_EQUAL) { fixture.runTestWithMethod(UNSIGNED_LONGS_EQUALTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); } TEST(UnitTestMacros, UNSIGNED_LONGS_EQUALBehavesAsProperMacro) { if (false) UNSIGNED_LONGS_EQUAL(1, 0); else UNSIGNED_LONGS_EQUAL(1, 1); } IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGS_EQUALWorksInAnIgnoredTest) { UNSIGNED_LONGS_EQUAL(1, 0); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void UNSIGNED_LONGS_EQUAL_TEXTTestMethod_() { UNSIGNED_LONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestUNSIGNED_LONGS_EQUAL_TEXT) { fixture.runTestWithMethod(UNSIGNED_LONGS_EQUAL_TEXTTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, UNSIGNED_LONGS_EQUAL_TEXTBehavesAsProperMacro) { if (false) UNSIGNED_LONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); else UNSIGNED_LONGS_EQUAL_TEXT(1, 1, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGS_EQUAL_TEXTWorksInAnIgnoredTest) { UNSIGNED_LONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE #if CPPUTEST_USE_LONG_LONG static void LONGLONGS_EQUALTestMethod_() { LONGLONGS_EQUAL(1, 1); LONGLONGS_EQUAL(1, 0); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestLONGLONGS_EQUAL) { fixture.runTestWithMethod(LONGLONGS_EQUALTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); } TEST(UnitTestMacros, LONGLONGS_EQUALBehavesAsProperMacro) { if (false) LONGLONGS_EQUAL(1, 0); else LONGLONGS_EQUAL(1, 1); } IGNORE_TEST(UnitTestMacros, LONGLONGS_EQUALWorksInAnIgnoredTest) { LONGLONGS_EQUAL(1, 0); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void LONGLONGS_EQUAL_TEXTTestMethod_() { LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestLONGLONGS_EQUAL_TEXT) { fixture.runTestWithMethod(LONGLONGS_EQUAL_TEXTTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, LONGLONGS_EQUAL_TEXTBehavesAsProperMacro) { if (false) LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); else LONGLONGS_EQUAL_TEXT(1, 1, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, LONGLONGS_EQUAL_TEXTWorksInAnIgnoredTest) { LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void UNSIGNED_LONGLONGS_EQUALTestMethod_() { UNSIGNED_LONGLONGS_EQUAL(1, 1); UNSIGNED_LONGLONGS_EQUAL(1, 0); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestUNSIGNED_LONGLONGS_EQUAL) { fixture.runTestWithMethod(UNSIGNED_LONGLONGS_EQUALTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); } TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUALBehavesAsProperMacro) { if (false) UNSIGNED_LONGLONGS_EQUAL(1, 0); else UNSIGNED_LONGLONGS_EQUAL(1, 1); } IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUALWorksInAnIgnoredTest) { UNSIGNED_LONGLONGS_EQUAL(1, 0); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void UNSIGNED_LONGLONGS_EQUAL_TEXTTestMethod_() { UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestUNSIGNED_LONGLONGS_EQUAL_TEXT) { fixture.runTestWithMethod(UNSIGNED_LONGLONGS_EQUAL_TEXTTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUAL_TEXTBehavesAsProperMacro) { if (false) UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); else UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 1, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUAL_TEXTWorksInAnIgnoredTest) { UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE #endif /* CPPUTEST_USE_LONG_LONG */ static void failingTestMethodWithCHECK_() { CHECK(false); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK) { fixture.runTestWithMethod(failingTestMethodWithCHECK_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK(false) failed"); } TEST(UnitTestMacros, CHECKBehavesAsProperMacro) { if (false) CHECK(false); else CHECK(true); } IGNORE_TEST(UnitTestMacros, CHECKWorksInAnIgnoredTest) { CHECK(false); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithCHECK_TEXT_() { CHECK_TEXT(false, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_TEXT) { fixture.runTestWithMethod(failingTestMethodWithCHECK_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK(false) failed"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, CHECK_TEXTBehavesAsProperMacro) { if (false) CHECK_TEXT(false, "false"); else CHECK_TEXT(true, "true"); } IGNORE_TEST(UnitTestMacros, CHECK_TEXTWorksInAnIgnoredTest) { CHECK_TEXT(false, "false"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithCHECK_TRUE_() { CHECK_TRUE(false); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_TRUE) { fixture.runTestWithMethod(failingTestMethodWithCHECK_TRUE_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_TRUE(false) failed"); } TEST(UnitTestMacros, CHECK_TRUEBehavesAsProperMacro) { if (false) CHECK_TRUE(false); else CHECK_TRUE(true); } IGNORE_TEST(UnitTestMacros, CHECK_TRUEWorksInAnIgnoredTest) { CHECK_TRUE(false); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithCHECK_TRUE_TEXT_() { CHECK_TRUE_TEXT(false, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_TRUE_TEXT) { fixture.runTestWithMethod(failingTestMethodWithCHECK_TRUE_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_TRUE(false) failed"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, CHECK_TRUE_TEXTBehavesAsProperMacro) { if (false) CHECK_TRUE_TEXT(false, "Failed because it failed"); else CHECK_TRUE_TEXT(true, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, CHECK_TRUE_TEXTWorksInAnIgnoredTest) { CHECK_TRUE_TEXT(false, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithCHECK_FALSE_() { CHECK_FALSE(true); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_FALSE) { fixture.runTestWithMethod(failingTestMethodWithCHECK_FALSE_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_FALSE(true) failed"); } TEST(UnitTestMacros, CHECK_FALSEBehavesAsProperMacro) { if (false) CHECK_FALSE(true); else CHECK_FALSE(false); } IGNORE_TEST(UnitTestMacros, CHECK_FALSEWorksInAnIgnoredTest) { CHECK_FALSE(true); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithCHECK_FALSE_TEXT_() { CHECK_FALSE_TEXT(true, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_FALSE_TEXT) { fixture.runTestWithMethod(failingTestMethodWithCHECK_FALSE_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_FALSE(true)"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, CHECK_FALSE_TEXTBehavesAsProperMacro) { if (false) CHECK_FALSE_TEXT(true, "Failed because it failed"); else CHECK_FALSE_TEXT(false, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, CHECK_FALSE_TEXTWorksInAnIgnoredTest) { CHECK_FALSE_TEXT(true, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithCHECK_EQUAL_() { CHECK_EQUAL(1, 2); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_EQUAL) { fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <2>"); } static void failingTestMethodWithCHECK_COMPARE_() { double small = 0.5, big = 0.8; CHECK_COMPARE(small, >=, big); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_COMPARE) { fixture.runTestWithMethod(failingTestMethodWithCHECK_COMPARE_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_COMPARE(0.5 >= 0.8)"); } TEST(UnitTestMacros, CHECK_COMPAREBehavesAsProperMacro) { if (false) CHECK_COMPARE(1, >, 2); else CHECK_COMPARE(1, <, 2); } IGNORE_TEST(UnitTestMacros, CHECK_COMPAREWorksInAnIgnoredTest) { CHECK_COMPARE(1, >, 2); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithCHECK_COMPARE_TEXT_() { double small = 0.5, big = 0.8; CHECK_COMPARE_TEXT(small, >=, big, "small bigger than big"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_COMPARE_TEXT) { fixture.runTestWithMethod(failingTestMethodWithCHECK_COMPARE_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_COMPARE(0.5 >= 0.8)"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("small bigger than big"); } TEST(UnitTestMacros, CHECK_COMPARE_TEXTBehavesAsProperMacro) { if (false) CHECK_COMPARE_TEXT(1, >, 2, "1 bigger than 2"); else CHECK_COMPARE_TEXT(1, <, 2, "1 smaller than 2"); } IGNORE_TEST(UnitTestMacros, CHECK_COMPARE_TEXTWorksInAnIgnoredTest) { CHECK_COMPARE_TEXT(1, >, 2, "1 smaller than 2"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static int countInCountingMethod; static int countingMethod_() { return countInCountingMethod++; } TEST(UnitTestMacros, LONGS_EQUAL_macroExpressionSafety) { LONGS_EQUAL(1, 0.4 + 0.7); LONGS_EQUAL(0.4 + 0.7, 1); LONGS_EQUAL_TEXT(1, 0.4 + 0.7, "-Wconversion=great"); LONGS_EQUAL_TEXT(0.4 + 0.7, 1, "-Wconversion=great"); } TEST(UnitTestMacros, UNSIGNED_LONGS_EQUAL_macroExpressionSafety) { UNSIGNED_LONGS_EQUAL(1, 0.4 + 0.7); UNSIGNED_LONGS_EQUAL(0.4 + 0.7, 1); UNSIGNED_LONGS_EQUAL_TEXT(1, 0.4 + 0.7, "-Wconversion=great"); UNSIGNED_LONGS_EQUAL_TEXT(0.4 + 0.7, 1, "-Wconversion=great"); } TEST(UnitTestMacros, passingCheckEqualWillNotBeEvaluatedMultipleTimesWithCHECK_EQUAL) { countInCountingMethod = 0; CHECK_EQUAL(0, countingMethod_()); LONGS_EQUAL(1, countInCountingMethod); } static void failing_CHECK_EQUAL_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning_() { CHECK_EQUAL(12345, countingMethod_()); } // LCOV_EXCL_LINE TEST(UnitTestMacros, failing_CHECK_EQUAL_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning) { fixture.runTestWithMethod(failing_CHECK_EQUAL_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("WARNING:\n\tThe \"Actual Parameter\" parameter is evaluated multiple times resulting in different values.\n\tThus the value in the error message is probably incorrect."); } static void failing_CHECK_EQUAL_WithExpectedBeingEvaluatesMultipleTimesWillGiveAWarning_() { CHECK_EQUAL(countingMethod_(), 12345); } // LCOV_EXCL_LINE TEST(UnitTestMacros, failing_CHECK_EQUAL_WithExpectedBeingEvaluatesMultipleTimesWillGiveAWarning) { fixture.runTestWithMethod(failing_CHECK_EQUAL_WithExpectedBeingEvaluatesMultipleTimesWillGiveAWarning_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("WARNING:\n\tThe \"Expected Parameter\" parameter is evaluated multiple times resulting in different values.\n\tThus the value in the error message is probably incorrect."); } TEST(UnitTestMacros, failing_CHECK_EQUAL_withParamatersThatDontChangeWillNotGiveAnyWarning) { fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_); fixture.assertPrintContainsNot("WARNING"); } TEST(UnitTestMacros, CHECK_EQUALBehavesAsProperMacro) { if (false) CHECK_EQUAL(1, 2); else CHECK_EQUAL(1, 1); } IGNORE_TEST(UnitTestMacros, CHECK_EQUALWorksInAnIgnoredTest) { CHECK_EQUAL(1, 2); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithCHECK_EQUAL_TEXT_() { CHECK_EQUAL_TEXT(1, 2, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_EQUAL_TEXT) { fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <2>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, CHECK_EQUAL_TEXTBehavesAsProperMacro) { if (false) CHECK_EQUAL_TEXT(1, 2, "Failed because it failed"); else CHECK_EQUAL_TEXT(1, 1, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, CHECK_EQUAL_TEXTWorksInAnIgnoredTest) { CHECK_EQUAL_TEXT(1, 2, "Failed because it failed"); // LCOV_EXCL_LINE; } // LCOV_EXCL_LINE static void failingTestMethodWithCHECK_EQUAL_ZERO_() { CHECK_EQUAL_ZERO(1); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_EQUAL_ZERO) { fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_ZERO_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <1>"); } TEST(UnitTestMacros, passingCheckEqualWillNotBeEvaluatedMultipleTimesWithCHECK_EQUAL_ZERO) { countInCountingMethod = 0; CHECK_EQUAL_ZERO(countingMethod_()); LONGS_EQUAL(1, countInCountingMethod); } static void failing_CHECK_EQUAL_ZERO_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning_() { countInCountingMethod = 1; CHECK_EQUAL_ZERO(countingMethod_()); } // LCOV_EXCL_LINE TEST(UnitTestMacros, failing_CHECK_EQUAL_ZERO_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning) { fixture.runTestWithMethod(failing_CHECK_EQUAL_ZERO_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("WARNING:\n\tThe \"Actual Parameter\" parameter is evaluated multiple times resulting in different values.\n\tThus the value in the error message is probably incorrect."); } TEST(UnitTestMacros, failing_CHECK_EQUAL_ZERO_withParamatersThatDontChangeWillNotGiveAnyWarning) { fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_ZERO_); fixture.assertPrintContainsNot("WARNING"); } IGNORE_TEST(UnitTestMacros, CHECK_EQUAL_ZERO_WorksInAnIgnoredTest) { CHECK_EQUAL_ZERO(1); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, CHECK_EQUAL_ZERO_BehavesAsProperMacro) { if (false) CHECK_EQUAL_ZERO(1); else CHECK_EQUAL_ZERO(0); } static void failingTestMethodWithCHECK_EQUAL_ZERO_TEXT_() { CHECK_EQUAL_ZERO_TEXT(1, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_EQUAL_ZERO_TEXT) { fixture.runTestWithMethod(failingTestMethodWithCHECK_EQUAL_ZERO_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, CHECK_EQUAL_ZERO_TEXTBehavesAsProperMacro) { if (false) CHECK_EQUAL_ZERO_TEXT(1, "Failed because it failed"); else CHECK_EQUAL_ZERO_TEXT(0, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, CHECK_EQUAL_ZERO_TEXTWorksInAnIgnoredTest) { CHECK_EQUAL_ZERO_TEXT(1, "Failed because it failed"); // LCOV_EXCL_LINE; } // LCOV_EXCL_LINE static void failingTestMethodWithLONGS_EQUAL_() { LONGS_EQUAL(1, 0xff); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithLONGS_EQUALS) { fixture.runTestWithMethod(failingTestMethodWithLONGS_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected < 1 (0x1)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <255 (0xff)>"); } static void failingTestMethodWithLONGS_EQUALWithSymbolicParameters_() { #define MONDAY 1 int day_of_the_week = MONDAY+1; LONGS_EQUAL(MONDAY, day_of_the_week); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithLONGS_EQUALShowsSymbolicParameters) { fixture.runTestWithMethod(failingTestMethodWithLONGS_EQUALWithSymbolicParameters_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("LONGS_EQUAL(MONDAY, day_of_the_week) failed"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <2 (0x2)>"); CHECK_FALSE(fixture.getOutput().contains("Message: ")); } TEST(UnitTestMacros, LONGS_EQUALBehavesAsProperMacro) { if (false) LONGS_EQUAL(1, 2); else LONGS_EQUAL(10, 10); } IGNORE_TEST(UnitTestMacros, LONGS_EQUALWorksInAnIgnoredTest) { LONGS_EQUAL(11, 22); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithLONGS_EQUAL_TEXT_() { LONGS_EQUAL_TEXT(1, 0xff, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithLONGS_EQUALS_TEXT) { fixture.runTestWithMethod(failingTestMethodWithLONGS_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected < 1 (0x1)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <255 (0xff)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, LONGS_EQUAL_TEXTBehavesAsProperMacro) { if (false) LONGS_EQUAL_TEXT(1, 2, "Failed because it failed"); else LONGS_EQUAL_TEXT(10, 10, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, LONGS_EQUAL_TEXTWorksInAnIgnoredTest) { LONGS_EQUAL_TEXT(11, 22, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithBYTES_EQUAL_() { BYTES_EQUAL('a', 'b'); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } TEST(UnitTestMacros, FailureWithBYTES_EQUAL) { fixture.runTestWithMethod(failingTestMethodWithBYTES_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <97 (0x61)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <98 (0x62)>"); } TEST(UnitTestMacros, BYTES_EQUALBehavesAsProperMacro) { if (false) BYTES_EQUAL('a', 'b'); else BYTES_EQUAL('c', 'c'); } IGNORE_TEST(UnitTestMacros, BYTES_EQUALWorksInAnIgnoredTest) { BYTES_EQUAL('q', 'w'); // LCOV_EXCL_LINE; } // LCOV_EXCL_LINE static void failingTestMethodWithBYTES_EQUAL_TEXT_() { BYTES_EQUAL_TEXT('a', 'b', "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } TEST(UnitTestMacros, FailureWithBYTES_EQUAL_TEXT) { fixture.runTestWithMethod(failingTestMethodWithBYTES_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <97 (0x61)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <98 (0x62)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, BYTES_EQUAL_TEXTBehavesAsProperMacro) { if (false) BYTES_EQUAL_TEXT('a', 'b', "Failed because it failed"); else BYTES_EQUAL_TEXT('c', 'c', "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, BYTES_EQUAL_TEXTWorksInAnIgnoredTest) { BYTES_EQUAL_TEXT('q', 'w', "Failed because it failed"); // LCOV_EXCL_LINE; } // LCOV_EXCL_LINE static void failingTestMethodWithSIGNED_BYTES_EQUAL_() { SIGNED_BYTES_EQUAL(-1, -2); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } TEST(UnitTestMacros, FailureWithSIGNED_BYTES_EQUAL) { fixture.runTestWithMethod(failingTestMethodWithSIGNED_BYTES_EQUAL_); #if CPPUTEST_CHAR_BIT == 16 CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-1 (0xffff)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-2 (0xfffe)>"); #elif CPPUTEST_CHAR_BIT == 8 CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-1 (0xff)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-2 (0xfe)>"); #endif } TEST(UnitTestMacros, CHARS_EQUALBehavesAsProperMacro) { if (false) SIGNED_BYTES_EQUAL(-1, -2); else SIGNED_BYTES_EQUAL(-3, -3); } IGNORE_TEST(UnitTestMacros, CHARS_EQUALWorksInAnIgnoredTest) { SIGNED_BYTES_EQUAL(-7, 19); // LCOV_EXCL_LINE; } // LCOV_EXCL_LINE static void failingTestMethodWithSIGNED_BYTES_EQUAL_TEXT_() { SIGNED_BYTES_EQUAL_TEXT(-127, -126, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } TEST(UnitTestMacros, FailureWithSIGNED_BYTES_EQUAL_TEXT) { fixture.runTestWithMethod(failingTestMethodWithSIGNED_BYTES_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-127 (0x81)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-126 (0x82)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, CHARS_EQUAL_TEXTBehavesAsProperMacro) { if (false) SIGNED_BYTES_EQUAL_TEXT(-1, -2, "Failed because it failed"); else SIGNED_BYTES_EQUAL_TEXT(-3, -3, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, SIGNED_BYTES_EQUAL_TEXTWorksInAnIgnoredTest) { SIGNED_BYTES_EQUAL_TEXT(-7, 19, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithPOINTERS_EQUAL_() { POINTERS_EQUAL((void*)0xa5a5, (void*)0xf0f0); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithPOINTERS_EQUAL) { fixture.runTestWithMethod(failingTestMethodWithPOINTERS_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>"); } TEST(UnitTestMacros, POINTERS_EQUALBehavesAsProperMacro) { if (false) POINTERS_EQUAL(NULLPTR, to_void_pointer(0xbeefbeef)); else POINTERS_EQUAL(to_void_pointer(0xdeadbeef), to_void_pointer(0xdeadbeef)); } IGNORE_TEST(UnitTestMacros, POINTERS_EQUALWorksInAnIgnoredTest) { POINTERS_EQUAL((void*) 0xbeef, (void*) 0xdead); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithPOINTERS_EQUAL_TEXT_() { POINTERS_EQUAL_TEXT((void*)0xa5a5, (void*)0xf0f0, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithPOINTERS_EQUAL_TEXT) { fixture.runTestWithMethod(failingTestMethodWithPOINTERS_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, POINTERS_EQUAL_TEXTBehavesAsProperMacro) { if (false) POINTERS_EQUAL_TEXT(NULLPTR, to_void_pointer(0xbeefbeef), "Failed because it failed"); else POINTERS_EQUAL_TEXT(to_void_pointer(0xdeadbeef), to_void_pointer(0xdeadbeef), "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, POINTERS_EQUAL_TEXTWorksInAnIgnoredTest) { POINTERS_EQUAL_TEXT((void*) 0xbeef, (void*) 0xdead, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithFUNCTIONPOINTERS_EQUAL_() { FUNCTIONPOINTERS_EQUAL((void (*)())0xa5a5, (void (*)())0xf0f0); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithFUNCTIONPOINTERS_EQUAL) { fixture.runTestWithMethod(failingTestMethodWithFUNCTIONPOINTERS_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>"); } TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUALBehavesAsProperMacro) { if (false) FUNCTIONPOINTERS_EQUAL(NULLPTR, to_func_pointer(0xbeefbeef)); else FUNCTIONPOINTERS_EQUAL(to_func_pointer(0xdeadbeef), to_func_pointer(0xdeadbeef)); } IGNORE_TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUALWorksInAnIgnoredTest) { FUNCTIONPOINTERS_EQUAL((void (*)())0xbeef, (void (*)())0xdead); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithFUNCTIONPOINTERS_EQUAL_TEXT_() { FUNCTIONPOINTERS_EQUAL_TEXT((void (*)())0xa5a5, (void (*)())0xf0f0, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithFUNCTIONPOINTERS_EQUAL_TEXT) { fixture.runTestWithMethod(failingTestMethodWithFUNCTIONPOINTERS_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUAL_TEXTBehavesAsProperMacro) { if (false) FUNCTIONPOINTERS_EQUAL_TEXT(NULLPTR, to_func_pointer(0xbeefbeef), "Failed because it failed"); else FUNCTIONPOINTERS_EQUAL_TEXT(to_func_pointer(0xdeadbeef), to_func_pointer(0xdeadbeef), "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUAL_TEXTWorksInAnIgnoredTest) { FUNCTIONPOINTERS_EQUAL_TEXT((void (*)())0xbeef, (void (*)())0xdead, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithDOUBLES_EQUAL_() { DOUBLES_EQUAL(0.12, 44.1, 0.3); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithDOUBLES_EQUAL) { fixture.runTestWithMethod(failingTestMethodWithDOUBLES_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0.12>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <44.1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("threshold used was <0.3>"); } TEST(UnitTestMacros, DOUBLES_EQUALBehavesAsProperMacro) { if (false) DOUBLES_EQUAL(0.0, 1.1, 0.0005); else DOUBLES_EQUAL(0.1, 0.2, 0.2); } IGNORE_TEST(UnitTestMacros, DOUBLES_EQUALWorksInAnIgnoredTest) { DOUBLES_EQUAL(100.0, 0.0, 0.2); // LCOV_EXCL_LINE; } // LCOV_EXCL_LINE static void failingTestMethodWithDOUBLES_EQUAL_TEXT_() { DOUBLES_EQUAL_TEXT(0.12, 44.1, 0.3, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithDOUBLES_EQUAL_TEXT) { fixture.runTestWithMethod(failingTestMethodWithDOUBLES_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0.12>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <44.1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("threshold used was <0.3>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, DOUBLES_EQUAL_TEXTBehavesAsProperMacro) { if (false) DOUBLES_EQUAL_TEXT(0.0, 1.1, 0.0005, "Failed because it failed"); else DOUBLES_EQUAL_TEXT(0.1, 0.2, 0.2, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, DOUBLES_EQUAL_TEXTWorksInAnIgnoredTest) { DOUBLES_EQUAL_TEXT(100.0, 0.0, 0.2, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static bool lineOfCodeExecutedAfterCheck = false; static void passingTestMethod_() { CHECK(true); lineOfCodeExecutedAfterCheck = true; } TEST(UnitTestMacros, SuccessPrintsNothing) { fixture.runTestWithMethod(passingTestMethod_); LONGS_EQUAL(0, fixture.getFailureCount()); fixture.assertPrintContains(".\nOK (1 tests"); CHECK(lineOfCodeExecutedAfterCheck); } static void methodThatOnlyPrints_() { UT_PRINT("Hello World!"); } TEST(UnitTestMacros, PrintPrintsWhateverPrintPrints) { fixture.runTestWithMethod(methodThatOnlyPrints_); LONGS_EQUAL(0, fixture.getFailureCount()); fixture.assertPrintContains("Hello World!"); fixture.assertPrintContains(__FILE__); } static void methodThatOnlyPrintsUsingSimpleStringFromFormat_() { UT_PRINT(StringFromFormat("Hello %s %d", "World!", 2009)); } TEST(UnitTestMacros, PrintPrintsSimpleStringsForExampleThoseReturnedByFromString) { fixture.runTestWithMethod(methodThatOnlyPrintsUsingSimpleStringFromFormat_); fixture.assertPrintContains("Hello World! 2009"); } static int functionThatReturnsAValue() { CHECK(0 == 0); CHECK_TEXT(0 == 0, "Shouldn't fail"); CHECK_TRUE(0 == 0); CHECK_TRUE_TEXT(0 == 0, "Shouldn't fail"); CHECK_FALSE(0 != 0); CHECK_FALSE_TEXT(0 != 0, "Shouldn't fail"); LONGS_EQUAL(1,1); LONGS_EQUAL_TEXT(1, 1, "Shouldn't fail"); BYTES_EQUAL(0xab,0xab); BYTES_EQUAL_TEXT(0xab, 0xab, "Shouldn't fail"); CHECK_EQUAL(100,100); CHECK_EQUAL_TEXT(100, 100, "Shouldn't fail"); CHECK_EQUAL_ZERO(0); CHECK_EQUAL_ZERO_TEXT(0, "Shouldn't fail"); STRCMP_EQUAL("THIS", "THIS"); STRCMP_EQUAL_TEXT("THIS", "THIS", "Shouldn't fail"); DOUBLES_EQUAL(1.0, 1.0, .01); DOUBLES_EQUAL_TEXT(1.0, 1.0, .01, "Shouldn't fail"); POINTERS_EQUAL(NULLPTR, NULLPTR); POINTERS_EQUAL_TEXT(NULLPTR, NULLPTR, "Shouldn't fail"); MEMCMP_EQUAL("THIS", "THIS", 5); MEMCMP_EQUAL_TEXT("THIS", "THIS", 5, "Shouldn't fail"); BITS_EQUAL(0x01, (unsigned char )0x01, 0xFF); BITS_EQUAL(0x0001, (unsigned short )0x0001, 0xFFFF); BITS_EQUAL(0x00000001, (unsigned long )0x00000001, 0xFFFFFFFF); BITS_EQUAL_TEXT(0x01, (unsigned char )0x01, 0xFF, "Shouldn't fail"); return 0; } TEST(UnitTestMacros, allMacrosFromFunctionThatReturnsAValue) { functionThatReturnsAValue(); } TEST(UnitTestMacros, MEMCMP_EQUALBehavesAsAProperMacro) { if (false) MEMCMP_EQUAL("TEST", "test", 5); else MEMCMP_EQUAL("TEST", "TEST", 5); } IGNORE_TEST(UnitTestMacros, MEMCMP_EQUALWorksInAnIgnoredTest) { MEMCMP_EQUAL("TEST", "test", 5); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void MEMCMP_EQUALFailingTestMethodWithUnequalInput_() { unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 }; MEMCMP_EQUAL(expectedData, actualData, sizeof(expectedData)); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, MEMCMP_EQUALFailureWithUnequalInput) { fixture.runTestWithMethod(MEMCMP_EQUALFailingTestMethodWithUnequalInput_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <00 01 02 03>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <00 01 03 03>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 2"); } static void MEMCMP_EQUALFailingTestMethodWithNullExpected_() { unsigned char actualData[] = { 0x00, 0x01, 0x02, 0x03 }; MEMCMP_EQUAL(NULLPTR, actualData, sizeof(actualData)); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, MEMCMP_EQUALFailureWithNullExpected) { fixture.runTestWithMethod(MEMCMP_EQUALFailingTestMethodWithNullExpected_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <00 01 02 03>"); } static void MEMCMP_EQUALFailingTestMethodWithNullActual_() { unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; MEMCMP_EQUAL(expectedData, NULLPTR, sizeof(expectedData)); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, MEMCMP_EQUALFailureWithNullActual) { fixture.runTestWithMethod(MEMCMP_EQUALFailingTestMethodWithNullActual_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <00 01 02 03>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>"); } TEST(UnitTestMacros, MEMCMP_EQUALNullExpectedNullActual) { MEMCMP_EQUAL(NULLPTR, NULLPTR, 0); MEMCMP_EQUAL(NULLPTR, NULLPTR, 1024); } TEST(UnitTestMacros, MEMCMP_EQUALNullPointerIgnoredInExpectationWhenSize0) { unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 }; MEMCMP_EQUAL(NULLPTR, actualData, 0); } TEST(UnitTestMacros, MEMCMP_EQUALNullPointerIgnoredInActualWhenSize0) { unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; MEMCMP_EQUAL(expectedData, NULLPTR, 0); } static void failingTestMethodWithMEMCMP_EQUAL_TEXT_() { unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 }; MEMCMP_EQUAL_TEXT(expectedData, actualData, sizeof(expectedData), "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithMEMCMP_EQUAL_TEXT) { fixture.runTestWithMethod(failingTestMethodWithMEMCMP_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <00 01 02 03>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <00 01 03 03>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 2"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, MEMCMP_EQUAL_TEXTBehavesAsAProperMacro) { if (false) MEMCMP_EQUAL_TEXT("TEST", "test", 5, "Failed because it failed"); else MEMCMP_EQUAL_TEXT("TEST", "TEST", 5, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, MEMCMP_EQUAL_TEXTWorksInAnIgnoredTest) { MEMCMP_EQUAL_TEXT("TEST", "test", 5, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, BITS_EQUALBehavesAsAProperMacro) { if (false) BITS_EQUAL(0x00, 0xFF, 0xFF); else BITS_EQUAL(0x00, 0x00, 0xFF); } IGNORE_TEST(UnitTestMacros, BITS_EQUALWorksInAnIgnoredTest) { BITS_EQUAL(0x00, 0xFF, 0xFF); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void BITS_EQUALFailingTestMethodWithUnequalInput_() { BITS_EQUAL(0x00, 0xFF, 0xFF); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, BITS_EQUALFailureWithUnequalInput) { fixture.runTestWithMethod(BITS_EQUALFailingTestMethodWithUnequalInput_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("00000000>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("11111111>"); } TEST(UnitTestMacros, BITS_EQUALZeroMaskEqual) { BITS_EQUAL(0x00, 0xFF, 0x00); } static void failingTestMethodWithBITS_EQUAL_TEXT_() { BITS_EQUAL_TEXT(0x00, 0xFFFFFFFF, 0xFF, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithBITS_EQUAL_TEXT) { fixture.runTestWithMethod(failingTestMethodWithBITS_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <xxxxxxxx xxxxxxxx xxxxxxxx 00000000>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <xxxxxxxx xxxxxxxx xxxxxxxx 11111111>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, BITS_EQUAL_TEXTBehavesAsAProperMacro) { if (false) BITS_EQUAL_TEXT(0x00, 0xFF, 0xFF, "Failed because it failed"); else BITS_EQUAL_TEXT(0x00, 0x00, 0xFF, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, BITS_EQUAL_TEXTWorksInAnIgnoredTest) { BITS_EQUAL_TEXT(0x00, 0xFF, 0xFF, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE #if defined(__cplusplus) && __cplusplus >= 201103L enum class ScopedIntEnum { A, B }; static void ENUMS_EQUAL_INTWithScopedIntEnumTestMethod_() { ENUMS_EQUAL_INT(ScopedIntEnum::B, ScopedIntEnum::B); ENUMS_EQUAL_INT(ScopedIntEnum::B, ScopedIntEnum::A); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestENUMS_EQUAL_INTWithScopedIntEnum) { fixture.runTestWithMethod(ENUMS_EQUAL_INTWithScopedIntEnumTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); } TEST(UnitTestMacros, ENUMS_EQUAL_INTWithScopedIntEnumBehavesAsProperMacro) { if (false) ENUMS_EQUAL_INT(ScopedIntEnum::B, ScopedIntEnum::A); else ENUMS_EQUAL_INT(ScopedIntEnum::B, ScopedIntEnum::B); } IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_INTWithScopedIntEnumWorksInAnIgnoredTest) { ENUMS_EQUAL_INT(ScopedIntEnum::B, ScopedIntEnum::A); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void ENUMS_EQUAL_INT_TEXTWithScopedIntEnumTestMethod_() { ENUMS_EQUAL_INT_TEXT(ScopedIntEnum::B, ScopedIntEnum::A, "Failed because it failed"); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestENUMS_EQUAL_INT_TEXTWithScopedIntEnum) { fixture.runTestWithMethod(ENUMS_EQUAL_INT_TEXTWithScopedIntEnumTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, ENUMS_EQUAL_INT_TEXTWithScopedIntEnumBehavesAsProperMacro) { if (false) ENUMS_EQUAL_INT_TEXT(ScopedIntEnum::B, ScopedIntEnum::A, "Failed because it failed"); else ENUMS_EQUAL_INT_TEXT(ScopedIntEnum::B, ScopedIntEnum::B, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_EQUAL_INT_TEXTWithScopedIntEnumWorksInAnIgnoredTest) { ENUMS_EQUAL_INT_TEXT(ScopedIntEnum::B, ScopedIntEnum::A, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE enum class ScopedLongEnum : long { A, B }; static void ENUMS_EQUAL_TYPEWithScopedLongEnumTestMethod_() { ENUMS_EQUAL_TYPE(long, ScopedLongEnum::B, ScopedLongEnum::B); ENUMS_EQUAL_TYPE(long, ScopedLongEnum::B, ScopedLongEnum::A); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestENUMS_EQUAL_TYPEWithScopedLongEnum) { fixture.runTestWithMethod(ENUMS_EQUAL_TYPEWithScopedLongEnumTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); } TEST(UnitTestMacros, ENUMS_EQUAL_TYPEWithScopedLongEnumBehavesAsProperMacro) { if (false) ENUMS_EQUAL_TYPE(long, ScopedLongEnum::B, ScopedLongEnum::A); else ENUMS_EQUAL_TYPE(long, ScopedLongEnum::B, ScopedLongEnum::B); } IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_TYPEWithScopedLongEnumWorksInAnIgnoredTest) { ENUMS_EQUAL_TYPE(long, ScopedLongEnum::B, ScopedLongEnum::A); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void ENUMS_EQUAL_TYPE_TEXTWithScopedLongEnumTestMethod_() { ENUMS_EQUAL_TYPE_TEXT(long, ScopedLongEnum::B, ScopedLongEnum::A, "Failed because it failed"); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestENUMS_EQUAL_TYPE_TEXTWithScopedLongEnum) { fixture.runTestWithMethod(ENUMS_EQUAL_TYPE_TEXTWithScopedLongEnumTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, ENUMS_EQUAL_TYPE_TEXTWithScopedLongEnumBehavesAsProperMacro) { if (false) ENUMS_EQUAL_TYPE_TEXT(long, ScopedLongEnum::B, ScopedLongEnum::A, "Failed because it failed"); else ENUMS_EQUAL_TYPE_TEXT(long, ScopedLongEnum::B, ScopedLongEnum::B, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_EQUAL_TYPE_TEXTWithScopedLongEnumWorksInAnIgnoredTest) { ENUMS_EQUAL_TYPE_TEXT(long, ScopedLongEnum::B, ScopedLongEnum::A, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE #endif enum UnscopedEnum { UNSCOPED_ENUM_A, UNSCOPED_ENUM_B }; static void ENUMS_EQUAL_INTWithUnscopedEnumTestMethod_() { ENUMS_EQUAL_INT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_B); ENUMS_EQUAL_INT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestENUMS_EQUAL_INTWithUnscopedEnum) { fixture.runTestWithMethod(ENUMS_EQUAL_INTWithUnscopedEnumTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); } TEST(UnitTestMacros, ENUMS_EQUAL_INTWithUnscopedEnumBehavesAsProperMacro) { if (false) ENUMS_EQUAL_INT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A); else ENUMS_EQUAL_INT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_B); } IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_INTWithUnscopedEnumWorksInAnIgnoredTest) { ENUMS_EQUAL_INT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void ENUMS_EQUAL_INT_TEXTWithUnscopedEnumTestMethod_() { ENUMS_EQUAL_INT_TEXT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A, "Failed because it failed"); } // LCOV_EXCL_LINE TEST(UnitTestMacros, TestENUMS_EQUAL_INT_TEXTWithUnscopedEnum) { fixture.runTestWithMethod(ENUMS_EQUAL_INT_TEXTWithUnscopedEnumTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestMacros, ENUMS_EQUAL_INT_TEXTWithUnscopedEnumBehavesAsProperMacro) { if (false) ENUMS_EQUAL_INT_TEXT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A, "Failed because it failed"); else ENUMS_EQUAL_INT_TEXT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_B, "Failed because it failed"); } IGNORE_TEST(UnitTestMacros, ENUMS_EQUAL_EQUAL_INT_TEXTWithUnscopedEnumWorksInAnIgnoredTest) { ENUMS_EQUAL_INT_TEXT(UNSCOPED_ENUM_B, UNSCOPED_ENUM_A, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE #if CPPUTEST_HAVE_EXCEPTIONS static void failingTestMethod_NoThrowWithCHECK_THROWS_() { CHECK_THROWS(int, (void) (1+2)); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_THROWS_whenDoesntThrow) { fixture.runTestWithMethod(failingTestMethod_NoThrowWithCHECK_THROWS_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected to throw int"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but threw nothing"); LONGS_EQUAL(1, fixture.getCheckCount()); } static void succeedingTestMethod_CorrectThrowWithCHECK_THROWS_() { CHECK_THROWS(int, throw 4); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } TEST(UnitTestMacros, SuccessWithCHECK_THROWS) { fixture.runTestWithMethod(succeedingTestMethod_CorrectThrowWithCHECK_THROWS_); LONGS_EQUAL(1, fixture.getCheckCount()); } static void failingTestMethod_WrongThrowWithCHECK_THROWS_() { CHECK_THROWS(int, throw 4.3); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestMacros, FailureWithCHECK_THROWS_whenWrongThrow) { fixture.runTestWithMethod(failingTestMethod_WrongThrowWithCHECK_THROWS_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected to throw int"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but threw a different type"); LONGS_EQUAL(1, fixture.getCheckCount()); } TEST(UnitTestMacros, MultipleCHECK_THROWS_inOneScope) { CHECK_THROWS(int, throw 4); CHECK_THROWS(int, throw 4); } #endif
null
19
cpp
cpputest
SimpleMutexTest.cpp
tests/CppUTest/SimpleMutexTest.cpp
null
/* * Copyright (c) 2014, Michael Feathers, James Grenning, Bas Vodde and Chen YewMing * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/SimpleMutex.h" #include "CppUTest/PlatformSpecificFunctions.h" static int mutexCreateCount = 0; static int mutexLockCount = 0; static int mutexUnlockCount = 0; static int mutexDestroyCount = 0; static PlatformSpecificMutex StubMutexCreate(void) { mutexCreateCount++; return NULLPTR; } static void StubMutexLock(PlatformSpecificMutex) { mutexLockCount++; } static void StubMutexUnlock(PlatformSpecificMutex) { mutexUnlockCount++; } static void StubMutexDestroy(PlatformSpecificMutex) { mutexDestroyCount++; } TEST_GROUP(SimpleMutexTest) { void setup() CPPUTEST_OVERRIDE { UT_PTR_SET(PlatformSpecificMutexCreate, StubMutexCreate); UT_PTR_SET(PlatformSpecificMutexLock, StubMutexLock); UT_PTR_SET(PlatformSpecificMutexUnlock, StubMutexUnlock); UT_PTR_SET(PlatformSpecificMutexDestroy, StubMutexDestroy); mutexCreateCount = 0; mutexDestroyCount = 0; mutexLockCount = 0; mutexUnlockCount = 0; } void teardown() CPPUTEST_OVERRIDE { } }; TEST(SimpleMutexTest, CreateAndDestroy) { { SimpleMutex mtx; } CHECK_EQUAL(1, mutexCreateCount); CHECK_EQUAL(1, mutexDestroyCount); CHECK_EQUAL(0, mutexLockCount); CHECK_EQUAL(0, mutexUnlockCount); } TEST(SimpleMutexTest, LockUnlockTest) { { SimpleMutex mtx; mtx.Lock(); mtx.Unlock(); } CHECK_EQUAL(1, mutexCreateCount); CHECK_EQUAL(1, mutexLockCount); CHECK_EQUAL(1, mutexUnlockCount); CHECK_EQUAL(1, mutexDestroyCount); }
null
20
cpp
cpputest
TestMemoryAllocatorTest.cpp
tests/CppUTest/TestMemoryAllocatorTest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestMemoryAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTest/MemoryLeakDetector.h" TEST_GROUP(TestMemoryAllocatorTest) { TestMemoryAllocator* allocator; GlobalMemoryAllocatorStash memoryAllocatorStash; void setup() CPPUTEST_OVERRIDE { allocator = NULLPTR; memoryAllocatorStash.save(); } void teardown() CPPUTEST_OVERRIDE { memoryAllocatorStash.restore(); delete allocator; } }; TEST(TestMemoryAllocatorTest, SetCurrentNewAllocator) { allocator = new TestMemoryAllocator("new allocator for test"); setCurrentNewAllocator(allocator); POINTERS_EQUAL(allocator, getCurrentNewAllocator()); } TEST(TestMemoryAllocatorTest, SetCurrentNewAllocatorToDefault) { TestMemoryAllocator* originalAllocator = getCurrentNewAllocator(); setCurrentNewAllocatorToDefault(); POINTERS_EQUAL(defaultNewAllocator(), getCurrentNewAllocator()); setCurrentNewAllocator(originalAllocator); } TEST(TestMemoryAllocatorTest, SetCurrentNewArrayAllocator) { allocator = new TestMemoryAllocator("new array allocator for test"); setCurrentNewArrayAllocator(allocator); POINTERS_EQUAL(allocator, getCurrentNewArrayAllocator()); setCurrentNewArrayAllocatorToDefault(); POINTERS_EQUAL(defaultNewArrayAllocator(), getCurrentNewArrayAllocator()); } TEST(TestMemoryAllocatorTest, SetCurrentMallocAllocator) { allocator = new TestMemoryAllocator("malloc_allocator"); setCurrentMallocAllocator(allocator); POINTERS_EQUAL(allocator, getCurrentMallocAllocator()); setCurrentMallocAllocatorToDefault(); POINTERS_EQUAL(defaultMallocAllocator(), getCurrentMallocAllocator()); } TEST(TestMemoryAllocatorTest, MemoryAllocation) { allocator = new TestMemoryAllocator(); allocator->free_memory(allocator->alloc_memory(100, "file", 1), 100, "file", 1); } TEST(TestMemoryAllocatorTest, MallocNames) { STRCMP_EQUAL("Standard Malloc Allocator", defaultMallocAllocator()->name()); STRCMP_EQUAL("malloc", defaultMallocAllocator()->alloc_name()); STRCMP_EQUAL("free", defaultMallocAllocator()->free_name()); } TEST(TestMemoryAllocatorTest, NewNames) { STRCMP_EQUAL("Standard New Allocator", defaultNewAllocator()->name()); STRCMP_EQUAL("new", defaultNewAllocator()->alloc_name()); STRCMP_EQUAL("delete", defaultNewAllocator()->free_name()); } TEST(TestMemoryAllocatorTest, NewArrayNames) { STRCMP_EQUAL("Standard New [] Allocator", defaultNewArrayAllocator()->name()); STRCMP_EQUAL("new []", defaultNewArrayAllocator()->alloc_name()); STRCMP_EQUAL("delete []", defaultNewArrayAllocator()->free_name()); } TEST(TestMemoryAllocatorTest, NullUnknownAllocation) { allocator = new NullUnknownAllocator; allocator->free_memory(allocator->alloc_memory(100, "file", 1), 100, "file", 1); } TEST(TestMemoryAllocatorTest, NullUnknownNames) { allocator = new NullUnknownAllocator; STRCMP_EQUAL("Null Allocator", allocator->name()); STRCMP_EQUAL("unknown", allocator->alloc_name()); STRCMP_EQUAL("unknown", allocator->free_name()); } #if (! CPPUTEST_SANITIZE_ADDRESS) #define MAX_SIZE_FOR_ALLOC ((size_t) -1 > (unsigned short)-1) ? (size_t)(-97) : (size_t)(-1) static void failTryingToAllocateTooMuchMemory(void) { TestMemoryAllocator allocator; allocator.alloc_memory(MAX_SIZE_FOR_ALLOC, "file", 1); } // LCOV_EXCL_LINE TEST(TestMemoryAllocatorTest, TryingToAllocateTooMuchFailsTest) { TestTestingFixture fixture; fixture.setTestFunction(&failTryingToAllocateTooMuchMemory); fixture.runAllTests(); fixture.assertPrintContains("malloc returned null pointer"); } #endif TEST_GROUP(MemoryLeakAllocator) { MemoryLeakAllocator* allocator; void setup() CPPUTEST_OVERRIDE { allocator = new MemoryLeakAllocator(defaultMallocAllocator()); } void teardown() CPPUTEST_OVERRIDE { delete allocator; } }; TEST(MemoryLeakAllocator, allocMemory) { char* memory = allocator->alloc_memory(10, __FILE__, __LINE__); memory[0] = 'B'; MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(allocator->actualAllocator(), memory); /* No leaks or crashes */ } TEST(MemoryLeakAllocator, freeMemory) { char* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(allocator->actualAllocator(), 10); allocator->free_memory(memory, 10, __FILE__, __LINE__); /* No leaks or crashes */ } TEST(MemoryLeakAllocator, originalAllocator) { POINTERS_EQUAL(defaultMallocAllocator(), allocator->actualAllocator()); STRCMP_EQUAL(defaultMallocAllocator()->alloc_name(), allocator->alloc_name()); STRCMP_EQUAL(defaultMallocAllocator()->free_name(), allocator->free_name()); } TEST(MemoryLeakAllocator, name) { STRCMP_EQUAL("MemoryLeakAllocator", allocator->name()); } #if CPPUTEST_USE_MEM_LEAK_DETECTION #if CPPUTEST_USE_MALLOC_MACROS class FailableMemoryAllocatorExecFunction : public ExecFunction { public: FailableMemoryAllocator* allocator_; void (*testFunction_)(FailableMemoryAllocator*); void exec() CPPUTEST_OVERRIDE { testFunction_(allocator_); } FailableMemoryAllocatorExecFunction() : allocator_(NULLPTR), testFunction_(NULLPTR) {} virtual ~FailableMemoryAllocatorExecFunction() CPPUTEST_DESTRUCTOR_OVERRIDE {} }; TEST_GROUP(FailableMemoryAllocator) { FailableMemoryAllocator *failableMallocAllocator; FailableMemoryAllocatorExecFunction testFunction; TestTestingFixture fixture; GlobalMemoryAllocatorStash stash; void setup() CPPUTEST_OVERRIDE { stash.save(); testFunction.allocator_ = failableMallocAllocator = new FailableMemoryAllocator("Failable Malloc Allocator", "malloc", "free"); fixture.setTestFunction(&testFunction); setCurrentMallocAllocator(failableMallocAllocator); } void teardown() CPPUTEST_OVERRIDE { failableMallocAllocator->checkAllFailedAllocsWereDone(); failableMallocAllocator->clearFailedAllocs(); delete failableMallocAllocator; stash.restore(); } }; TEST(FailableMemoryAllocator, MallocWorksNormallyIfNotAskedToFail) { int *memory = (int*)malloc(sizeof(int)); CHECK(memory != NULLPTR); free(memory); } TEST(FailableMemoryAllocator, FailFirstMalloc) { failableMallocAllocator->failAllocNumber(1); POINTERS_EQUAL(NULLPTR, (int*)malloc(sizeof(int))); } TEST(FailableMemoryAllocator, FailSecondAndFourthMalloc) { failableMallocAllocator->failAllocNumber(2); failableMallocAllocator->failAllocNumber(4); int *memory1 = (int*)malloc(sizeof(int)); int *memory2 = (int*)malloc(sizeof(int)); int *memory3 = (int*)malloc(sizeof(int)); int *memory4 = (int*)malloc(sizeof(int)); CHECK(NULLPTR != memory1); POINTERS_EQUAL(NULLPTR, memory2); CHECK(NULLPTR != memory3); POINTERS_EQUAL(NULLPTR, memory4); free(memory1); free(memory3); } static void failingAllocIsNeverDone_(FailableMemoryAllocator* failableMallocAllocator) { failableMallocAllocator->failAllocNumber(1); failableMallocAllocator->failAllocNumber(2); failableMallocAllocator->failAllocNumber(3); malloc(sizeof(int)); malloc(sizeof(int)); failableMallocAllocator->checkAllFailedAllocsWereDone(); } TEST(FailableMemoryAllocator, CheckAllFailingAllocsWereDone) { testFunction.testFunction_ = failingAllocIsNeverDone_; fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); fixture.assertPrintContains("Expected allocation number 3 was never done"); failableMallocAllocator->clearFailedAllocs(); } TEST(FailableMemoryAllocator, FailFirstAllocationAtGivenLine) { failableMallocAllocator->failNthAllocAt(1, __FILE__, __LINE__ + 2); POINTERS_EQUAL(NULLPTR, malloc(sizeof(int))); } TEST(FailableMemoryAllocator, FailThirdAllocationAtGivenLine) { int *memory[10] = { NULLPTR }; int allocation; failableMallocAllocator->failNthAllocAt(3, __FILE__, __LINE__ + 4); for (allocation = 1; allocation <= 10; allocation++) { memory[allocation - 1] = (int *)malloc(sizeof(int)); if (memory[allocation - 1] == NULLPTR) break; free(memory[allocation -1]); } LONGS_EQUAL(3, allocation); } static void failingLocationAllocIsNeverDone_(FailableMemoryAllocator* failableMallocAllocator) { failableMallocAllocator->failNthAllocAt(1, "TestMemoryAllocatorTest.cpp", __LINE__); failableMallocAllocator->checkAllFailedAllocsWereDone(); } TEST(FailableMemoryAllocator, CheckAllFailingLocationAllocsWereDone) { testFunction.testFunction_ = failingLocationAllocIsNeverDone_; fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); fixture.assertPrintContains("Expected failing alloc at TestMemoryAllocatorTest.cpp:"); fixture.assertPrintContains("was never done"); failableMallocAllocator->clearFailedAllocs(); } #endif #endif class MemoryAccountantExecFunction : public ExecFunction { public: virtual ~MemoryAccountantExecFunction() CPPUTEST_DESTRUCTOR_OVERRIDE { } void (*testFunction_)(MemoryAccountant*); MemoryAccountant* parameter_; virtual void exec() CPPUTEST_OVERRIDE { testFunction_(parameter_); } }; TEST_GROUP(TestMemoryAccountant) { MemoryAccountant accountant; TestTestingFixture fixture; MemoryAccountantExecFunction testFunction; void setup() CPPUTEST_OVERRIDE { testFunction.parameter_ = &accountant; fixture.setTestFunction(&testFunction); } void teardown() CPPUTEST_OVERRIDE { accountant.clear(); } }; TEST(TestMemoryAccountant, totalAllocsIsZero) { LONGS_EQUAL(0, accountant.totalAllocations()); LONGS_EQUAL(0, accountant.totalDeallocations()); } TEST(TestMemoryAccountant, countAllocationsPerSize) { accountant.alloc(4); LONGS_EQUAL(1, accountant.totalAllocationsOfSize(4)); LONGS_EQUAL(0, accountant.totalAllocationsOfSize(10)); LONGS_EQUAL(1, accountant.totalAllocations()); LONGS_EQUAL(0, accountant.maximumAllocationAtATimeOfSize(10)); } TEST(TestMemoryAccountant, countAllocationsPerSizeMultipleAllocations) { accountant.alloc(4); accountant.alloc(4); accountant.alloc(8); LONGS_EQUAL(2, accountant.totalAllocationsOfSize(4)); LONGS_EQUAL(1, accountant.totalAllocationsOfSize(8)); LONGS_EQUAL(0, accountant.totalAllocationsOfSize(10)); LONGS_EQUAL(3, accountant.totalAllocations()); } TEST(TestMemoryAccountant, countAllocationsPerSizeMultipleAllocationsOutOfOrder) { accountant.alloc(4); accountant.alloc(8); accountant.alloc(4); accountant.alloc(5); accountant.alloc(2); accountant.alloc(4); accountant.alloc(10); LONGS_EQUAL(3, accountant.totalAllocationsOfSize(4)); LONGS_EQUAL(1, accountant.totalAllocationsOfSize(8)); LONGS_EQUAL(1, accountant.totalAllocationsOfSize(10)); LONGS_EQUAL(7, accountant.totalAllocations()); } TEST(TestMemoryAccountant, countDeallocationsPerSizeMultipleAllocations) { accountant.dealloc(8); accountant.dealloc(4); accountant.dealloc(8); LONGS_EQUAL(1, accountant.totalDeallocationsOfSize(4)); LONGS_EQUAL(2, accountant.totalDeallocationsOfSize(8)); LONGS_EQUAL(0, accountant.totalDeallocationsOfSize(20)); LONGS_EQUAL(3, accountant.totalDeallocations()); } TEST(TestMemoryAccountant, countMaximumAllocationsAtATime) { accountant.alloc(4); accountant.alloc(4); accountant.dealloc(4); accountant.dealloc(4); accountant.alloc(4); LONGS_EQUAL(2, accountant.maximumAllocationAtATimeOfSize(4)); } TEST(TestMemoryAccountant, reportNoAllocations) { STRCMP_EQUAL("CppUTest Memory Accountant has not noticed any allocations or deallocations. Sorry\n", accountant.report().asCharString()); } TEST(TestMemoryAccountant, reportAllocations) { accountant.dealloc(8); accountant.dealloc(8); accountant.dealloc(8); accountant.alloc(4); accountant.dealloc(4); accountant.alloc(4); STRCMP_EQUAL("CppUTest Memory Accountant report:\n" "Allocation size # allocations # deallocations max # allocations at one time\n" " 4 2 1 1\n" " 8 0 3 0\n" " Thank you for your business\n" , accountant.report().asCharString()); } TEST(TestMemoryAccountant, reportAllocationsWithSizeZero) { accountant.dealloc(0); accountant.dealloc(4); accountant.dealloc(4); accountant.alloc(4); STRCMP_EQUAL("CppUTest Memory Accountant report:\n" "Allocation size # allocations # deallocations max # allocations at one time\n" "other 0 1 0\n" " 4 1 2 1\n" " Thank you for your business\n" , accountant.report().asCharString()); } static void failUseCacheSizesAfterAllocation_(MemoryAccountant* accountant) { size_t cacheSizes[] = {0}; accountant->alloc(4); accountant->useCacheSizes(cacheSizes, 1); } TEST(TestMemoryAccountant, withCacheSizesFailsWhenAlreadyAllocatedMemory) { testFunction.testFunction_ = failUseCacheSizesAfterAllocation_; fixture.runAllTests(); fixture.assertPrintContains("MemoryAccountant: Cannot set cache sizes as allocations already occured!"); } TEST(TestMemoryAccountant, reportWithCacheSizesEmpty) { size_t cacheSizes[] = {0}; accountant.useCacheSizes(cacheSizes, 0); accountant.alloc(4); STRCMP_EQUAL("CppUTest Memory Accountant report (with cache sizes):\n" "Cache size # allocations # deallocations max # allocations at one time\n" "other 1 0 1\n" " Thank you for your business\n" , accountant.report().asCharString()); } TEST(TestMemoryAccountant, reportWithCacheSizes) { size_t cacheSizes[] = {4}; accountant.useCacheSizes(cacheSizes, 1); accountant.dealloc(8); accountant.dealloc(12); accountant.dealloc(20); accountant.alloc(4); accountant.dealloc(4); accountant.alloc(4); STRCMP_EQUAL("CppUTest Memory Accountant report (with cache sizes):\n" "Cache size # allocations # deallocations max # allocations at one time\n" " 4 2 1 1\n" "other 0 3 0\n" " Thank you for your business\n" , accountant.report().asCharString()); } TEST(TestMemoryAccountant, reportWithCacheSizesMultipleCaches) { size_t cacheSizes[] = {4, 10, 20}; accountant.useCacheSizes(cacheSizes, 3); accountant.alloc(8); accountant.alloc(12); accountant.alloc(20); accountant.alloc(4); accountant.dealloc(4); accountant.alloc(4); STRCMP_EQUAL("CppUTest Memory Accountant report (with cache sizes):\n" "Cache size # allocations # deallocations max # allocations at one time\n" " 4 2 1 1\n" " 10 1 0 1\n" " 20 2 0 2\n" "other 0 0 0\n" " Thank you for your business\n" , accountant.report().asCharString()); } TEST_GROUP(AccountingTestMemoryAllocator) { MemoryAccountant accountant; AccountingTestMemoryAllocator *allocator; void setup() CPPUTEST_OVERRIDE { allocator = new AccountingTestMemoryAllocator(accountant, getCurrentMallocAllocator()); } void teardown() CPPUTEST_OVERRIDE { accountant.clear(); delete allocator; } }; TEST(AccountingTestMemoryAllocator, canAllocateAndAccountMemory) { char* memory = allocator->alloc_memory(10, __FILE__, __LINE__); allocator->free_memory(memory, 10, __FILE__, __LINE__); LONGS_EQUAL(1, accountant.totalAllocationsOfSize(10)); LONGS_EQUAL(1, accountant.totalDeallocationsOfSize(10)); } TEST(AccountingTestMemoryAllocator, canAllocateAndAccountMemoryMultipleAllocations) { char* memory1 = allocator->alloc_memory(10, __FILE__, __LINE__); char* memory2 = allocator->alloc_memory(8, __FILE__, __LINE__); char* memory3 = allocator->alloc_memory(12, __FILE__, __LINE__); allocator->free_memory(memory1, 10, __FILE__, __LINE__); allocator->free_memory(memory3, 12, __FILE__, __LINE__); char* memory4 = allocator->alloc_memory(15, __FILE__, __LINE__); char* memory5 = allocator->alloc_memory(20, __FILE__, __LINE__); allocator->free_memory(memory2, 8, __FILE__, __LINE__); allocator->free_memory(memory4, 15, __FILE__, __LINE__); allocator->free_memory(memory5, 20, __FILE__, __LINE__); char* memory6 = allocator->alloc_memory(1, __FILE__, __LINE__); char* memory7 = allocator->alloc_memory(100, __FILE__, __LINE__); allocator->free_memory(memory6, 1, __FILE__, __LINE__); allocator->free_memory(memory7, 100, __FILE__, __LINE__); LONGS_EQUAL(7, accountant.totalAllocations()); LONGS_EQUAL(7, accountant.totalDeallocations()); } TEST(AccountingTestMemoryAllocator, useOriginalAllocatorWhenDeallocatingMemoryNotAllocatedByAllocator) { char* memory = getCurrentMallocAllocator()->alloc_memory(10, __FILE__, __LINE__); allocator->free_memory(memory, 10, __FILE__, __LINE__); LONGS_EQUAL(0, accountant.totalAllocations()); LONGS_EQUAL(1, accountant.totalDeallocations()); } TEST(AccountingTestMemoryAllocator, allocatorForwardsAllocAndFreeName) { STRCMP_EQUAL("malloc", allocator->alloc_name()); STRCMP_EQUAL("free", allocator->free_name()); } class GlobalMemoryAccountantExecFunction : public ExecFunction { public: void (*testFunction_)(GlobalMemoryAccountant*); GlobalMemoryAccountant* parameter_; virtual void exec() CPPUTEST_OVERRIDE { testFunction_(parameter_); } }; TEST_GROUP(GlobalMemoryAccountant) { GlobalMemoryAccountant accountant; TestTestingFixture fixture; GlobalMemoryAccountantExecFunction testFunction; GlobalMemoryAllocatorStash stash; void setup() CPPUTEST_OVERRIDE { testFunction.parameter_ = &accountant; fixture.setTestFunction(&testFunction); stash.save(); } void teardown() CPPUTEST_OVERRIDE { stash.restore(); } }; TEST(GlobalMemoryAccountant, start) { accountant.start(); POINTERS_EQUAL(accountant.getMallocAllocator(), getCurrentMallocAllocator()); POINTERS_EQUAL(accountant.getNewAllocator(), getCurrentNewAllocator()); POINTERS_EQUAL(accountant.getNewArrayAllocator(), getCurrentNewArrayAllocator()); accountant.stop(); } TEST(GlobalMemoryAccountant, stop) { TestMemoryAllocator* originalMallocAllocator = getCurrentMallocAllocator(); TestMemoryAllocator* originalNewAllocator = getCurrentNewAllocator(); TestMemoryAllocator* originalNewArrayAllocator = getCurrentNewArrayAllocator(); accountant.start(); accountant.stop(); POINTERS_EQUAL(originalMallocAllocator, getCurrentMallocAllocator()); POINTERS_EQUAL(originalNewAllocator, getCurrentNewAllocator()); POINTERS_EQUAL(originalNewArrayAllocator, getCurrentNewArrayAllocator()); } #if CPPUTEST_USE_MEM_LEAK_DETECTION TEST(GlobalMemoryAccountant, report) { accountant.start(); char* memory = new char[185]; delete [] memory; accountant.stop(); /* Allocation includes memory leak info */ STRCMP_CONTAINS("1 1 1", accountant.report().asCharString()); } TEST(GlobalMemoryAccountant, reportWithCacheSizes) { size_t cacheSizes[] = {512}; accountant.useCacheSizes(cacheSizes, 1); accountant.start(); char* memory = new char[185]; delete [] memory; accountant.stop(); /* Allocation includes memory leak info */ STRCMP_CONTAINS("512 1 1 1", accountant.report().asCharString()); } #endif static void failStopWithoutStartingWillFail_(GlobalMemoryAccountant* accountant) { accountant->stop(); } TEST(GlobalMemoryAccountant, StopCantBeCalledWithoutStarting) { testFunction.testFunction_ = failStopWithoutStartingWillFail_; fixture.runAllTests(); fixture.assertPrintContains("GlobalMemoryAccount: Stop called without starting"); } static void failStartingTwiceWillFail_(GlobalMemoryAccountant* accountant) { accountant->start(); accountant->start(); } TEST(GlobalMemoryAccountant, startTwiceWillFail) { testFunction.testFunction_ = failStartingTwiceWillFail_; fixture.runAllTests(); accountant.stop(); fixture.assertPrintContains("Global allocator start called twice!"); } static void failChangeMallocMemoryAllocator_(GlobalMemoryAccountant* accountant) { accountant->start(); setCurrentMallocAllocator(defaultMallocAllocator()); accountant->stop(); } TEST(GlobalMemoryAccountant, checkWhetherMallocAllocatorIsNotChanged) { testFunction.testFunction_ = failChangeMallocMemoryAllocator_; fixture.runAllTests(); fixture.assertPrintContains("GlobalMemoryAccountant: Malloc memory allocator has been changed while accounting for memory"); } static void failChangeNewMemoryAllocator_(GlobalMemoryAccountant* accountant) { accountant->start(); setCurrentNewAllocator(defaultNewAllocator()); accountant->stop(); } TEST(GlobalMemoryAccountant, checkWhetherNewAllocatorIsNotChanged) { testFunction.testFunction_ = failChangeNewMemoryAllocator_; fixture.runAllTests(); fixture.assertPrintContains("GlobalMemoryAccountant: New memory allocator has been changed while accounting for memory"); } static void failChangeNewArrayMemoryAllocator_(GlobalMemoryAccountant* accountant) { accountant->start(); setCurrentNewArrayAllocator(defaultNewArrayAllocator()); accountant->stop(); } TEST(GlobalMemoryAccountant, checkWhetherNewArrayAllocatorIsNotChanged) { testFunction.testFunction_ = failChangeNewArrayMemoryAllocator_; fixture.runAllTests(); fixture.assertPrintContains("GlobalMemoryAccountant: New Array memory allocator has been changed while accounting for memory"); }
null
21
cpp
cpputest
SetPluginTest.cpp
tests/CppUTest/SetPluginTest.cpp
null
#include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" #include "CppUTest/TestOutput.h" #include "CppUTest/TestPlugin.h" static void orig_func1() { } static void stub_func1() { } static void orig_func2() { } static void stub_func2() { } static void (*fp1)(); static void (*fp2)(); TEST_GROUP(SetPointerPluginTest) { SetPointerPlugin* plugin_; TestRegistry* myRegistry_; StringBufferTestOutput* output_; TestResult* result_; void setup() CPPUTEST_OVERRIDE { myRegistry_ = new TestRegistry(); plugin_ = new SetPointerPlugin("TestSetPlugin"); myRegistry_->setCurrentRegistry(myRegistry_); myRegistry_->installPlugin(plugin_); output_ = new StringBufferTestOutput(); result_ = new TestResult(*output_); } void teardown() CPPUTEST_OVERRIDE { myRegistry_->setCurrentRegistry(NULLPTR); delete myRegistry_; delete plugin_; delete output_; delete result_; } }; class FunctionPointerUtest : public Utest { public: void setup() CPPUTEST_OVERRIDE { UT_PTR_SET(fp1, stub_func1); UT_PTR_SET(fp2, stub_func2); UT_PTR_SET(fp2, stub_func2); } void testBody() CPPUTEST_OVERRIDE { CHECK(fp1 == stub_func1); CHECK(fp2 == stub_func2); } }; class FunctionPointerUtestShell: public UtestShell { public: virtual Utest* createTest() CPPUTEST_OVERRIDE { return new FunctionPointerUtest(); } }; TEST(SetPointerPluginTest, installTwoFunctionPointer) { FunctionPointerUtestShell *tst = new FunctionPointerUtestShell(); 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()); LONGS_EQUAL(2, result_->getCheckCount()); delete tst; } class MaxFunctionPointerUtest : public Utest { public: int numOfFpSets; MaxFunctionPointerUtest(int num) : numOfFpSets(num) { } void setup() CPPUTEST_OVERRIDE { for (int i = 0; i < numOfFpSets; ++i) { UT_PTR_SET(fp1, stub_func1); } } }; class MaxFunctionPointerUtestShell: public UtestShell { public: int numOfFpSets; MaxFunctionPointerUtestShell(int num) : numOfFpSets(num) { } virtual Utest* createTest() CPPUTEST_OVERRIDE { return new MaxFunctionPointerUtest(numOfFpSets); } }; TEST(SetPointerPluginTest, installTooMuchFunctionPointer) { MaxFunctionPointerUtestShell *tst = new MaxFunctionPointerUtestShell(SetPointerPlugin::MAX_SET + 1); myRegistry_->addTest(tst); myRegistry_->runAllTests(*result_); LONGS_EQUAL(1, result_->getFailureCount()); delete tst; } static double orig_double = 3.0; static double* orig_double_ptr = &orig_double; static double stub_double = 4.0; class SetDoublePointerUtest : public Utest { public: void setup() CPPUTEST_OVERRIDE { UT_PTR_SET(orig_double_ptr, &stub_double); } void testBody() CPPUTEST_OVERRIDE { CHECK(orig_double_ptr == &stub_double); } }; class SetDoublePointerUtestShell: public UtestShell { public: Utest * createTest() CPPUTEST_OVERRIDE { return new SetDoublePointerUtest(); } }; TEST(SetPointerPluginTest, doublePointer) { SetDoublePointerUtestShell *doubletst = new SetDoublePointerUtestShell(); myRegistry_->addTest(doubletst); myRegistry_->runAllTests(*result_); CHECK(orig_double_ptr == &orig_double); LONGS_EQUAL(1, result_->getCheckCount()); delete doubletst; }
null
22
cpp
cpputest
MemoryLeakWarningTest.cpp
tests/CppUTest/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/TestMemoryAllocator.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTest/TestHarness_c.h" #include "CppUTest/SimpleMutex.h" #include "DummyMemoryLeakDetector.h" TEST_GROUP(MemoryLeakWarningLocalDetectorTest) { DummyMemoryLeakFailure dummy; }; TEST(MemoryLeakWarningLocalDetectorTest, localDetectorReturnsNewGlobalWhenNoneWasSet) { MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", NULLPTR); CHECK(NULLPTR != memoryLeakWarningPlugin.getMemoryLeakDetector()); } TEST(MemoryLeakWarningLocalDetectorTest, localDetectorIsTheOneSpecifiedInConstructor) { MemoryLeakDetector localDetector(&dummy); MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", &localDetector); POINTERS_EQUAL(&localDetector, memoryLeakWarningPlugin.getMemoryLeakDetector()); } TEST(MemoryLeakWarningLocalDetectorTest, localDetectorIsGlobalDetector) { MemoryLeakDetector* globalDetector = MemoryLeakWarningPlugin::getGlobalDetector(); MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", NULLPTR); MemoryLeakDetector* localDetector = memoryLeakWarningPlugin.getMemoryLeakDetector(); POINTERS_EQUAL(globalDetector, localDetector); } static char* leak1; static long* leak2; static MemoryLeakDetector* detector; static MemoryLeakWarningPlugin* memPlugin; static TestMemoryAllocator* allocator; TEST_GROUP(MemoryLeakWarningTest) { DummyMemoryLeakFailure dummy; TestTestingFixture* fixture; void setup() CPPUTEST_OVERRIDE { fixture = new TestTestingFixture(); detector = new MemoryLeakDetector(&dummy); allocator = new TestMemoryAllocator; memPlugin = new MemoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", detector); fixture->installPlugin(memPlugin); memPlugin->enable(); leak1 = NULLPTR; leak2 = NULLPTR; } void teardown() CPPUTEST_OVERRIDE { detector->deallocMemory(allocator, leak1); detector->deallocMemory(allocator, leak2); delete fixture; delete memPlugin; delete detector; delete allocator; } }; static void testTwoLeaks_() { leak1 = detector->allocMemory(allocator, 10); leak2 = (long*) (void*) detector->allocMemory(allocator, 4); } #if CPPUTEST_USE_MEM_LEAK_DETECTION TEST(MemoryLeakWarningTest, TwoLeaks) { fixture->setTestFunction(testTwoLeaks_); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); } #else TEST(MemoryLeakWarningTest, TwoLeaks) { fixture->setTestFunction(testTwoLeaks_); fixture->runAllTests(); LONGS_EQUAL(0, fixture->getFailureCount()); } #endif static void testLeakWarningWithPluginDisabled_() { memPlugin->expectLeaksInTest(1); leak1 = (char*) cpputest_malloc_location_with_leak_detection(10, __FILE__, __LINE__); } TEST(MemoryLeakWarningTest, LeakWarningWithPluginDisabled) { fixture->setTestFunction(testLeakWarningWithPluginDisabled_); MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); fixture->runAllTests(); LONGS_EQUAL(0, fixture->getFailureCount()); fixture->assertPrintContains("Warning: Expected 1 leak(s), but leak detection was disabled"); cpputest_free_location_with_leak_detection(leak1, __FILE__, __LINE__); leak1 = NULLPTR; MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); } static void testIgnore2_() { memPlugin->expectLeaksInTest(2); leak1 = detector->allocMemory(allocator, 10); leak2 = (long*) (void*) 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()); } static bool cpputestHasCrashed; TEST_GROUP(MemoryLeakWarningGlobalDetectorTest) { MemoryLeakDetector* detector; MemoryLeakFailure* failureReporter; DummyMemoryLeakDetector * dummyDetector; MemoryLeakFailure* dummyReporter; GlobalMemoryAllocatorStash memoryAllocatorStash; static void crashMethod() { cpputestHasCrashed = true; } void setup() CPPUTEST_OVERRIDE { memoryAllocatorStash.save(); detector = MemoryLeakWarningPlugin::getGlobalDetector(); failureReporter = MemoryLeakWarningPlugin::getGlobalFailureReporter(); MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); dummyReporter = new DummyMemoryLeakFailure; dummyDetector = new DummyMemoryLeakDetector(dummyReporter); UtestShell::setCrashMethod(crashMethod); cpputestHasCrashed = false; } void teardown() CPPUTEST_OVERRIDE { MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); if (!DummyMemoryLeakDetector::wasDeleted()) delete dummyDetector; if (!DummyMemoryLeakFailure::wasDeleted()) delete dummyReporter; MemoryLeakWarningPlugin::setGlobalDetector(detector, failureReporter); MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); UtestShell::resetCrashMethod(); memoryAllocatorStash.restore(); } }; TEST(MemoryLeakWarningGlobalDetectorTest, turnOffNewOverloadsCausesNoAdditionalLeaks) { size_t storedAmountOfLeaks = detector->totalMemoryLeaks(mem_leak_period_all); char* arrayMemory = new char[100]; char* nonArrayMemory = new char; char* mallocMemory = (char*) cpputest_malloc_location_with_leak_detection(10, "file", 10); char* reallocMemory = (char*) cpputest_realloc_location_with_leak_detection(NULLPTR, 10, "file", 10); LONGS_EQUAL(storedAmountOfLeaks, detector->totalMemoryLeaks(mem_leak_period_all)); cpputest_free_location_with_leak_detection(mallocMemory, "file", 10); cpputest_free_location_with_leak_detection(reallocMemory, "file", 10); delete [] arrayMemory; delete nonArrayMemory; } TEST(MemoryLeakWarningGlobalDetectorTest, destroyGlobalDetector) { MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter); MemoryLeakWarningPlugin::destroyGlobalDetector(); CHECK(DummyMemoryLeakDetector::wasDeleted()); CHECK(DummyMemoryLeakFailure::wasDeleted()); } TEST(MemoryLeakWarningGlobalDetectorTest, MemoryWarningPluginCanBeSetToDestroyTheGlobalDetector) { MemoryLeakWarningPlugin* plugin = new MemoryLeakWarningPlugin("dummy"); plugin->destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(true); MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter); delete plugin; CHECK(DummyMemoryLeakDetector::wasDeleted()); } #if CPPUTEST_USE_MEM_LEAK_DETECTION TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorNew) { MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter); MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); crash_on_allocation_number(1); char* memory = new char[100]; CHECK(cpputestHasCrashed); delete [] memory; MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); } TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorNewArray) { MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter); MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); crash_on_allocation_number(1); char* memory = new char; CHECK(cpputestHasCrashed); delete memory; MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); } TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorMalloc) { MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter); MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); crash_on_allocation_number(1); char* memory = (char*) cpputest_malloc(10); CHECK(cpputestHasCrashed); cpputest_free(memory); MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); } TEST(MemoryLeakWarningGlobalDetectorTest, gettingTheGlobalDetectorDoesNotRestoreTheMemoryLeakOverloadsWhenTheyWereAlreadyOff) { MemoryLeakWarningPlugin::setGlobalDetector(NULLPTR, NULLPTR); MemoryLeakDetector* temporaryDetector = MemoryLeakWarningPlugin::getGlobalDetector(); MemoryLeakFailure* temporaryReporter = MemoryLeakWarningPlugin::getGlobalFailureReporter(); MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); bool areNewDeleteOverloaded = MemoryLeakWarningPlugin::areNewDeleteOverloaded(); MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); CHECK(!areNewDeleteOverloaded); delete temporaryReporter; delete temporaryDetector; MemoryLeakWarningPlugin::setGlobalDetector(NULLPTR, NULLPTR); } TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOn) { MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); CHECK(MemoryLeakWarningPlugin::areNewDeleteOverloaded()); MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); } TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOff) { MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); bool areNewDeleteOverloaded = MemoryLeakWarningPlugin::areNewDeleteOverloaded(); MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); CHECK(!areNewDeleteOverloaded); } TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOnWithRestore) { MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); CHECK(MemoryLeakWarningPlugin::areNewDeleteOverloaded()); MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); } TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOffWithSaveDisable) { MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); CHECK(!MemoryLeakWarningPlugin::areNewDeleteOverloaded()); MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); } TEST(MemoryLeakWarningGlobalDetectorTest, threadSafeMemoryLeakDetectorOverloadsAreAlsoOverloaded) { MemoryLeakWarningPlugin::restoreNewDeleteOverloads(); MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads(); CHECK(MemoryLeakWarningPlugin::areNewDeleteOverloaded()); MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); MemoryLeakWarningPlugin::saveAndDisableNewDeleteOverloads(); } #endif #if CPPUTEST_USE_STD_CPP_LIB TEST(MemoryLeakWarningGlobalDetectorTest, turnOffNewOverloadsNoThrowCausesNoAdditionalLeaks) { #undef new size_t storedAmountOfLeaks = detector->totalMemoryLeaks(mem_leak_period_all); char* nonMemoryNoThrow = new (std::nothrow) char; char* nonArrayMemoryNoThrow = new (std::nothrow) char[10]; char* nonArrayMemoryThrow = new char[10]; LONGS_EQUAL(storedAmountOfLeaks, detector->totalMemoryLeaks(mem_leak_period_all)); ::operator delete(nonMemoryNoThrow, std::nothrow); ::operator delete[](nonArrayMemoryNoThrow, std::nothrow); ::operator delete[](nonArrayMemoryThrow, std::nothrow); #ifdef CPPUTEST_USE_NEW_MACROS #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif } #if CPPUTEST_USE_MEM_LEAK_DETECTION static int mutexLockCount = 0; static int mutexUnlockCount = 0; static void StubMutexLock(PlatformSpecificMutex) { mutexLockCount++; } static void StubMutexUnlock(PlatformSpecificMutex) { mutexUnlockCount++; } TEST_GROUP(MemoryLeakWarningThreadSafe) { void setup() CPPUTEST_OVERRIDE { UT_PTR_SET(PlatformSpecificMutexLock, StubMutexLock); UT_PTR_SET(PlatformSpecificMutexUnlock, StubMutexUnlock); mutexLockCount = 0; mutexUnlockCount = 0; } void teardown() CPPUTEST_OVERRIDE { } }; TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeMallocFreeReallocOverloadsDebug) { size_t storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all); MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads(); int *n = (int*) cpputest_malloc(sizeof(int)); LONGS_EQUAL(storedAmountOfLeaks + 1, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all)); CHECK_EQUAL(1, mutexLockCount); CHECK_EQUAL(1, mutexUnlockCount); n = (int*) cpputest_realloc(n, sizeof(int)*3); LONGS_EQUAL(storedAmountOfLeaks + 1, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all)); CHECK_EQUAL(2, mutexLockCount); CHECK_EQUAL(2, mutexUnlockCount); cpputest_free(n); LONGS_EQUAL(storedAmountOfLeaks, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all)); CHECK_EQUAL(3, mutexLockCount); CHECK_EQUAL(3, mutexUnlockCount); MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); } TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloadsDebug) { size_t storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all); MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads(); int *n = new int; char *str = new char[20]; LONGS_EQUAL(storedAmountOfLeaks + 2, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all)); CHECK_EQUAL(2, mutexLockCount); CHECK_EQUAL(2, mutexUnlockCount); delete [] str; delete n; LONGS_EQUAL(storedAmountOfLeaks, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all)); CHECK_EQUAL(4, mutexLockCount); CHECK_EQUAL(4, mutexUnlockCount); MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); } #ifdef __clang__ IGNORE_TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloads) { /* Clang misbehaves with -O2 - it will not overload operator new or * operator new[] no matter what. Therefore, this test is must be ignored. */ } #else TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloads) { #undef new size_t storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all); MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads(); int *n = new int; int *n_nothrow = new (std::nothrow) int; char *str = new char[20]; char *str_nothrow = new (std::nothrow) char[20]; LONGS_EQUAL(storedAmountOfLeaks + 4, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all)); CHECK_EQUAL(4, mutexLockCount); CHECK_EQUAL(4, mutexUnlockCount); delete [] str_nothrow; delete [] str; delete n; delete n_nothrow; LONGS_EQUAL(storedAmountOfLeaks, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all)); CHECK_EQUAL(8, mutexLockCount); CHECK_EQUAL(8, mutexUnlockCount); MemoryLeakWarningPlugin::turnOnDefaultNotThreadSafeNewDeleteOverloads(); #ifdef CPPUTEST_USE_NEW_MACROS #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif } #endif #endif #endif
null
23
cpp
cpputest
TestOutputTest.cpp
tests/CppUTest/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 unsigned long millisTime; extern "C" { static unsigned long MockGetPlatformSpecificTimeInMillis() { return millisTime; } } TEST_GROUP(TestOutput) { TestOutput* printer; StringBufferTestOutput* mock; UtestShell* tst; TestFailure *f; TestFailure *f2; TestFailure *f3; TestResult* result; void setup() CPPUTEST_OVERRIDE { mock = new StringBufferTestOutput(); printer = mock; tst = new UtestShell("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; UT_PTR_SET(GetPlatformSpecificTimeInMillis, MockGetPlatformSpecificTimeInMillis); TestOutput::setWorkingEnvironment(TestOutput::eclipse); } void teardown() CPPUTEST_OVERRIDE { TestOutput::setWorkingEnvironment(TestOutput::detectEnvironment); delete printer; delete tst; delete f; delete f2; delete f3; delete result; } void runOneTest() { result->countTest(); result->countRun(); } }; TEST(TestOutput, PrintConstCharStar) { printer->print("hello"); printer->print("hello\n"); STRCMP_EQUAL("hellohello\n", mock->getOutput().asCharString()); } TEST(TestOutput, PrintLong) { long number = 1234; printer->print(number); STRCMP_EQUAL("1234", mock->getOutput().asCharString()); } TEST(TestOutput, PrintSize) { size_t ten = 10; printer->print(ten); STRCMP_EQUAL("10", mock->getOutput().asCharString()); } TEST(TestOutput, PrintDouble) { printer->printDouble(12.34); STRCMP_EQUAL("12.34", 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, PrintTestALotAndSimulateRepeatRun) { for (int i = 0; i < 60; ++i) { runOneTest(); printer->printCurrentTestEnded(*result); } printer->printTestsEnded(*result); for (int i = 0; i < 60; ++i) { runOneTest(); printer->printCurrentTestEnded(*result); } STRCMP_EQUAL("..................................................\n.........." \ "\nOK (60 tests, 60 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)\n\n" \ "..................................................\n..........", mock->getOutput().asCharString()); } TEST(TestOutput, SetProgressIndicator) { printer->setProgressIndicator("."); printer->printCurrentTestEnded(*result); printer->setProgressIndicator("!"); printer->printCurrentTestEnded(*result); printer->setProgressIndicator("."); printer->printCurrentTestEnded(*result); STRCMP_EQUAL(".!.", mock->getOutput().asCharString()); } TEST(TestOutput, PrintTestVerboseStarted) { mock->verbose(TestOutput::level_verbose); printer->printCurrentTestStarted(*tst); STRCMP_EQUAL("TEST(group, test)", mock->getOutput().asCharString()); } TEST(TestOutput, PrintTestVerboseEnded) { mock->verbose(TestOutput::level_verbose); result->currentTestStarted(tst); millisTime = 5; result->currentTestEnded(tst); STRCMP_EQUAL("TEST(group, test) - 5 ms\n", mock->getOutput().asCharString()); } TEST(TestOutput, printColorWithSuccess) { mock->color(); runOneTest(); printer->printTestsEnded(*result); STRCMP_EQUAL("\n\033[32;1mOK (1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)\033[m\n\n", mock->getOutput().asCharString()); } TEST(TestOutput, printColorWithFailures) { mock->color(); runOneTest(); result->addFailure(*f); printer->flush(); printer->printTestsEnded(*result); STRCMP_EQUAL("\n\033[31;1mErrors (1 failures, 1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)" "\033[m\n\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->printFailure(*f2); STRCMP_EQUAL("\nfile:20: error: Failure in TEST(group, test)\n\tmessage\n\n", mock->getOutput().asCharString()); } TEST(TestOutput, PrintFailureWithFailInDifferentFile) { printer->printFailure(*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->printFailure(*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, PrintInVisualStudioFormat) { TestOutput::setWorkingEnvironment(TestOutput::visualStudio); printer->printFailure(*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()); } TEST(TestOutput, printTestsEndedWithNoTestsRunOrIgnored) { result->countTest(); printer->flush(); printer->printTestsEnded(*result); STRCMP_EQUAL("\nErrors (ran nothing, 1 tests, 0 ran, 0 checks, 0 ignored, 0 filtered out, 10 ms)\n" "Note: test run failed because no tests were run or ignored. Assuming something went wrong. " "This often happens because of linking errors or typos in test filter.\n\n", mock->getOutput().asCharString()); } class CompositeTestOutputTestStringBufferTestOutput : public StringBufferTestOutput { public: virtual void printTestsStarted() CPPUTEST_OVERRIDE { output += "Test Start\n"; } virtual void printTestsEnded(const TestResult& result) CPPUTEST_OVERRIDE { output += StringFromFormat("Test End %d\n", (int) result.getTestCount()); } void printCurrentGroupStarted(const UtestShell& test) CPPUTEST_OVERRIDE { output += StringFromFormat("Group %s Start\n", test.getGroup().asCharString()); } void printCurrentGroupEnded(const TestResult& res) CPPUTEST_OVERRIDE { output += StringFromFormat("Group End %d\n", (int) res.getTestCount()); } virtual void printCurrentTestStarted(const UtestShell&) CPPUTEST_OVERRIDE { output += "s"; } void flush() CPPUTEST_OVERRIDE { output += "flush"; } virtual bool isVerbose() { return verbose_ == level_verbose || verbose_ == level_veryVerbose; } virtual bool isColor() { return color_; } virtual const char* getProgressIndicator() { return progressIndication_; } }; TEST_GROUP(CompositeTestOutput) { CompositeTestOutputTestStringBufferTestOutput* output1; CompositeTestOutputTestStringBufferTestOutput* output2; CompositeTestOutput compositeOutput; TestResult* result; UtestShell* test; void setup() CPPUTEST_OVERRIDE { output1 = new CompositeTestOutputTestStringBufferTestOutput; output2 = new CompositeTestOutputTestStringBufferTestOutput; compositeOutput.setOutputOne(output1); compositeOutput.setOutputTwo(output2); result = new TestResult(compositeOutput); test = new UtestShell("Group", "Name", "file", 10); } void teardown() CPPUTEST_OVERRIDE { delete test; delete result; } }; TEST(CompositeTestOutput, TestStartedAndEnded) { compositeOutput.printTestsStarted(); compositeOutput.printTestsEnded(*result); STRCMP_EQUAL("Test Start\nTest End 0\n", output1->getOutput().asCharString()); STRCMP_EQUAL("Test Start\nTest End 0\n", output2->getOutput().asCharString()); } TEST(CompositeTestOutput, CurrentTestStartedAndEnded) { compositeOutput.printCurrentTestStarted(*test); compositeOutput.printCurrentTestEnded(*result); STRCMP_EQUAL("s.", output1->getOutput().asCharString()); STRCMP_EQUAL("s.", output2->getOutput().asCharString()); } TEST(CompositeTestOutput, CurrentGroupStartedAndEnded) { compositeOutput.printCurrentGroupStarted(*test); compositeOutput.printCurrentGroupEnded(*result); STRCMP_EQUAL("Group Group Start\nGroup End 0\n", output1->getOutput().asCharString()); STRCMP_EQUAL("Group Group Start\nGroup End 0\n", output2->getOutput().asCharString()); } TEST(CompositeTestOutput, PrintBuffer) { compositeOutput.printBuffer("Boo"); STRCMP_EQUAL("Boo", output1->getOutput().asCharString()); STRCMP_EQUAL("Boo", output2->getOutput().asCharString()); } TEST(CompositeTestOutput, printChar) { compositeOutput.print("Boo"); STRCMP_EQUAL("Boo", output1->getOutput().asCharString()); STRCMP_EQUAL("Boo", output2->getOutput().asCharString()); } TEST(CompositeTestOutput, printLong) { long ten = 10; compositeOutput.print(ten); STRCMP_EQUAL("10", output1->getOutput().asCharString()); STRCMP_EQUAL("10", output2->getOutput().asCharString()); } TEST(CompositeTestOutput, PrintSize) { size_t ten = 10; compositeOutput.print(ten); STRCMP_EQUAL("10", output1->getOutput().asCharString()); STRCMP_EQUAL("10", output2->getOutput().asCharString()); } TEST(CompositeTestOutput, printDouble) { compositeOutput.printDouble(1.01); STRCMP_EQUAL("1.01", output1->getOutput().asCharString()); STRCMP_EQUAL("1.01", output2->getOutput().asCharString()); } TEST(CompositeTestOutput, verbose) { compositeOutput.verbose(TestOutput::level_verbose); CHECK(output1->isVerbose()); CHECK(output2->isVerbose()); } TEST(CompositeTestOutput, color) { compositeOutput.color(); CHECK(output1->isColor()); CHECK(output2->isColor()); } TEST(CompositeTestOutput, PrintTestFailure) { TestOutput::WorkingEnvironment previousEnvironment = TestOutput::getWorkingEnvironment(); TestOutput::setWorkingEnvironment(TestOutput::eclipse); TestFailure failure(test, "file", 10, "failed"); compositeOutput.printFailure(failure); STRCMP_EQUAL("\nfile:10: error: Failure in TEST(Group, Name)\n\tfailed\n\n", output1->getOutput().asCharString()); STRCMP_EQUAL("\nfile:10: error: Failure in TEST(Group, Name)\n\tfailed\n\n", output2->getOutput().asCharString()); TestOutput::setWorkingEnvironment(previousEnvironment); } TEST(CompositeTestOutput, PrintTestRun) { compositeOutput.printTestRun(1, 2); STRCMP_EQUAL("Test run 1 of 2\n", output1->getOutput().asCharString()); STRCMP_EQUAL("Test run 1 of 2\n", output2->getOutput().asCharString()); } TEST(CompositeTestOutput, setProgressIndicator) { compositeOutput.setProgressIndicator("?"); STRCMP_EQUAL("?", output1->getProgressIndicator()); STRCMP_EQUAL("?", output2->getProgressIndicator()); } TEST(CompositeTestOutput, flush) { compositeOutput.flush(); STRCMP_EQUAL("flush", output1->getOutput().asCharString()); STRCMP_EQUAL("flush", output2->getOutput().asCharString()); } TEST(CompositeTestOutput, deletePreviousInstanceWhenSettingNew) { compositeOutput.setOutputOne(new CompositeTestOutput); compositeOutput.setOutputTwo(new CompositeTestOutput); // CHECK NO MEMORY LEAKS } TEST(CompositeTestOutput, printVeryVerbose) { compositeOutput.verbose(TestOutput::level_veryVerbose); compositeOutput.printVeryVerbose("very-verbose"); STRCMP_EQUAL("very-verbose", output1->getOutput().asCharString()); STRCMP_EQUAL("very-verbose", output2->getOutput().asCharString()); }
null
24
cpp
cpputest
SimpleStringCacheTest.cpp
tests/CppUTest/SimpleStringCacheTest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/SimpleStringInternalCache.h" #include "CppUTest/TestTestingFixture.h" class TestFunctionWithCache : public ExecFunction { public: void (*testFunction)(SimpleStringInternalCache*, size_t); SimpleStringInternalCache* parameter; size_t allocationSize; void exec() CPPUTEST_OVERRIDE { testFunction(parameter, allocationSize); } }; TEST_GROUP(SimpleStringInternalCache) { SimpleStringInternalCache cache; MemoryAccountant accountant; MemoryLeakAllocator* defaultAllocator; AccountingTestMemoryAllocator* allocator; TestFunctionWithCache testFunction; TestTestingFixture fixture; void setup() CPPUTEST_OVERRIDE { fixture.setTestFunction(&testFunction); testFunction.parameter = &cache; defaultAllocator = new MemoryLeakAllocator(defaultMallocAllocator()); allocator = new AccountingTestMemoryAllocator(accountant, defaultAllocator); cache.setAllocator(defaultAllocator); } void teardown() CPPUTEST_OVERRIDE { cache.clearAllIncludingCurrentlyUsedMemory(); accountant.clear(); delete allocator; delete defaultAllocator; } void createCacheForSize(size_t size, size_t amount) { for (size_t i = 0; i < amount; i++) { char* memory = cache.alloc(size); cache.dealloc(memory, size); } } }; TEST(SimpleStringInternalCache, cacheHitWithOneEntry) { createCacheForSize(10, 1); cache.setAllocator(allocator); char* mem = cache.alloc(10); mem[0] = 'B'; mem[3] = 'A'; mem[9] = 'S'; cache.setAllocator(allocator->originalAllocator()); LONGS_EQUAL(0, accountant.totalAllocationsOfSize(10)); CHECK(!cache.hasFreeBlocksOfSize(10)); cache.setAllocator(allocator); } TEST(SimpleStringInternalCache, cacheHitWithTwoEntries) { createCacheForSize(10, 2); cache.setAllocator(allocator); cache.alloc(10); cache.alloc(10); cache.setAllocator(allocator->originalAllocator()); LONGS_EQUAL(0, accountant.totalAllocationsOfSize(10)); CHECK(!cache.hasFreeBlocksOfSize(10)); cache.setAllocator(allocator); } TEST(SimpleStringInternalCache, allocatingMoreThanCacheAvailable) { createCacheForSize(10, 1); cache.setAllocator(allocator); cache.alloc(10); cache.alloc(10); cache.setAllocator(allocator->originalAllocator()); LONGS_EQUAL(1, accountant.totalAllocationsOfSize(32)); CHECK(!cache.hasFreeBlocksOfSize(10)); cache.setAllocator(allocator); } TEST(SimpleStringInternalCache, allocationWillReuseTheAllocatedBlocks) { cache.setAllocator(allocator); char* mem = cache.alloc(10); cache.dealloc(mem, 10); mem = cache.alloc(10); cache.dealloc(mem, 10); LONGS_EQUAL(1, accountant.totalAllocationsOfSize(32)); } TEST(SimpleStringInternalCache, multipleDifferentSizeAllocationsAndDeallocations) { cache.setAllocator(allocator); char* mem10 = cache.alloc(10); char* mem11 = cache.alloc(11); char* mem100 = cache.alloc(100); cache.dealloc(mem100, 100); char* mem101 = cache.alloc(101); char* mem102 = cache.alloc(102); char* mem103 = cache.alloc(103); cache.dealloc(mem101, 102); cache.dealloc(mem102, 103); cache.dealloc(mem103, 104); cache.alloc(105); cache.alloc(106); cache.alloc(107); cache.dealloc(mem10, 10); cache.dealloc(mem11, 11); LONGS_EQUAL(2, accountant.totalAllocationsOfSize(32)); LONGS_EQUAL(3, accountant.totalAllocationsOfSize(128)); } TEST(SimpleStringInternalCache, deallocOfCachedMemoryWillNotDealloc) { cache.setAllocator(allocator); char* mem = cache.alloc(10); cache.dealloc(mem, 10); LONGS_EQUAL(0, accountant.totalDeallocationsOfSize(32)); } TEST(SimpleStringInternalCache, clearCacheWillRemoveAllCachedMemoryButNotAllUsedMemory) { cache.setAllocator(allocator); char* mem = cache.alloc(10); cache.dealloc(mem, 10); cache.alloc(60); cache.clearCache(); LONGS_EQUAL(1, accountant.totalDeallocationsOfSize(32)); LONGS_EQUAL(0, accountant.totalDeallocationsOfSize(64)); } TEST(SimpleStringInternalCache, clearAllIncludingCurrentlyUsedMemory) { cache.setAllocator(allocator); cache.alloc(60); cache.clearAllIncludingCurrentlyUsedMemory(); LONGS_EQUAL(1, accountant.totalDeallocationsOfSize(64)); } TEST(SimpleStringInternalCache, allocatingLargerStringThanCached) { cache.setAllocator(allocator); char* mem = cache.alloc(1234); cache.dealloc(mem, 1234); LONGS_EQUAL(1, accountant.totalAllocationsOfSize(1234)); LONGS_EQUAL(1, accountant.totalDeallocationsOfSize(1234)); } TEST(SimpleStringInternalCache, allocatingMultipleLargerStringThanCached) { cache.setAllocator(allocator); char* mem = cache.alloc(1234); char* mem2 = cache.alloc(1234); char* mem3 = cache.alloc(1234); cache.dealloc(mem2, 1234); cache.dealloc(mem, 1234); cache.dealloc(mem3, 1234); LONGS_EQUAL(3, accountant.totalAllocationsOfSize(1234)); LONGS_EQUAL(3, accountant.totalDeallocationsOfSize(1234)); } TEST(SimpleStringInternalCache, clearAllIncludingCurrentlyUsedMemoryAlsoReleasesLargeNonCachesMemory) { cache.setAllocator(allocator); cache.alloc(1234); cache.alloc(1234); cache.alloc(1234); cache.clearAllIncludingCurrentlyUsedMemory(); LONGS_EQUAL(3, accountant.totalAllocationsOfSize(1234)); LONGS_EQUAL(3, accountant.totalDeallocationsOfSize(1234)); } static void deallocatingStringMemoryThatWasntAllocatedWithCache_(SimpleStringInternalCache* cache, size_t allocationSize) { char* mem = defaultMallocAllocator()->alloc_memory(allocationSize, __FILE__, __LINE__); mem[0] = 'B'; mem[1] = 'a'; mem[2] = 's'; mem[3] = '\0'; cache->dealloc(mem, allocationSize); defaultMallocAllocator()->free_memory(mem, allocationSize, __FILE__, __LINE__); } TEST(SimpleStringInternalCache, deallocatingMemoryThatWasntAllocatedWhileCacheWasInPlaceProducesWarning) { testFunction.testFunction = deallocatingStringMemoryThatWasntAllocatedWithCache_; testFunction.allocationSize = 123; cache.setAllocator(allocator); fixture.runAllTests(); fixture.assertPrintContains("\nWARNING: Attempting to deallocate a String buffer that was allocated while not caching. Ignoring it!\n" "This is likely due statics and will cause problems.\n" "Only warning once to avoid recursive warnings.\n" "String we are deallocating: \"Bas\"\n"); } static void deallocatingStringMemoryTwiceThatWasntAllocatedWithCache_(SimpleStringInternalCache* cache, size_t allocationSize) { char* mem = defaultMallocAllocator()->alloc_memory(allocationSize, __FILE__, __LINE__); mem[0] = '\0'; cache->dealloc(mem, allocationSize); cache->dealloc(mem, allocationSize); defaultMallocAllocator()->free_memory(mem, allocationSize, __FILE__, __LINE__); } TEST(SimpleStringInternalCache, deallocatingMemoryThatWasntAllocatedWhileCacheWasInPlaceProducesWarningButOnlyOnce) { testFunction.testFunction = deallocatingStringMemoryTwiceThatWasntAllocatedWithCache_; testFunction.allocationSize = 123; cache.setAllocator(allocator); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getOutput().count("WARNING")); } TEST(SimpleStringInternalCache, deallocatingLargeMemoryThatWasntAllocatedWhileCacheWasInPlaceProducesWarning) { testFunction.testFunction = deallocatingStringMemoryThatWasntAllocatedWithCache_; testFunction.allocationSize = 12345; cache.setAllocator(allocator); fixture.runAllTests(); fixture.assertPrintContains("\nWARNING: Attempting to deallocate a String buffer that was allocated while not caching. Ignoring it!\n" "This is likely due statics and will cause problems.\n" "Only warning once to avoid recursive warnings.\n" "String we are deallocating: \"Bas\"\n"); } TEST(SimpleStringInternalCache, deallocatingLargeMemoryThatWasntAllocatedWhileCacheWasInPlaceProducesWarningButOnlyOnce) { testFunction.testFunction = deallocatingStringMemoryTwiceThatWasntAllocatedWithCache_; testFunction.allocationSize = 12345; cache.setAllocator(allocator); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getOutput().count("WARNING")); } TEST_GROUP(SimpleStringCacheAllocator) { SimpleStringCacheAllocator* allocator; SimpleStringInternalCache cache; MemoryAccountant accountant; AccountingTestMemoryAllocator* accountingAllocator; void setup() CPPUTEST_OVERRIDE { accountingAllocator = new AccountingTestMemoryAllocator(accountant, defaultMallocAllocator()); allocator = new SimpleStringCacheAllocator(cache, accountingAllocator); } void teardown() CPPUTEST_OVERRIDE { cache.clearCache(); delete allocator; delete accountingAllocator; } }; TEST(SimpleStringCacheAllocator, allocationIsCached) { char* mem = allocator->alloc_memory(10, __FILE__, __LINE__); allocator->free_memory(mem, 10, __FILE__, __LINE__); size_t totalAllocations = accountant.totalAllocations(); size_t totalDeallocations = accountant.totalDeallocations(); mem = allocator->alloc_memory(10, __FILE__, __LINE__); allocator->free_memory(mem, 10, __FILE__, __LINE__); LONGS_EQUAL(totalAllocations, accountant.totalAllocations()); LONGS_EQUAL(totalDeallocations, accountant.totalDeallocations()); } TEST(SimpleStringCacheAllocator, originalAllocator) { POINTERS_EQUAL(defaultMallocAllocator(), allocator->actualAllocator()); STRCMP_EQUAL(defaultMallocAllocator()->alloc_name(), allocator->alloc_name()); STRCMP_EQUAL(defaultMallocAllocator()->free_name(), allocator->free_name()); } TEST(SimpleStringCacheAllocator, name) { STRCMP_EQUAL("SimpleStringCacheAllocator", allocator->name()); } TEST_GROUP(GlobalSimpleStringCache) { }; TEST(GlobalSimpleStringCache, installsAndRemovedCache) { TestMemoryAllocator* originalStringAllocator = SimpleString::getStringAllocator(); { GlobalSimpleStringCache cache; STRCMP_EQUAL("SimpleStringCacheAllocator", SimpleString::getStringAllocator()->name()); POINTERS_EQUAL(cache.getAllocator(), SimpleString::getStringAllocator()); } POINTERS_EQUAL(originalStringAllocator, SimpleString::getStringAllocator()); }
null
25
cpp
cpputest
AllTests.h
tests/CppUTest/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
26
cpp
cpputest
AllocationInCppFile.cpp
tests/CppUTest/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" #include "AllocationInCppFile.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]; } #if CPPUTEST_HAVE_EXCEPTIONS ClassThatThrowsAnExceptionInTheConstructor::ClassThatThrowsAnExceptionInTheConstructor() { throw 1; } #endif
null
27
cpp
cpputest
UtestPlatformTest.cpp
tests/CppUTest/UtestPlatformTest.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/TestHarness.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTest/PlatformSpecificFunctions.h" #include "CppUTest/StandardCLibrary.h" #include "CppUTest/TestMemoryAllocator.h" #if CPPUTEST_USE_STD_C_LIB // This will cause a crash in VS2010 due to PlatformSpecificFree being uninitialized static const SimpleString str1("abc"); static const SimpleString str2("def"); static const SimpleString str3(str1 + str2); TEST_GROUP(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess) { TestTestingFixture fixture; }; // There is a possibility that a compiler provides fork but not waitpid. #if !defined(CPPUTEST_HAVE_FORK) || !defined(CPPUTEST_HAVE_WAITPID) TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, DummyFailsWithMessage) { fixture.setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("-p doesn't work on this platform, as it is lacking fork.\b"); } #else static void failFunction_() { FAIL("This test fails"); } CPPUTEST_NORETURN static void exitNonZeroFunction_(); static void exitNonZeroFunction_() { /* destructor of static objects will be called. If StringCache was there then the allocator will report invalid deallocations of static SimpleString */ SimpleString::setStringAllocator(SimpleString::getStringAllocator()->actualAllocator()); exit(1); } #include <errno.h> static int waitpid_while_debugging_stub_number_called = 0; static int waitpid_while_debugging_stub_forced_failures = 0; extern "C" { static int (*original_waitpid)(int, int*, int) = NULLPTR; static int fork_failed_stub(void) { return -1; } static int waitpid_while_debugging_stub(int pid, int* status, int options) { static int saved_status; if (waitpid_while_debugging_stub_number_called++ < waitpid_while_debugging_stub_forced_failures) { saved_status = *status; errno=EINTR; return -1; } else { *status = saved_status; return original_waitpid(pid, status, options); } } static int waitpid_failed_stub(int, int*, int) { return -1; } } #include <unistd.h> #include <signal.h> static void stoppedTestFunction_() { kill(getpid(), SIGSTOP); } TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, TestInSeparateProcessWorks) { fixture.setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("OK (1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out"); } TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, FailureInSeparateProcessWorks) { fixture.setRunTestsInSeperateProcess(); fixture.setTestFunction(failFunction_); fixture.runAllTests(); fixture.assertPrintContains("Failed in separate process"); fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out"); } #if (! CPPUTEST_SANITIZE_ADDRESS) static int accessViolationTestFunction_() { return *(volatile int*) NULLPTR; // NOLINT(clang-analyzer-core.NullDereference) } TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, AccessViolationInSeparateProcessWorks) { fixture.setRunTestsInSeperateProcess(); fixture.setTestFunction((void(*)())accessViolationTestFunction_); fixture.runAllTests(); fixture.assertPrintContains("Failed in separate process - killed by signal 11"); fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran"); } #endif TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, StoppedInSeparateProcessWorks) { fixture.setRunTestsInSeperateProcess(); fixture.setTestFunction(stoppedTestFunction_); fixture.runAllTests(); fixture.assertPrintContains("Stopped in separate process - continuing"); fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran"); } TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, CallToForkFailedInSeparateProcessWorks) { UT_PTR_SET(PlatformSpecificFork, fork_failed_stub); fixture.setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("Call to fork() failed"); fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran"); } TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, CallToWaitPidWhileDebuggingInSeparateProcessWorks) { UT_PTR_SET(original_waitpid, PlatformSpecificWaitPid); UT_PTR_SET(PlatformSpecificWaitPid, waitpid_while_debugging_stub); waitpid_while_debugging_stub_number_called = 0; waitpid_while_debugging_stub_forced_failures = 10; fixture.setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("OK (1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out"); // extra check to confirm that waitpid() was polled until it passed (and passed call adds one) CHECK(waitpid_while_debugging_stub_number_called > waitpid_while_debugging_stub_forced_failures); } TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, CallToWaitPidStopsAndReportsAnErrorAfter20TimesRetry) { UT_PTR_SET(original_waitpid, PlatformSpecificWaitPid); UT_PTR_SET(PlatformSpecificWaitPid, waitpid_while_debugging_stub); waitpid_while_debugging_stub_number_called = 0; waitpid_while_debugging_stub_forced_failures = 40; fixture.setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("Call to waitpid() failed with EINTR. Tried 30 times and giving up! Sometimes happens in debugger"); // extra check to confirm that waitpid() was polled until it passed (and passed call adds one) CHECK(waitpid_while_debugging_stub_number_called > 30); } TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, CallToWaitPidFailedInSeparateProcessWorks) { UT_PTR_SET(PlatformSpecificWaitPid, waitpid_failed_stub); fixture.setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("Call to waitpid() failed"); fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran"); } TEST(UTestPlatformsTest_PlatformSpecificRunTestInASeperateProcess, MultipleTestsInSeparateProcessAreCountedProperly) { fixture.setRunTestsInSeperateProcess(); fixture.runTestWithMethod(NULLPTR); fixture.runTestWithMethod(stoppedTestFunction_); fixture.runTestWithMethod(NULLPTR); fixture.runTestWithMethod(exitNonZeroFunction_); fixture.runTestWithMethod(NULLPTR); fixture.assertPrintContains("Failed in separate process"); fixture.assertPrintContains("Stopped in separate process"); fixture.assertPrintContains("Errors (2 failures, 5 tests, 5 ran, 0 checks, 0 ignored, 0 filtered out"); } #endif #endif
null
28
cpp
cpputest
PreprocessorTest.cpp
tests/CppUTest/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) { };
null
29
cpp
cpputest
TestResultTest.cpp
tests/CppUTest/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" extern "C" { static unsigned long MockGetPlatformSpecificTimeInMillis() { return 10; } } TEST_GROUP(TestResult) { TestOutput* printer; StringBufferTestOutput* mock; TestResult* res; void setup() CPPUTEST_OVERRIDE { mock = new StringBufferTestOutput(); printer = mock; res = new TestResult(*printer); UT_PTR_SET(GetPlatformSpecificTimeInMillis, MockGetPlatformSpecificTimeInMillis); } void teardown() CPPUTEST_OVERRIDE { delete printer; delete res; } }; TEST(TestResult, TestEndedWillPrintResultsAndExecutionTime) { res->testsEnded(); CHECK(mock->getOutput().contains("10 ms")); } TEST(TestResult, ResultIsOkIfTestIsRunWithNoFailures) { res->countTest(); res->countRun(); CHECK_FALSE(res->isFailure()); } TEST(TestResult, ResultIsOkIfTestIsIgnored) { res->countTest(); res->countIgnored(); CHECK_FALSE(res->isFailure()); } TEST(TestResult, ResultIsNotOkIfFailures) { res->countTest(); res->countRun(); res->addFailure(TestFailure(UtestShell::getCurrent(), StringFrom("dummy message"))); CHECK_TRUE(res->isFailure()); } TEST(TestResult, ResultIsNotOkIfNoTestsAtAll) { CHECK_TRUE(res->isFailure()); } TEST(TestResult, ResultIsNotOkIfNoTestsRunOrIgnored) { res->countTest(); CHECK_TRUE(res->isFailure()); }
null
30
cpp
cpputest
PluginTest.cpp
tests/CppUTest/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), preActionSequence(0), postAction(0), postActionSequence(0) { } virtual void preTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE { preAction++; preActionSequence = sequenceNumber++; } virtual void postTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE { 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 *const *av, int index) CPPUTEST_OVERRIDE { 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() CPPUTEST_OVERRIDE { firstPlugin = new DummyPlugin(GENERIC_PLUGIN); secondPlugin = new DummyPluginWhichAcceptsParameters(GENERIC_PLUGIN2); thirdPlugin = new DummyPlugin(GENERIC_PLUGIN3); genFixture = new TestTestingFixture; registry = genFixture->getRegistry(); registry->installPlugin(firstPlugin); sequenceNumber = 1; } void teardown() CPPUTEST_OVERRIDE { delete firstPlugin; delete secondPlugin; delete thirdPlugin; delete genFixture; } }; #define GENERIC_PLUGIN "GenericPlugin" TEST(PluginTest, PluginHasName) { STRCMP_EQUAL(GENERIC_PLUGIN, firstPlugin->getName().asCharString()); } TEST(PluginTest, InstallPlugin) { CHECK_EQUAL(firstPlugin, registry->getFirstPlugin()); CHECK_EQUAL(firstPlugin, registry->getPluginByName(GENERIC_PLUGIN)); LONGS_EQUAL(1, registry->countPlugins()); } TEST(PluginTest, InstallMultiplePlugins) { registry->installPlugin(thirdPlugin); CHECK_EQUAL(firstPlugin, registry->getPluginByName(GENERIC_PLUGIN)); CHECK_EQUAL(thirdPlugin, registry->getPluginByName(GENERIC_PLUGIN3)); POINTERS_EQUAL(NULLPTR, registry->getPluginByName("I do not exist")); } TEST(PluginTest, ActionsAllRun) { genFixture->runAllTests(); genFixture->runAllTests(); CHECK_EQUAL(2, firstPlugin->preAction); CHECK_EQUAL(2, firstPlugin->postAction); } TEST(PluginTest, Sequence) { registry->installPlugin(thirdPlugin); genFixture->runAllTests(); CHECK_EQUAL(1, thirdPlugin->preActionSequence); CHECK_EQUAL(2, firstPlugin->preActionSequence); CHECK_EQUAL(3, firstPlugin->postActionSequence); CHECK_EQUAL(4, thirdPlugin->postActionSequence); LONGS_EQUAL(2, registry->countPlugins()); } TEST(PluginTest, RemovePluginByName) { registry->installPlugin(secondPlugin); registry->installPlugin(thirdPlugin); LONGS_EQUAL(3, registry->countPlugins()); registry->removePluginByName(GENERIC_PLUGIN2); LONGS_EQUAL(2, registry->countPlugins()); } struct DefaultPlugin : public TestPlugin { DefaultPlugin() : TestPlugin("default") {} }; TEST(PluginTest, DefaultPostTestActionDoesntDoAnything) { DefaultPlugin defaultPlugin; registry->installPlugin(&defaultPlugin); genFixture->runAllTests(); } 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, const_cast<char**>(cmd_line), 0) == false); /* cover non-const wrapper, too */ } TEST(PluginTest, ParseArgumentsContinuesAndSucceedsWhenAPluginCanParse) { registry->installPlugin(secondPlugin); const char *cmd_line[] = {"-paccept", "andmorenonsense"}; CHECK(registry->getFirstPlugin()->parseAllArguments(2, const_cast<char**>(cmd_line), 0)); /* cover non-const wrapper, too */ }
null
31
cpp
cpputest
TestUTestStringMacro.cpp
tests/CppUTest/TestUTestStringMacro.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/TestTestingFixture.h" #define CHECK_TEST_FAILS_PROPER_WITH_TEXT(text) fixture.checkTestFailsWithProperTestLocation(text, __FILE__, __LINE__) TEST_GROUP(UnitTestStringMacros) { TestTestingFixture fixture; }; static void STRCMP_EQUALWithActualIsNULLTestMethod_() { STRCMP_EQUAL("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUALAndActualIsNULL) { fixture.runTestWithMethod(STRCMP_EQUALWithActualIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>"); } static void STRCMP_EQUALWithExpectedIsNULLTestMethod_() { STRCMP_EQUAL(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUALAndExpectedIsNULL) { fixture.runTestWithMethod(STRCMP_EQUALWithExpectedIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>"); } static void STRCMP_CONTAINSWithActualIsNULLTestMethod_() { STRCMP_CONTAINS("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINSAndActualIsNULL) { fixture.runTestWithMethod(STRCMP_CONTAINSWithActualIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <ok>"); } static void STRCMP_CONTAINSWithExpectedIsNULLTestMethod_() { STRCMP_CONTAINS(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINSAndExpectedIsNULL) { fixture.runTestWithMethod(STRCMP_CONTAINSWithExpectedIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <>"); } static void STRNCMP_EQUALWithActualIsNULLTestMethod_() { STRNCMP_EQUAL("ok", NULLPTR, 2); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUALAndActualIsNULL) { fixture.runTestWithMethod(STRNCMP_EQUALWithActualIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>"); } static void STRNCMP_EQUALWithExpectedIsNULLTestMethod_() { STRNCMP_EQUAL(NULLPTR, "ok", 2); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUALAndExpectedIsNULL) { fixture.runTestWithMethod(STRNCMP_EQUALWithExpectedIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>"); } static void STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod_() { STRCMP_NOCASE_EQUAL("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndActualIsNULL) { fixture.runTestWithMethod(STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>"); } static void STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod_() { STRCMP_NOCASE_EQUAL(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndExpectedIsNULL) { fixture.runTestWithMethod(STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>"); } static void STRCMP_NOCASE_EQUALWithUnequalInputTestMethod_() { STRCMP_NOCASE_EQUAL("no", "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndUnequalInput) { fixture.runTestWithMethod(STRCMP_NOCASE_EQUALWithUnequalInputTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <ok>"); } static void STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod_() { STRCMP_NOCASE_CONTAINS("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINSAndActualIsNULL) { fixture.runTestWithMethod(STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <ok>"); } static void STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod_() { STRCMP_NOCASE_CONTAINS(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINSAndExpectedIsNULL) { fixture.runTestWithMethod(STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <>"); } static void failingTestMethodWithSTRCMP_EQUAL_() { STRCMP_EQUAL("hello", "hell"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUAL) { fixture.runTestWithMethod(failingTestMethodWithSTRCMP_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>"); } TEST(UnitTestStringMacros, STRCMP_EQUALBehavesAsProperMacro) { if (false) STRCMP_EQUAL("1", "2"); else STRCMP_EQUAL("1", "1"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_EQUALWorksInAnIgnoredTest) { STRCMP_EQUAL("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithSTRCMP_EQUAL_TEXT_() { STRCMP_EQUAL_TEXT("hello", "hell", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUAL_TEXT) { fixture.runTestWithMethod(failingTestMethodWithSTRCMP_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestStringMacros, STRCMP_EQUAL_TEXTBehavesAsProperMacro) { if (false) STRCMP_EQUAL_TEXT("1", "2", "Failed because it failed"); else STRCMP_EQUAL_TEXT("1", "1", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_EQUAL_TEXTWorksInAnIgnoredTest) { STRCMP_EQUAL_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithSTRNCMP_EQUAL_() { STRNCMP_EQUAL("hello", "hallo", 5); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUAL) { fixture.runTestWithMethod(failingTestMethodWithSTRNCMP_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hallo>"); } TEST(UnitTestStringMacros, STRNCMP_EQUALBehavesAsProperMacro) { if (false) STRNCMP_EQUAL("1", "2", 1); else STRNCMP_EQUAL("1", "1", 1); } IGNORE_TEST(UnitTestStringMacros, STRNCMP_EQUALWorksInAnIgnoredTest) { STRNCMP_EQUAL("Hello", "World", 3); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithSTRNCMP_EQUAL_TEXT_() { STRNCMP_EQUAL_TEXT("hello", "hallo", 5, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUAL_TEXT) { fixture.runTestWithMethod(failingTestMethodWithSTRNCMP_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hallo>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestStringMacros, STRNCMP_EQUAL_TEXTBehavesAsProperMacro) { if (false) STRNCMP_EQUAL_TEXT("1", "2", 1, "Failed because it failed"); else STRNCMP_EQUAL_TEXT("1", "1", 1, "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRNCMP_EQUAL_TEXTWorksInAnIgnoredTest) { STRNCMP_EQUAL_TEXT("Hello", "World", 3, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithSTRCMP_NOCASE_EQUAL_() { STRCMP_NOCASE_EQUAL("hello", "Hell"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUAL) { fixture.runTestWithMethod(failingTestMethodWithSTRCMP_NOCASE_EQUAL_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Hell>"); } TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUALBehavesAsProperMacro) { if (false) STRCMP_NOCASE_EQUAL("1", "2"); else STRCMP_NOCASE_EQUAL("1", "1"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUALWorksInAnIgnoredTest) { STRCMP_NOCASE_EQUAL("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT_() { STRCMP_NOCASE_EQUAL_TEXT("hello", "hell", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUAL_TEXT) { fixture.runTestWithMethod(failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUAL_TEXTBehavesAsProperMacro) { if (false) STRCMP_NOCASE_EQUAL_TEXT("1", "2", "Failed because it failed"); else STRCMP_NOCASE_EQUAL_TEXT("1", "1", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUAL_TEXTWorksInAnIgnoredTest) { STRCMP_NOCASE_EQUAL_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithSTRCMP_CONTAINS_() { STRCMP_CONTAINS("hello", "world"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINS) { fixture.runTestWithMethod(failingTestMethodWithSTRCMP_CONTAINS_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <world>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>"); } TEST(UnitTestStringMacros, STRCMP_CONTAINSBehavesAsProperMacro) { if (false) STRCMP_CONTAINS("1", "2"); else STRCMP_CONTAINS("1", "1"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_CONTAINSWorksInAnIgnoredTest) { STRCMP_CONTAINS("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithSTRCMP_CONTAINS_TEXT_() { STRCMP_CONTAINS_TEXT("hello", "world", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINS_TEXT) { fixture.runTestWithMethod(failingTestMethodWithSTRCMP_CONTAINS_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <world>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestStringMacros, STRCMP_CONTAINS_TEXTBehavesAsProperMacro) { if (false) STRCMP_CONTAINS_TEXT("1", "2", "Failed because it failed"); else STRCMP_CONTAINS_TEXT("1", "1", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_CONTAINS_TEXTWorksInAnIgnoredTest) { STRCMP_CONTAINS_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithSTRCMP_NOCASE_CONTAINS_() { STRCMP_NOCASE_CONTAINS("hello", "WORLD"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINS) { fixture.runTestWithMethod(failingTestMethodWithSTRCMP_NOCASE_CONTAINS_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <WORLD>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>"); } TEST(UnitTestStringMacros, STRCMP_NOCASE_CONTAINSBehavesAsProperMacro) { if (false) STRCMP_NOCASE_CONTAINS("never", "executed"); else STRCMP_NOCASE_CONTAINS("hello", "HELLO WORLD"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NO_CASE_CONTAINSWorksInAnIgnoredTest) { STRCMP_NOCASE_CONTAINS("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT_() { STRCMP_NOCASE_CONTAINS_TEXT("hello", "WORLD", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINS_TEXT) { fixture.runTestWithMethod(failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <WORLD>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestStringMacros, STRCMP_NOCASE_CONTAINS_TEXTBehavesAsProperMacro) { if (false) STRCMP_NOCASE_CONTAINS_TEXT("never", "executed", "Failed because it failed"); else STRCMP_NOCASE_CONTAINS_TEXT("hello", "HELLO WORLD", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NO_CASE_CONTAINS_TEXTWorksInAnIgnoredTest) { STRCMP_NOCASE_CONTAINS_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, NFirstCharsComparison) { STRNCMP_EQUAL("Hello World!", "Hello Peter!", 0); STRNCMP_EQUAL("Hello World!", "Hello Peter!", 1); STRNCMP_EQUAL("Hello World!", "Hello Peter!", 6); STRNCMP_EQUAL("Hello World!", "Hello", 5); } static void compareNFirstCharsWithUpperAndLowercase_() { STRNCMP_EQUAL("hello world!", "HELLO WORLD!", 12); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, CompareNFirstCharsWithUpperAndLowercase) { fixture.runTestWithMethod(compareNFirstCharsWithUpperAndLowercase_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello world!>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <HELLO WORLD!>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 0"); } static void compareNFirstCharsWithDifferenceInTheMiddle_() { STRNCMP_EQUAL("Hello World!", "Hello Peter!", 12); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, CompareNFirstCharsWithDifferenceInTheMiddle) { fixture.runTestWithMethod(compareNFirstCharsWithDifferenceInTheMiddle_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <Hello World!>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Hello Peter!>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 6"); } static void compareNFirstCharsWithEmptyString_() { STRNCMP_EQUAL("", "Not empty string", 5); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, CompareNFirstCharsWithEmptyString) { fixture.runTestWithMethod(compareNFirstCharsWithEmptyString_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Not empty string>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 0"); } static void compareNFirstCharsWithLastCharDifferent_() { STRNCMP_EQUAL("Not empty string?", "Not empty string!", 17); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, CompareNFirstCharsWithLastCharDifferent) { fixture.runTestWithMethod(compareNFirstCharsWithLastCharDifferent_); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <Not empty string?>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Not empty string!>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 16"); }
null
32
cpp
cpputest
UtestTest.cpp
tests/CppUTest/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/TestTestingFixture.h" #include "CppUTest/PlatformSpecificFunctions.h" #if CPPUTEST_USE_STD_C_LIB #include <math.h> #endif TEST_GROUP(UtestShell) { TestTestingFixture fixture; }; static void failMethod_() { FAIL("This test fails"); } static void passingTestMethod_() { CHECK(true); } static void passingCheckEqualTestMethod_() { CHECK_EQUAL(1, 1); } static void exitTestMethod_() { TEST_EXIT; FAIL("Should not get here"); } TEST(UtestShell, compareDoubles) { CHECK(doubles_equal(1.0, 1.001, 0.01)); CHECK(!doubles_equal(1.0, 1.1, 0.05)); double a = 1.2345678; CHECK(doubles_equal(a, a, 0.000000001)); } #ifdef NAN TEST(UtestShell, compareDoublesNaN) { CHECK(!doubles_equal((double)NAN, 1.001, 0.01)); CHECK(!doubles_equal(1.0, (double)NAN, 0.01)); CHECK(!doubles_equal(1.0, 1.001, (double)NAN)); } #endif #ifdef INFINITY TEST(UtestShell, compareDoublesInf) { CHECK(!doubles_equal((double)INFINITY, 1.0, 0.01)); CHECK(!doubles_equal(1.0, (double)INFINITY, 0.01)); CHECK(doubles_equal(1.0, -1.0, (double)INFINITY)); CHECK(doubles_equal((double)INFINITY, (double)INFINITY, 0.01)); CHECK(doubles_equal((double)INFINITY, (double)INFINITY, (double)INFINITY)); } #endif TEST(UtestShell, FailWillIncreaseTheAmountOfChecks) { fixture.setTestFunction(failMethod_); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getCheckCount()); } TEST(UtestShell, PassedCheckEqualWillIncreaseTheAmountOfChecks) { fixture.setTestFunction(passingCheckEqualTestMethod_); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getCheckCount()); } IGNORE_TEST(UtestShell, IgnoreTestAccessingFixture) { CHECK(&fixture != NULLPTR); } TEST(UtestShell, MacrosUsedInSetup) { IGNORE_ALL_LEAKS_IN_TEST(); fixture.setSetup(failMethod_); fixture.setTestFunction(passingTestMethod_); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); } TEST(UtestShell, MacrosUsedInTearDown) { IGNORE_ALL_LEAKS_IN_TEST(); fixture.setTeardown(failMethod_); fixture.setTestFunction(passingTestMethod_); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); } TEST(UtestShell, ExitLeavesQuietly) { fixture.setTestFunction(exitTestMethod_); fixture.runAllTests(); LONGS_EQUAL(0, fixture.getFailureCount()); } static bool cpputestHasCrashed; static void crashMethod() { cpputestHasCrashed = true; } TEST(UtestShell, FailWillNotCrashIfNotEnabled) { cpputestHasCrashed = false; UtestShell::setCrashMethod(crashMethod); fixture.setTestFunction(failMethod_); fixture.runAllTests(); CHECK_FALSE(cpputestHasCrashed); LONGS_EQUAL(1, fixture.getFailureCount()); UtestShell::resetCrashMethod(); } TEST(UtestShell, FailWillCrashIfEnabled) { cpputestHasCrashed = false; UtestShell::setCrashOnFail(); UtestShell::setCrashMethod(crashMethod); fixture.setTestFunction(failMethod_); fixture.runAllTests(); CHECK(cpputestHasCrashed); UtestShell::restoreDefaultTestTerminator(); UtestShell::resetCrashMethod(); } static int teardownCalled = 0; static void teardownMethod_() { teardownCalled++; } TEST(UtestShell, TeardownCalledAfterTestFailure) { teardownCalled = 0; IGNORE_ALL_LEAKS_IN_TEST(); fixture.setTeardown(teardownMethod_); fixture.setTestFunction(failMethod_); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); LONGS_EQUAL(1, teardownCalled); } static int stopAfterFailure = 0; static void stopAfterFailureMethod_() { FAIL("fail"); stopAfterFailure++; } TEST(UtestShell, TestStopsAfterTestFailure) { IGNORE_ALL_LEAKS_IN_TEST(); stopAfterFailure = 0; fixture.setTestFunction(stopAfterFailureMethod_); fixture.runAllTests(); CHECK(fixture.hasTestFailed()); LONGS_EQUAL(1, fixture.getFailureCount()); LONGS_EQUAL(0, stopAfterFailure); } TEST(UtestShell, TestStopsAfterSetupFailure) { stopAfterFailure = 0; fixture.setSetup(stopAfterFailureMethod_); fixture.setTeardown(stopAfterFailureMethod_); fixture.setTestFunction(failMethod_); fixture.runAllTests(); LONGS_EQUAL(2, fixture.getFailureCount()); LONGS_EQUAL(0, stopAfterFailure); } #if CPPUTEST_HAVE_EXCEPTIONS // Prevents -Wunreachable-code; should always be 'true' static bool shouldThrowException = true; static void thrownUnknownExceptionMethod_() { if (shouldThrowException) { throw 33; } stopAfterFailure++; } TEST(UtestShell, TestStopsAfterUnknownExceptionIsThrown) { bool initialRethrowExceptions = UtestShell::isRethrowingExceptions(); UtestShell::setRethrowExceptions(false); stopAfterFailure = 0; shouldThrowException = true; fixture.setTestFunction(thrownUnknownExceptionMethod_); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); fixture.assertPrintContains("Unexpected exception of unknown type was thrown"); LONGS_EQUAL(0, stopAfterFailure); UtestShell::setRethrowExceptions(initialRethrowExceptions); } TEST(UtestShell, NoExceptionIsRethrownIfEnabledButNotThrown) { bool initialRethrowExceptions = UtestShell::isRethrowingExceptions(); bool exceptionRethrown = false; stopAfterFailure = 0; UtestShell::setRethrowExceptions(true); shouldThrowException = false; fixture.setTestFunction(thrownUnknownExceptionMethod_); try { fixture.runAllTests(); } catch(...) { exceptionRethrown = true; } CHECK_FALSE(exceptionRethrown); LONGS_EQUAL(0, fixture.getFailureCount()); LONGS_EQUAL(1, stopAfterFailure); UtestShell::setRethrowExceptions(initialRethrowExceptions); } TEST(UtestShell, UnknownExceptionIsRethrownIfEnabled) { bool initialRethrowExceptions = UtestShell::isRethrowingExceptions(); bool exceptionRethrown = false; stopAfterFailure = 0; UtestShell::setRethrowExceptions(true); shouldThrowException = true; fixture.setTestFunction(thrownUnknownExceptionMethod_); try { fixture.runAllTests(); stopAfterFailure++; } catch(...) { exceptionRethrown = true; } CHECK_TRUE(exceptionRethrown); LONGS_EQUAL(1, fixture.getFailureCount()); fixture.assertPrintContains("Unexpected exception of unknown type was thrown"); LONGS_EQUAL(0, stopAfterFailure); UtestShell::setRethrowExceptions(initialRethrowExceptions); } #if CPPUTEST_USE_STD_CPP_LIB static void thrownStandardExceptionMethod_() { if (shouldThrowException) { throw std::runtime_error("exception text"); } stopAfterFailure++; } TEST(UtestShell, TestStopsAfterStandardExceptionIsThrown) { bool initialRethrowExceptions = UtestShell::isRethrowingExceptions(); UtestShell::setRethrowExceptions(false); stopAfterFailure = 0; shouldThrowException = true; fixture.setTestFunction(thrownStandardExceptionMethod_); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); #if CPPUTEST_HAVE_RTTI fixture.assertPrintContains("Unexpected exception of type '"); fixture.assertPrintContains("runtime_error"); fixture.assertPrintContains("' was thrown: exception text"); #else fixture.assertPrintContains("Unexpected exception of unknown type was thrown"); #endif LONGS_EQUAL(0, stopAfterFailure); UtestShell::setRethrowExceptions(initialRethrowExceptions); } TEST(UtestShell, StandardExceptionIsRethrownIfEnabled) { bool initialRethrowExceptions = UtestShell::isRethrowingExceptions(); bool exceptionRethrown = false; stopAfterFailure = 0; UtestShell::setRethrowExceptions(true); shouldThrowException = true; fixture.setTestFunction(thrownStandardExceptionMethod_); try { fixture.runAllTests(); stopAfterFailure++; } catch(const std::exception &) { exceptionRethrown = true; } CHECK_TRUE(exceptionRethrown); LONGS_EQUAL(1, fixture.getFailureCount()); fixture.assertPrintContains("Unexpected exception of type '"); fixture.assertPrintContains("runtime_error"); fixture.assertPrintContains("' was thrown: exception text"); LONGS_EQUAL(0, stopAfterFailure); UtestShell::setRethrowExceptions(initialRethrowExceptions); } #endif // CPPUTEST_USE_STD_CPP_LIB #endif // CPPUTEST_HAVE_EXCEPTIONS TEST(UtestShell, veryVebose) { UtestShell shell("Group", "name", __FILE__, __LINE__); StringBufferTestOutput normalOutput; normalOutput.verbose(TestOutput::level_veryVerbose); NullTestPlugin plugin; TestResult result(normalOutput); shell.runOneTestInCurrentProcess(&plugin, result); STRCMP_CONTAINS("\n------ before runTest", normalOutput.getOutput().asCharString()); } class defaultUtestShell: public UtestShell { }; TEST(UtestShell, this_test_covers_the_UtestShell_createTest_and_Utest_testBody_methods) { defaultUtestShell shell; fixture.addTest(&shell); fixture.runAllTests(); LONGS_EQUAL(2, fixture.getTestCount()); } static void StubPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result) { result->addFailure(TestFailure(shell, "Failed in separate process")); } TEST(UtestShell, RunInSeparateProcessTest) { UT_PTR_SET(PlatformSpecificRunTestInASeperateProcess, StubPlatformSpecificRunTestInASeperateProcess); fixture.getRegistry()->setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("Failed in separate process"); } // There is a possibility that a compiler provides fork but not waitpid. #if !defined(CPPUTEST_HAVE_FORK) || !defined(CPPUTEST_HAVE_WAITPID) IGNORE_TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) {} #else TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) { fixture.setTestFunction(UtestShell::crash); fixture.setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("Failed in separate process - killed by signal"); } #endif #if CPPUTEST_HAVE_EXCEPTIONS static bool destructorWasCalledOnFailedTest = false; static void destructorCalledForLocalObjects_() { SetBooleanOnDestructorCall pleaseCallTheDestructor(destructorWasCalledOnFailedTest); destructorWasCalledOnFailedTest = false; FAIL("fail"); } TEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails) { fixture.setTestFunction(destructorCalledForLocalObjects_); fixture.runAllTests(); CHECK(destructorWasCalledOnFailedTest); } #endif TEST_GROUP(IgnoredUtestShell) { TestTestingFixture fixture; IgnoredUtestShell ignoredTest; ExecFunctionTestShell normalUtestShell; void setup() CPPUTEST_OVERRIDE { fixture.addTest(&ignoredTest); fixture.addTest(&normalUtestShell); } }; TEST(IgnoredUtestShell, doesIgnoreCount) { fixture.runAllTests(); LONGS_EQUAL(1, fixture.getIgnoreCount()); } TEST(IgnoredUtestShell, printsIGNORE_TESTwhenVerbose) { fixture.setOutputVerbose(); fixture.runAllTests(); fixture.assertPrintContains("IGNORE_TEST"); } TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenIncreaseRunCount) { ignoredTest.setRunIgnored(); fixture.runAllTests(); LONGS_EQUAL(3, fixture.getRunCount()); LONGS_EQUAL(0, fixture.getIgnoreCount()); } TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenIncreaseIgnoredCount) { fixture.runAllTests(); LONGS_EQUAL(2, fixture.getRunCount()); LONGS_EQUAL(1, fixture.getIgnoreCount()); } TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedWillNotInfluenceNormalTestCount) { normalUtestShell.setRunIgnored(); fixture.runAllTests(); LONGS_EQUAL(2, fixture.getRunCount()); LONGS_EQUAL(1, fixture.getIgnoreCount()); } TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenReturnTESTInFormattedName) { ignoredTest.setGroupName("TestGroup"); ignoredTest.setTestName("TestName"); ignoredTest.setRunIgnored(); fixture.runAllTests(); STRCMP_EQUAL("TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString()); } TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenReturnIGNORETESTInFormattedName) { ignoredTest.setGroupName("TestGroup"); ignoredTest.setTestName("TestName"); fixture.runAllTests(); STRCMP_EQUAL("IGNORE_TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString()); } TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenWillRunReturnFalse) { CHECK_FALSE(ignoredTest.willRun()); } TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenWillRunReturnTrue) { ignoredTest.setRunIgnored(); CHECK_TRUE(ignoredTest.willRun()); } TEST_BASE(MyOwnTest) { MyOwnTest() : inTest(false) { } bool inTest; void setup() CPPUTEST_OVERRIDE { CHECK(!inTest); inTest = true; } void teardown() CPPUTEST_OVERRIDE { CHECK(inTest); inTest = false; } }; TEST_GROUP_BASE(UtestMyOwn, MyOwnTest) { }; TEST(UtestMyOwn, test) { CHECK(inTest); } class NullParameterTest: public UtestShell { }; TEST(UtestMyOwn, NullParameters) { NullParameterTest nullTest; /* Bug fix tests for creating a test without a name, fix in SimpleString */ TestFilter emptyFilter; CHECK(nullTest.shouldRun(&emptyFilter, &emptyFilter)); } class AllocateAndDeallocateInConstructorAndDestructor { char* memory_; char* morememory_; public: AllocateAndDeallocateInConstructorAndDestructor() { memory_ = new char[100]; morememory_ = NULLPTR; } void allocateMoreMemory() { morememory_ = new char[123]; } ~AllocateAndDeallocateInConstructorAndDestructor() { delete [] memory_; delete [] morememory_; } }; TEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks) { AllocateAndDeallocateInConstructorAndDestructor dummy; }; TEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName) { dummy.allocateMoreMemory(); } static int getZero() { return 0; } static int getOne() { return 1; } TEST_GROUP(UtestShellPointerArrayTest) { UtestShell* test0; UtestShell* test1; UtestShell* test2; void setup() CPPUTEST_OVERRIDE { test0 = new IgnoredUtestShell(); test1 = new IgnoredUtestShell(); test2 = new IgnoredUtestShell(); test0->addTest(test1); test1->addTest(test2); } void teardown() CPPUTEST_OVERRIDE { delete test0; delete test1; delete test2; } }; TEST(UtestShellPointerArrayTest, empty) { UtestShellPointerArray tests(NULLPTR); tests.shuffle(0); CHECK(NULLPTR == tests.getFirstTest()); } TEST(UtestShellPointerArrayTest, testsAreInOrder) { UtestShellPointerArray tests(test0); CHECK(tests.get(0) == test0); CHECK(tests.get(1) == test1); CHECK(tests.get(2) == test2); } TEST(UtestShellPointerArrayTest, relinkingTestsWillKeepThemTheSameWhenNothingWasDone) { UtestShellPointerArray tests(test0); tests.relinkTestsInOrder(); CHECK(tests.get(0) == test0); CHECK(tests.get(1) == test1); CHECK(tests.get(2) == test2); } TEST(UtestShellPointerArrayTest, firstTestisNotTheFirstTestWithSeed1234) { UtestShellPointerArray tests(test0); tests.shuffle(1234); CHECK(tests.getFirstTest() != test0); } TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningZero) { UT_PTR_SET(PlatformSpecificRand, getZero); UtestShellPointerArray tests(test0); tests.shuffle(3); CHECK(tests.get(0) == test1); CHECK(tests.get(1) == test2); CHECK(tests.get(2) == test0); } // swaps with 4 mod 3 (1) then 4 mod 2 (0): 1, [2], [0] --> [1], [0], 2 --> 0, 1, 2 TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningOne) { UT_PTR_SET(PlatformSpecificRand, getOne); UtestShellPointerArray tests(test0); tests.shuffle(3); CHECK(tests.get(0) == test0); CHECK(tests.get(1) == test2); CHECK(tests.get(2) == test1); } TEST(UtestShellPointerArrayTest, reverse) { UT_PTR_SET(PlatformSpecificRand, getOne); UtestShellPointerArray tests(test0); tests.reverse(); CHECK(tests.get(0) == test2); CHECK(tests.get(1) == test1); CHECK(tests.get(2) == test0); }
null
33
cpp
cpputest
TestFilterTest.cpp
tests/CppUTest/TestFilterTest.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/TestFilter.h" TEST_GROUP(TestFilter) { }; TEST(TestFilter, emptyFilterMatchesEverything) { TestFilter filter; CHECK(filter.match("random_name")); CHECK(filter.match("")); CHECK(filter.match("*&%#^&%$(*&^@#(&*@#^(&*$^@#")); } TEST(TestFilter, defaultAbsoluteMismatches) { TestFilter filter("filtername"); CHECK(!filter.match("notevenclose")); CHECK(!filter.match("filterrname")); CHECK(!filter.match("")); } TEST(TestFilter, strictMatching) { TestFilter filter("filter"); filter.strictMatching(); CHECK(filter.match("filter")); CHECK(!filter.match("filterr")); CHECK(!filter.match(" filter")); } TEST(TestFilter, invertMatching) { TestFilter filter("filter"); filter.invertMatching(); CHECK(!filter.match("filter")); CHECK(!filter.match("filterr")); CHECK(filter.match("notevenclose")); CHECK(filter.match("")); } TEST(TestFilter, invertStrictMatching) { TestFilter filter("filter"); filter.invertMatching(); filter.strictMatching(); CHECK(!filter.match("filter")); CHECK(filter.match("filterr")); CHECK(filter.match(" filter")); } TEST(TestFilter, equality) { TestFilter filter1("filter"); TestFilter filter2("filter"); TestFilter filter3("filter3"); CHECK(filter1 == filter2); CHECK(! (filter1 == filter3)); } TEST(TestFilter, equalityWithStrictness) { TestFilter filter1("filter"); TestFilter filter2("filter"); filter2.strictMatching(); CHECK(! (filter1 == filter2)); } TEST(TestFilter, equalityWithInvertion) { TestFilter filter1("filter"); TestFilter filter2("filter"); filter2.invertMatching(); CHECK(! (filter1 == filter2)); } TEST(TestFilter, notEqual) { TestFilter filter1("filter"); TestFilter filter2("filter"); TestFilter filter3("filter3"); CHECK(filter1 != filter3); CHECK(! (filter1 != filter2)); } TEST(TestFilter, stringFrom) { TestFilter filter("filter"); STRCMP_EQUAL("TestFilter: \"filter\"", StringFrom(filter).asCharString()); } TEST(TestFilter, stringFromWithStrictMatching) { TestFilter filter("filter"); filter.strictMatching(); STRCMP_EQUAL("TestFilter: \"filter\" with strict matching", StringFrom(filter).asCharString()); } TEST(TestFilter, stringFromWithInvertMatching) { TestFilter filter("filter"); filter.invertMatching(); STRCMP_EQUAL("TestFilter: \"filter\" with invert matching", StringFrom(filter).asCharString()); } TEST(TestFilter, stringFromWithStrictInvertMatching) { TestFilter filter("filter"); filter.strictMatching(); filter.invertMatching(); STRCMP_EQUAL("TestFilter: \"filter\" with strict, invert matching", StringFrom(filter).asCharString()); } TEST(TestFilter, listOfFilters) { TestFilter *listOfFilters = NULLPTR; TestFilter first("foo"); TestFilter secnd("bar"); listOfFilters = first.add(listOfFilters); listOfFilters = secnd.add(listOfFilters); TestFilter *current = listOfFilters; STRCMP_EQUAL("TestFilter: \"bar\"", StringFrom(*current).asCharString()); current = current->getNext(); STRCMP_EQUAL("TestFilter: \"foo\"", StringFrom(*current).asCharString()); POINTERS_EQUAL(NULLPTR, current->getNext()); } TEST(TestFilter, constructors) { TestFilter filter1; TestFilter filter2(SimpleString("a")); TestFilter filter3("a"); CHECK(filter1.getNext() == NULLPTR); CHECK(filter2.getNext() == NULLPTR); CHECK(filter3.getNext() == NULLPTR); CHECK(filter2.match("ab")); CHECK(filter3.match("ab")); }
null
34
cpp
cpputest
DummyMemoryLeakDetector.cpp
tests/CppUTest/DummyMemoryLeakDetector.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 "DummyMemoryLeakDetector.h" DummyMemoryLeakDetector::DummyMemoryLeakDetector(MemoryLeakFailure* reporter) : MemoryLeakDetector(reporter) { memoryLeakDetectorWasDeleted = false; } DummyMemoryLeakDetector::~DummyMemoryLeakDetector() { memoryLeakDetectorWasDeleted = true; } bool DummyMemoryLeakDetector::wasDeleted() { return memoryLeakDetectorWasDeleted; } bool DummyMemoryLeakDetector::memoryLeakDetectorWasDeleted = false; DummyMemoryLeakFailure::DummyMemoryLeakFailure() : MemoryLeakFailure() { memoryLeakFailureWasDelete = false; } DummyMemoryLeakFailure::~DummyMemoryLeakFailure() { memoryLeakFailureWasDelete = true; } bool DummyMemoryLeakFailure::wasDeleted() { return memoryLeakFailureWasDelete; } void DummyMemoryLeakFailure::fail(char*) { } bool DummyMemoryLeakFailure::memoryLeakFailureWasDelete = false;
null
35
cpp
cpputest
TestInstallerTest.cpp
tests/CppUTest/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" class TestInstallerTestUtestShell : public UtestShell { }; // this is file scope because the test is installed // with all other tests, which also happen to be // created as static instances at file scope TEST_GROUP(TestInstaller) { TestInstaller* testInstaller; TestRegistry* myRegistry; TestInstallerTestUtestShell shell; void setup() CPPUTEST_OVERRIDE { myRegistry = new TestRegistry(); myRegistry->setCurrentRegistry(myRegistry); testInstaller = new TestInstaller(shell, "TestInstaller", "test", __FILE__, __LINE__); } void teardown() CPPUTEST_OVERRIDE { myRegistry->setCurrentRegistry(NULLPTR); testInstaller->unDo(); delete testInstaller; delete myRegistry; } }; TEST(TestInstaller, Create) { }
null
36
cpp
cpputest
AllocLetTestFreeTest.cpp
tests/CppUTest/AllocLetTestFreeTest.cpp
null
#include "CppUTest/StandardCLibrary.h" extern "C" { #include "AllocLetTestFree.h" } #include "CppUTest/TestHarness.h" #if CPPUTEST_USE_STD_C_LIB /* * This test makes sure that memory leak malloc macros are forced into .cpp and .c files */ TEST_GROUP(AllocLetTestFree) { AllocLetTestFree allocLetTestFree; void setup() CPPUTEST_OVERRIDE { allocLetTestFree = AllocLetTestFree_Create(); } void teardown() CPPUTEST_OVERRIDE { AllocLetTestFree_Destroy(allocLetTestFree); } }; TEST(AllocLetTestFree, Create) { free(allocLetTestFree); } #endif
null
37
cpp
cpputest
TestHarness_cTest.cpp
tests/CppUTest/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. */ #include "CppUTest/TestHarness_c.h" #include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" #include "CppUTest/TestOutput.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTest/PlatformSpecificFunctions.h" extern "C" int setup_teardown_was_called_in_test_group_in_C; extern "C" int test_was_called_in_test_group_in_C; int setup_teardown_was_called_in_test_group_in_C = 0; int test_was_called_in_test_group_in_C = 0; TEST_GROUP_C_WRAPPER(TestGroupInC) { TEST_GROUP_C_SETUP_WRAPPER(TestGroupInC) TEST_GROUP_C_TEARDOWN_WRAPPER(TestGroupInC) }; TEST_C_WRAPPER(TestGroupInC, checkThatTheTestHasRun) IGNORE_TEST_C_WRAPPER(TestGroupInC, ignoreMacroForCFile) /* * This test is a bit strange. They use the fact that you can do -r2 for repeating the same run. * When you do so, the same statics will be shared and therefore we can test whether the setup/teardown is run * correctly. */ TEST(TestGroupInC, setupHasBeenCalled) { test_was_called_in_test_group_in_C++; /* Increased in setup, decreased in teardown. So at this point it must be 1 also on a multiple run */ LONGS_EQUAL(1, setup_teardown_was_called_in_test_group_in_C); } static bool hasDestructorOfTheDestructorCheckedBeenCalled; class HasTheDestructorBeenCalledChecker { public: HasTheDestructorBeenCalledChecker(){} ~HasTheDestructorBeenCalledChecker() { hasDestructorOfTheDestructorCheckedBeenCalled = true; } }; TEST_GROUP(TestHarness_c) { TestTestingFixture* fixture; TEST_SETUP() { hasDestructorOfTheDestructorCheckedBeenCalled = false; fixture = new TestTestingFixture(); } TEST_TEARDOWN() { delete fixture; } }; static void failBoolMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_BOOL(1, 0); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkBool) { CHECK_EQUAL_C_BOOL(1, 1); CHECK_EQUAL_C_BOOL(1, 2); fixture->setTestFunction(failBoolMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <true>\n\tbut was <false>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failBoolTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_BOOL_TEXT(1, 0, "BoolTestText"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkBoolText) { CHECK_EQUAL_C_BOOL_TEXT(1, 1, "Text"); CHECK_EQUAL_C_BOOL_TEXT(1, 2, "Text"); fixture->setTestFunction(failBoolTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <true>\n\tbut was <false>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: BoolTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failIntMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_INT(1, 2); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkInt) { CHECK_EQUAL_C_INT(2, 2); fixture->setTestFunction(failIntMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failIntTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_INT_TEXT(1, 2, "IntTestText"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkIntText) { CHECK_EQUAL_C_INT_TEXT(2, 2, "Text"); fixture->setTestFunction(failIntTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: IntTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failUnsignedIntMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_UINT(1, 2); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkUnsignedInt) { CHECK_EQUAL_C_UINT(2, 2); fixture->setTestFunction(failUnsignedIntMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failUnsignedIntTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_UINT_TEXT(1, 2, "UnsignedIntTestText"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkUnsignedIntText) { CHECK_EQUAL_C_UINT_TEXT(2, 2, "Text"); fixture->setTestFunction(failUnsignedIntTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: UnsignedIntTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failLongIntMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_LONG(1, 2); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkLongInt) { CHECK_EQUAL_C_LONG(2, 2); fixture->setTestFunction(failLongIntMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failLongIntTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_LONG_TEXT(1, 2, "LongIntTestText"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkLongIntText) { CHECK_EQUAL_C_LONG_TEXT(2, 2, "Text"); fixture->setTestFunction(failLongIntTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: LongIntTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failUnsignedLongIntMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_ULONG(1, 2); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkUnsignedLongInt) { CHECK_EQUAL_C_ULONG(2, 2); fixture->setTestFunction(failUnsignedLongIntMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failUnsignedLongIntTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_ULONG_TEXT(1, 2, "UnsignedLongIntTestText"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkUnsignedLongIntText) { CHECK_EQUAL_C_ULONG_TEXT(2, 2, "Text"); fixture->setTestFunction(failUnsignedLongIntTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: UnsignedLongIntTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } #if CPPUTEST_USE_LONG_LONG static void failLongLongIntMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_LONGLONG(1, 2); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkLongLongInt) { CHECK_EQUAL_C_LONGLONG(2, 2); fixture->setTestFunction(failLongLongIntMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failLongLongIntTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_LONGLONG_TEXT(1, 2, "LongLongTestText"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkLongLongIntText) { CHECK_EQUAL_C_LONGLONG_TEXT(2, 2, "Text"); fixture->setTestFunction(failLongLongIntTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: LongLongTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failUnsignedLongLongIntMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_ULONGLONG(1, 2); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkUnsignedLongLongInt) { CHECK_EQUAL_C_ULONGLONG(2, 2); fixture->setTestFunction(failUnsignedLongLongIntMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failUnsignedLongLongIntTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_ULONGLONG_TEXT(1, 2, "UnsignedLongLongTestText"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkUnsignedLongLongIntText) { CHECK_EQUAL_C_ULONGLONG_TEXT(2, 2, "Text"); fixture->setTestFunction(failUnsignedLongLongIntTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1 (0x1)>\n\tbut was <2 (0x2)>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: UnsignedLongLongTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } #else static void failLongLongIntMethod_() { cpputest_longlong dummy_longlong; CHECK_EQUAL_C_LONGLONG(dummy_longlong, dummy_longlong); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkLongLongInt) { fixture->setTestFunction(failLongLongIntMethod_); fixture->runAllTests(); fixture->assertPrintContains("is not supported"); fixture->assertPrintContains("arness_c"); } static void failLongLongIntTextMethod_() { cpputest_longlong dummy_longlong; CHECK_EQUAL_C_LONGLONG_TEXT(dummy_longlong, dummy_longlong, "Text"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkLongLongIntText) { fixture->setTestFunction(failLongLongIntTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("is not supported"); fixture->assertPrintContains("arness_c"); } static void failUnsignedLongLongIntMethod_() { cpputest_ulonglong dummy_ulonglong; CHECK_EQUAL_C_ULONGLONG(dummy_ulonglong, dummy_ulonglong); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkUnsignedLongLongInt) { fixture->setTestFunction(failUnsignedLongLongIntMethod_); fixture->runAllTests(); fixture->assertPrintContains("is not supported"); fixture->assertPrintContains("arness_c"); } static void failUnsignedLongLongIntTextMethod_() { cpputest_ulonglong dummy_ulonglong; CHECK_EQUAL_C_ULONGLONG_TEXT(dummy_ulonglong, dummy_ulonglong, "Text"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkUnsignedLongLongIntText) { fixture->setTestFunction(failUnsignedLongLongIntTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("is not supported"); fixture->assertPrintContains("arness_c"); } #endif static void failRealMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_REAL(1.0, 2.0, 0.5); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkReal) { CHECK_EQUAL_C_REAL(1.0, 1.1, 0.5); fixture->setTestFunction(failRealMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1>\n\tbut was <2>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failRealTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_REAL_TEXT(1.0, 2.0, 0.5, "RealTestText"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkRealText) { CHECK_EQUAL_C_REAL_TEXT(1.0, 1.1, 0.5, "Text"); fixture->setTestFunction(failRealTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <1>\n\tbut was <2>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: RealTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failCharMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_CHAR('a', 'c'); } TEST(TestHarness_c, checkChar) { CHECK_EQUAL_C_CHAR('a', 'a'); fixture->setTestFunction(failCharMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <a>\n\tbut was <c>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failCharTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_CHAR_TEXT('a', 'c', "CharTestText"); } TEST(TestHarness_c, checkCharText) { CHECK_EQUAL_C_CHAR_TEXT('a', 'a', "Text"); fixture->setTestFunction(failCharTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <a>\n\tbut was <c>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: CharTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failUnsignedByteMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_UBYTE(254, 253); } TEST(TestHarness_c, checkUnsignedByte) { CHECK_EQUAL_C_UBYTE(254, 254); fixture->setTestFunction(failUnsignedByteMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <254>\n\tbut was <253>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failUnsignedByteTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_UBYTE_TEXT(254, 253, "UnsignedByteTestText"); } TEST(TestHarness_c, checkUnsignedByteText) { CHECK_EQUAL_C_UBYTE_TEXT(254, 254, "Text"); fixture->setTestFunction(failUnsignedByteTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <254>\n\tbut was <253>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: UnsignedByteTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failSignedByteMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_SBYTE(-3, -5); } TEST(TestHarness_c, checkSignedByte) { CHECK_EQUAL_C_SBYTE(-3, -3); fixture->setTestFunction(failSignedByteMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <-3>\n\tbut was <-5>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failSignedByteTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_SBYTE_TEXT(-3, -5, "SignedByteTestText"); } TEST(TestHarness_c, checkSignedByteText) { CHECK_EQUAL_C_SBYTE_TEXT(-3, -3, "Text"); fixture->setTestFunction(failSignedByteTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <-3>\n\tbut was <-5>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: SignedByteTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failStringMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_STRING("Hello", "Hello World"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkString) { CHECK_EQUAL_C_STRING("Hello", "Hello"); fixture->setTestFunction(failStringMethod_); fixture->runAllTests(); StringEqualFailure failure(UtestShell::getCurrent(), "file", 1, "Hello", "Hello World", ""); fixture->assertPrintContains(failure.getMessage()); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failStringTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_STRING_TEXT("Hello", "Hello World", "StringTestText"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkStringText) { CHECK_EQUAL_C_STRING_TEXT("Hello", "Hello", "Text"); fixture->setTestFunction(failStringTextMethod_); fixture->runAllTests(); StringEqualFailure failure(UtestShell::getCurrent(), "file", 1, "Hello", "Hello World", ""); fixture->assertPrintContains(failure.getMessage()); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: StringTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failPointerMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_POINTER(NULLPTR, (void *)0x1); } TEST(TestHarness_c, checkPointer) { CHECK_EQUAL_C_POINTER(NULLPTR, NULLPTR); fixture->setTestFunction(failPointerMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <0x0>\n\tbut was <0x1>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failPointerTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_POINTER_TEXT(NULLPTR, (void *)0x1, "PointerTestText"); } TEST(TestHarness_c, checkPointerText) { CHECK_EQUAL_C_POINTER_TEXT(NULLPTR, NULLPTR, "Text"); fixture->setTestFunction(failPointerTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <0x0>\n\tbut was <0x1>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: PointerTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failMemcmpMethod_() { HasTheDestructorBeenCalledChecker checker; unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 }; CHECK_EQUAL_C_MEMCMP(expectedData, actualData, sizeof(expectedData)); } TEST(TestHarness_c, checkMemcmp) { CHECK_EQUAL_C_MEMCMP("TEST", "TEST", 5); fixture->setTestFunction(failMemcmpMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <00 01 02 03>\n\tbut was <00 01 03 03>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failMemcmpTextMethod_() { HasTheDestructorBeenCalledChecker checker; unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 }; unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 }; CHECK_EQUAL_C_MEMCMP_TEXT(expectedData, actualData, sizeof(expectedData), "MemcmpTestText"); } TEST(TestHarness_c, checkMemcmpText) { CHECK_EQUAL_C_MEMCMP_TEXT("TEST", "TEST", 5, "Text"); fixture->setTestFunction(failMemcmpTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <00 01 02 03>\n\tbut was <00 01 03 03>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: MemcmpTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failBitsMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_BITS(0x0001, (unsigned short)0x0003, 0xFFFF); } TEST(TestHarness_c, checkBits) { CHECK_EQUAL_C_BITS(0xABCD, (unsigned short)0xABCD, 0xFFFF); fixture->setTestFunction(failBitsMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <00000000 00000001>\n\tbut was <00000000 00000011>"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failBitsTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_EQUAL_C_BITS_TEXT(0x0001, (unsigned short)0x0003, 0xFFFF, "BitsTestText"); } TEST(TestHarness_c, checkBitsText) { CHECK_EQUAL_C_BITS_TEXT(0xABCD, (unsigned short)0xABCD, 0xFFFF, "Text"); fixture->setTestFunction(failBitsTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("expected <00000000 00000001>\n\tbut was <00000000 00000011>"); fixture->assertPrintContains("arness_c"); fixture->assertPrintContains("Message: BitsTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failTextMethod_() { HasTheDestructorBeenCalledChecker checker; FAIL_TEXT_C("Booo"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkFailText) { fixture->setTestFunction(failTextMethod_); fixture->runAllTests(); fixture->assertPrintContains("Booo"); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void failMethod_() { HasTheDestructorBeenCalledChecker checker; FAIL_C(); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkFail) { fixture->setTestFunction(failMethod_); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); fixture->assertPrintContains("arness_c"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static bool cpputestHasCrashed; static void crashMethod() { cpputestHasCrashed = true; } TEST(TestHarness_c, doesNotCrashIfNotSetToCrash) { cpputestHasCrashed = false; UtestShell::setCrashMethod(crashMethod); fixture->setTestFunction(failMethod_); fixture->runAllTests(); CHECK_FALSE(cpputestHasCrashed); LONGS_EQUAL(1, fixture->getFailureCount()); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); UtestShell::resetCrashMethod(); } TEST(TestHarness_c, doesCrashIfSetToCrash) { cpputestHasCrashed = false; UtestShell::setCrashOnFail(); UtestShell::setCrashMethod(crashMethod); fixture->setTestFunction(failMethod_); fixture->runAllTests(); CHECK(cpputestHasCrashed); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); UtestShell::restoreDefaultTestTerminator(); UtestShell::resetCrashMethod(); } static void CheckMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_C(false); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkCheck) { CHECK_C(true); fixture->setTestFunction(CheckMethod_); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } static void CheckTextMethod_() { HasTheDestructorBeenCalledChecker checker; CHECK_C_TEXT(false, "CheckTestText"); } // LCOV_EXCL_LINE TEST(TestHarness_c, checkCheckText) { CHECK_C_TEXT(true, "Text"); fixture->setTestFunction(CheckTextMethod_); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); fixture->assertPrintContains("Message: CheckTestText"); CHECK(!hasDestructorOfTheDestructorCheckedBeenCalled); } #if CPPUTEST_USE_MEM_LEAK_DETECTION TEST(TestHarness_c, cpputest_malloc_out_of_memory) { cpputest_malloc_set_out_of_memory(); CHECK(NULLPTR == cpputest_malloc(100)); cpputest_malloc_set_not_out_of_memory(); void * mem = cpputest_malloc(100); CHECK(NULLPTR != mem); cpputest_free(mem); } TEST(TestHarness_c, cpputest_malloc_out_of_memory_after_n_mallocs) { cpputest_malloc_set_out_of_memory_countdown(3); void * m1 = cpputest_malloc(10); void * m2 = cpputest_malloc(11); void * m3 = cpputest_malloc(12); CHECK(m1 != NULLPTR); CHECK(m2 != NULLPTR); CHECK(m3 == NULLPTR); cpputest_malloc_set_not_out_of_memory(); cpputest_free(m1); cpputest_free(m2); } TEST(TestHarness_c, cpputest_malloc_out_of_memory_after_0_mallocs) { cpputest_malloc_set_out_of_memory_countdown(0); void * m1 = cpputest_malloc(10); CHECK(m1 == NULLPTR); cpputest_malloc_set_not_out_of_memory(); } TEST(TestHarness_c, count_mallocs) { cpputest_malloc_count_reset(); void * m1 = cpputest_malloc(10); void * m2 = cpputest_malloc(11); void * m3 = cpputest_malloc(12); cpputest_free(m1); cpputest_free(m2); cpputest_free(m3); LONGS_EQUAL(3, cpputest_malloc_get_count()); } #ifdef CPPUTEST_USE_STRDUP_MACROS TEST(TestHarness_c, cpputest_strdup) { char * mem = cpputest_strdup("0123456789"); CHECK(NULLPTR != mem); STRCMP_EQUAL("0123456789", mem); cpputest_free(mem); } TEST(TestHarness_c, cpputest_strndup) { char * mem = cpputest_strndup("0123456789", 3); CHECK(NULLPTR != mem); STRCMP_EQUAL("012", mem); cpputest_free(mem); } #endif TEST(TestHarness_c, cpputest_calloc) { void * mem = cpputest_calloc(10, 10); CHECK(NULLPTR != mem); cpputest_free(mem); } TEST(TestHarness_c, cpputest_realloc_larger) { const char* number_string = "123456789"; char* mem1 = (char*) cpputest_malloc(10); SimpleString::StrNCpy(mem1, number_string, 10); CHECK(mem1 != NULLPTR); char* mem2 = (char*) cpputest_realloc(mem1, 1000); CHECK(mem2 != NULLPTR); STRCMP_EQUAL(number_string, mem2); cpputest_free(mem2); } #include "CppUTest/MemoryLeakDetector.h" TEST(TestHarness_c, macros) { #if CPPUTEST_USE_MALLOC_MACROS MemoryLeakDetector* memLeakDetector = MemoryLeakWarningPlugin::getGlobalDetector(); size_t memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking); #endif void* mem1 = malloc(10); void* mem2 = calloc(10, 20); void* mem3 = realloc(mem2, 100); #if CPPUTEST_USE_MALLOC_MACROS LONGS_EQUAL(memLeaks + 2, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); #endif free(mem1); free(mem3); #if CPPUTEST_USE_MALLOC_MACROS LONGS_EQUAL(memLeaks, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking)); #endif } TEST(TestHarness_c, callocInitializedToZero) { char* mem = (char*) calloc(20, sizeof(char)); for (int i = 0; i < 20; i++) CHECK(mem[i] == 0); free(mem); } TEST(TestHarness_c, callocShouldReturnNULLWhenOutOfMemory) { cpputest_malloc_set_out_of_memory_countdown(0); void * m = cpputest_calloc(1, 1); CHECK(m == NULLPTR); cpputest_malloc_set_not_out_of_memory(); } #endif
null
38
cpp
cpputest
DummyUTestPlatform.cpp
tests/DummyUTestPlatform/DummyUTestPlatform.cpp
null
#include <CppUTest/PlatformSpecificFunctions.h> typedef char jmp_buf[200]; TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() { return TestOutput::eclipse; } void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) = NULLPTR; int (*PlatformSpecificFork)(void) = NULLPTR; int (*PlatformSpecificWaitPid)(int pid, int* status, int options) = NULLPTR; static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; extern "C" int setjmp(jmp_buf); static int fakeSetJmp(void (*function)(void* data), void* data) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; function(data); jmp_buf_index--; return 1; } return 0; } int (*PlatformSpecificSetJmp)(void (*function)(void*), void* data) = fakeSetJmp; extern "C" void longjmp(jmp_buf, int); static void fakeLongJmp(void) { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } void (*PlatformSpecificLongJmp)(void) = fakeLongJmp; static void fakeRestoreJumpBuffer() { jmp_buf_index--; } void (*PlatformSpecificRestoreJumpBuffer)(void) = fakeRestoreJumpBuffer; static unsigned long fakeTimeInMillis(void) { return 0; } unsigned long (*GetPlatformSpecificTimeInMillis)(void) = fakeTimeInMillis; static const char* fakeTimeString(void) { return ""; } const char* (*GetPlatformSpecificTimeString)() = fakeTimeString; extern "C" int vsnprintf(char*, size_t, const char*, va_list); int (*PlatformSpecificVSNprintf)(char* str, size_t size, const char* format, va_list va_args_list) = vsnprintf; extern "C" double fabs(double); double (*PlatformSpecificFabs)(double d) = fabs; static int fakeIsNan(double d) { return d != d; } int (*PlatformSpecificIsNan)(double d) = fakeIsNan; static int fakeIsInf(double d) { return !fakeIsNan(d) && fakeIsNan(d - d); } int (*PlatformSpecificIsInf)(double d) = fakeIsInf; extern "C" int atexit(void (*func)(void)); int (*PlatformSpecificAtExit)(void (*func)(void)) = atexit; extern "C" void* stdout; PlatformSpecificFile PlatformSpecificStdOut = stdout; extern "C" void* fopen(const char*, const char*); PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = fopen; extern "C" int fputs(const char*, void*); static void fakeFPuts(const char* str, PlatformSpecificFile file) { fputs(str, file); } void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = fakeFPuts; extern "C" int fclose(void* stream); static void fakeFClose(PlatformSpecificFile file) { fclose(file); } void (*PlatformSpecificFClose)(PlatformSpecificFile file) = fakeFClose; extern "C" int fflush(void* stream); static void fakeFlush(void) { fflush(stdout); } void (*PlatformSpecificFlush)(void) = fakeFlush; static void fakeSrand(unsigned int){}; void (*PlatformSpecificSrand)(unsigned int) = fakeSrand; static int fakeRand(void) { return 0; } int (*PlatformSpecificRand)(void) = fakeRand; extern "C" void* malloc(size_t); void* (*PlatformSpecificMalloc)(size_t) = malloc; extern "C" void* realloc(void* ptr, size_t new_size); void* (*PlatformSpecificRealloc)(void* memory, size_t size) = realloc; extern "C" void free(void*); void (*PlatformSpecificFree)(void* memory) = free; extern "C" void* memcpy(void* dest, const void* src, size_t count); void* (*PlatformSpecificMemCpy)(void* s1, const void* s2, size_t size) = memcpy; extern "C" void* memset(void* dest, int ch, size_t count); void* (*PlatformSpecificMemset)(void* mem, int c, size_t size) = memset; static PlatformSpecificMutex fakeMutexCreate(void) { return 0; } PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = fakeMutexCreate; static void fakeMutexFunc(PlatformSpecificMutex) {} void (*PlatformSpecificMutexLock)(PlatformSpecificMutex mtx) = fakeMutexFunc; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex mtx) = fakeMutexFunc; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex mtx) = fakeMutexFunc; extern "C" void abort(void); void (*PlatformSpecificAbort)(void) = abort;
null
39
cpp
cpputest
OrderedTestTest.cpp
tests/CppUTestExt/OrderedTestTest.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" #include "OrderedTestTest.h" TEST_GROUP(TestOrderedTest) { TestTestingFixture* fixture; OrderedTestShell orderedTest; OrderedTestShell orderedTest2; OrderedTestShell orderedTest3; ExecFunctionTestShell normalTest; ExecFunctionTestShell normalTest2; ExecFunctionTestShell normalTest3; OrderedTestShell* orderedTestCache; void setup() CPPUTEST_OVERRIDE { orderedTestCache = OrderedTestShell::getOrderedTestHead(); OrderedTestShell::setOrderedTestHead(NULLPTR); fixture = new TestTestingFixture(); fixture->getRegistry()->unDoLastAddTest(); } void teardown() CPPUTEST_OVERRIDE { delete fixture; OrderedTestShell::setOrderedTestHead(orderedTestCache); } void InstallOrderedTest(OrderedTestShell& test, int level) { OrderedTestInstaller(test, "testgroup", "testname", __FILE__, __LINE__, level); } void InstallNormalTest(UtestShell& test) { TestInstaller(test, "testgroup", "testname", __FILE__, __LINE__); } UtestShell* firstTest() { return fixture->getRegistry()->getFirstTest(); } UtestShell* secondTest() { return firstTest()->getNext(); } }; TEST(TestOrderedTest, TestInstallerSetsFields) { OrderedTestInstaller installer(orderedTest, "testgroup", "testname", "this.cpp", 10, 5); STRCMP_EQUAL("testgroup", orderedTest.getGroup().asCharString()); STRCMP_EQUAL("testname", orderedTest.getName().asCharString()); STRCMP_EQUAL("this.cpp", orderedTest.getFile().asCharString()); LONGS_EQUAL(10, orderedTest.getLineNumber()); LONGS_EQUAL(5, orderedTest.getLevel()); } TEST(TestOrderedTest, InstallOneText) { InstallOrderedTest(orderedTest, 5); CHECK(firstTest() == &orderedTest); } TEST(TestOrderedTest, OrderedTestsAreLast) { InstallNormalTest(normalTest); InstallOrderedTest(orderedTest, 5); CHECK(firstTest() == &normalTest); CHECK(secondTest() == &orderedTest); } TEST(TestOrderedTest, TwoTestsAddedInReverseOrder) { InstallOrderedTest(orderedTest, 5); InstallOrderedTest(orderedTest2, 3); CHECK(firstTest() == &orderedTest2); CHECK(secondTest() == &orderedTest); } TEST(TestOrderedTest, TwoTestsAddedInOrder) { InstallOrderedTest(orderedTest2, 3); InstallOrderedTest(orderedTest, 5); CHECK(firstTest() == &orderedTest2); CHECK(secondTest() == &orderedTest); } TEST(TestOrderedTest, MultipleOrderedTests) { InstallNormalTest(normalTest); InstallOrderedTest(orderedTest2, 3); InstallNormalTest(normalTest2); InstallOrderedTest(orderedTest, 5); InstallNormalTest(normalTest3); InstallOrderedTest(orderedTest3, 7); UtestShell * firstOrderedTest = firstTest()->getNext()->getNext()->getNext(); CHECK(firstOrderedTest == &orderedTest2); CHECK(firstOrderedTest->getNext() == &orderedTest); CHECK(firstOrderedTest->getNext()->getNext() == &orderedTest3); } TEST(TestOrderedTest, MultipleOrderedTests2) { InstallOrderedTest(orderedTest, 3); InstallOrderedTest(orderedTest2, 1); InstallOrderedTest(orderedTest3, 2); CHECK(firstTest() == &orderedTest2); CHECK(secondTest() == &orderedTest3); CHECK(secondTest()->getNext() == &orderedTest); } class OrderedTestTestingFixture { public: static void checkRun(int run) { if(run != run_) { run_ = run; count_ = 0; } } static int count(void) { return count_++; } private: static int run_; static int count_; }; int OrderedTestTestingFixture::run_ = 0; int OrderedTestTestingFixture::count_ = 0; TEST_GROUP(TestOrderedTestMacros) { void setup() CPPUTEST_OVERRIDE { OrderedTestTestingFixture::checkRun(TestRegistry::getCurrentRegistry()->getCurrentRepetition()); } }; TEST(TestOrderedTestMacros, NormalTest) { CHECK(OrderedTestTestingFixture::count() == 0); } TEST_ORDERED(TestOrderedTestMacros, Test2, 2) { CHECK(OrderedTestTestingFixture::count() == 2); } TEST_ORDERED(TestOrderedTestMacros, Test1, 1) { CHECK(OrderedTestTestingFixture::count() == 1); } TEST_ORDERED(TestOrderedTestMacros, Test4, 4) { CHECK(OrderedTestTestingFixture::count() == 4); } TEST_ORDERED(TestOrderedTestMacros, Test3, 3) { CHECK(OrderedTestTestingFixture::count() == 3); } // Test with same level TEST_ORDERED(TestOrderedTestMacros, Test5_1, 5) { CHECK(OrderedTestTestingFixture::count() == 5); } TEST_ORDERED(TestOrderedTestMacros, Test6_1, 6) { CHECK(OrderedTestTestingFixture::count() == 7); } TEST_ORDERED(TestOrderedTestMacros, Test5_2, 5) { CHECK(OrderedTestTestingFixture::count() == 6); } TEST_ORDERED(TestOrderedTestMacros, Test6_2, 6) { CHECK(OrderedTestTestingFixture::count() == 8); } // Test C-Interface TEST_ORDERED(TestOrderedTestMacros, Test10, 10) { CHECK(OrderedTestTestingFixture::count() == 12); } TEST_ORDERED(TestOrderedTestMacros, Test8, 8) { CHECK(OrderedTestTestingFixture::count() == 10); } // Export to be usable in OrderedTestTest_c.c extern "C" { int orderedTestFixtureCWrapper(void) { return OrderedTestTestingFixture::count(); } } TEST_ORDERED_C_WRAPPER(TestOrderedTestMacros, Test11, 11) TEST_ORDERED_C_WRAPPER(TestOrderedTestMacros, Test7, 7) TEST_ORDERED_C_WRAPPER(TestOrderedTestMacros, Test9, 9)
null
40
cpp
cpputest
MockReturnValueTest.cpp
tests/CppUTestExt/MockReturnValueTest.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 "MockFailureReporterForTest.h" TEST_GROUP(MockReturnValueTest) { void teardown() CPPUTEST_OVERRIDE { mock().checkExpectations(); mock().clear(); } }; TEST(MockReturnValueTest, 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(MockReturnValueTest, UnsignedIntegerReturnValue) { unsigned int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); MockActualCall& actual_call = mock().actualCall("foo"); LONGS_EQUAL(expected_value, actual_call.returnValue().getUnsignedIntValue()); LONGS_EQUAL(expected_value, actual_call.returnUnsignedIntValue()); LONGS_EQUAL(expected_value, mock().returnValue().getUnsignedIntValue()); LONGS_EQUAL(expected_value, mock().unsignedIntReturnValue()); } TEST(MockReturnValueTest, PositiveIntReturnValueCanBeRetrievedAsUnsignedInt) { int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); LONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedIntValue()); } TEST(MockReturnValueTest, IntReturnValueCanBeRetrievedAsLongInt) { int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); LONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongIntValue()); } TEST(MockReturnValueTest, UnsignedIntReturnValueCanBeRetrievedAsLongInt) { unsigned int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); LONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongIntValue()); } TEST(MockReturnValueTest, PositiveIntReturnValueCanBeRetrievedAsUnsignedLongInt) { int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); UNSIGNED_LONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongIntValue()); } TEST(MockReturnValueTest, PositiveLongIntReturnValueCanBeRetrievedAsUnsignedLongInt) { long int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); UNSIGNED_LONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongIntValue()); } TEST(MockReturnValueTest, UnsignedIntReturnValueCanBeRetrievedAsUnsignedLongInt) { unsigned int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); UNSIGNED_LONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongIntValue()); } #if CPPUTEST_USE_LONG_LONG TEST(MockReturnValueTest, PositiveIntReturnValueCanBeRetrievedAsUnsignedLongLongInt) { int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); } TEST(MockReturnValueTest, PositiveLongIntReturnValueCanBeRetrievedAsUnsignedLongLongInt) { long int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); } TEST(MockReturnValueTest, PositiveLongLongIntReturnValueCanBeRetrievedAsUnsignedLongLongInt) { long long int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); } TEST(MockReturnValueTest, UnsignedIntReturnValueCanBeRetrievedAsUnsignedLongLongInt) { unsigned int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); } TEST(MockReturnValueTest, UnsignedLongIntReturnValueCanBeRetrievedAsUnsignedLongLongInt) { unsigned long int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); } TEST(MockReturnValueTest, UnsignedLongLongIntReturnValueCanBeRetrieved) { unsigned long long int expected_value = 2ULL; mock().expectOneCall("foo").andReturnValue(expected_value); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); } TEST(MockReturnValueTest, PositiveIntReturnValueCanBeRetrievedAsLongLongInt) { int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); } TEST(MockReturnValueTest, PositiveLongIntReturnValueCanBeRetrievedAsLongLongInt) { long int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); } TEST(MockReturnValueTest, UnsignedIntReturnValueCanBeRetrievedAsLongLongInt) { unsigned int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); } TEST(MockReturnValueTest, UnsignedLongIntReturnValueCanBeRetrievedAsLongLongInt) { unsigned long int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); } TEST(MockReturnValueTest, LongLongIntReturnValueCanBeRetrieved) { long long int expected_value = 2LL; mock().expectOneCall("foo").andReturnValue(expected_value); LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); } #endif TEST(MockReturnValueTest, UnsignedIntegerReturnValueSetsDifferentValues) { unsigned int expected_value = 1; unsigned int another_expected_value = 2; mock().expectOneCall("foo").andReturnValue(expected_value); mock().expectOneCall("foo").andReturnValue(another_expected_value); LONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedIntValue()); LONGS_EQUAL(expected_value, mock().returnValue().getUnsignedIntValue()); LONGS_EQUAL(another_expected_value, mock().actualCall("foo").returnValue().getUnsignedIntValue()); LONGS_EQUAL(another_expected_value, mock().returnValue().getUnsignedIntValue()); } TEST(MockReturnValueTest, UnsignedIntegerReturnValueSetsDifferentValuesWhileParametersAreIgnored) { unsigned int ret_value = 1; unsigned int another_ret_value = 2; mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(ret_value); mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(another_ret_value); LONGS_EQUAL(ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getUnsignedIntValue()); LONGS_EQUAL(ret_value, mock().returnValue().getUnsignedIntValue()); LONGS_EQUAL(another_ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getUnsignedIntValue()); LONGS_EQUAL(another_ret_value, mock().returnValue().getUnsignedIntValue()); } TEST(MockReturnValueTest, WhenADoubleReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { double default_return_value = 10.7; double expected_return_value = default_return_value + 1.3; mock().expectOneCall("foo").andReturnValue(expected_return_value); DOUBLES_EQUAL(expected_return_value, mock().actualCall("foo").returnDoubleValueOrDefault(default_return_value), 0.05); DOUBLES_EQUAL(expected_return_value, mock().returnDoubleValueOrDefault(default_return_value), 0.05); } TEST(MockReturnValueTest, WhenNoDoubleReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { double default_return_value = 7.7; mock().expectOneCall("foo"); DOUBLES_EQUAL(default_return_value, mock().actualCall("foo").returnDoubleValueOrDefault(default_return_value), 0.05); DOUBLES_EQUAL(default_return_value, mock().returnDoubleValueOrDefault(default_return_value), 0.05); } TEST(MockReturnValueTest, WhenAUnsignedIntegerReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { unsigned int default_return_value = 10; unsigned int expected_return_value = default_return_value + 1; mock().expectOneCall("foo").andReturnValue(expected_return_value); LONGS_EQUAL(expected_return_value, mock().actualCall("foo").returnUnsignedIntValueOrDefault(default_return_value)); LONGS_EQUAL(expected_return_value, mock().returnUnsignedIntValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenNoUnsignedIntegerReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { unsigned int default_return_value = 10; mock().expectOneCall("foo"); LONGS_EQUAL(default_return_value, mock().actualCall("foo").returnUnsignedIntValueOrDefault(default_return_value)); LONGS_EQUAL(default_return_value, mock().returnUnsignedIntValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenAUnsignedLongIntegerReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { unsigned long int default_return_value = 121487; unsigned long int expected_return_value = default_return_value + 1; mock().expectOneCall("foo").andReturnValue(expected_return_value); LONGS_EQUAL(expected_return_value, mock().actualCall("foo").returnUnsignedLongIntValueOrDefault(default_return_value)); LONGS_EQUAL(expected_return_value, mock().returnUnsignedLongIntValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenNoUnsignedLongIntegerReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { unsigned long int default_return_value = 7710144; mock().expectOneCall("foo"); LONGS_EQUAL(default_return_value, mock().actualCall("foo").returnUnsignedLongIntValueOrDefault(default_return_value)); LONGS_EQUAL(default_return_value, mock().returnUnsignedLongIntValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenALongIntegerReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { long int default_return_value = 748797; long int expected_return_value = default_return_value + 1; mock().expectOneCall("foo").andReturnValue(expected_return_value); LONGS_EQUAL(expected_return_value, mock().actualCall("foo").returnLongIntValueOrDefault(default_return_value)); LONGS_EQUAL(expected_return_value, mock().returnLongIntValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenNoLongIntegerReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { long int default_return_value = 123659; mock().expectOneCall("foo"); LONGS_EQUAL(default_return_value, mock().actualCall("foo").returnLongIntValueOrDefault(default_return_value)); LONGS_EQUAL(default_return_value, mock().returnLongIntValueOrDefault(default_return_value)); } #if CPPUTEST_USE_LONG_LONG TEST(MockReturnValueTest, WhenAUnsignedLongLongIntegerReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { unsigned long long int default_return_value = 2ULL; unsigned long long int expected_return_value = default_return_value - 1; mock().expectOneCall("foo").andReturnValue(expected_return_value); LONGS_EQUAL(expected_return_value, mock().actualCall("foo").returnUnsignedLongLongIntValueOrDefault(default_return_value)); LONGS_EQUAL(expected_return_value, mock().returnUnsignedLongLongIntValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenNoUnsignedLongLongIntegerReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { unsigned long long int default_return_value = 2ULL; mock().expectOneCall("foo"); LONGS_EQUAL(default_return_value, mock().actualCall("foo").returnUnsignedLongLongIntValueOrDefault(default_return_value)); LONGS_EQUAL(default_return_value, mock().returnUnsignedLongLongIntValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenALongLongIntegerReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { long long int default_return_value = 2LL; long long int expected_return_value = default_return_value - 1; mock().expectOneCall("foo").andReturnValue(expected_return_value); LONGS_EQUAL(expected_return_value, mock().actualCall("foo").returnLongLongIntValueOrDefault(default_return_value)); LONGS_EQUAL(expected_return_value, mock().returnLongLongIntValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenNoLongLongIntegerReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { long long int default_return_value = 2LL; mock().expectOneCall("foo"); LONGS_EQUAL(default_return_value, mock().actualCall("foo").returnLongLongIntValueOrDefault(default_return_value)); LONGS_EQUAL(default_return_value, mock().returnLongLongIntValueOrDefault(default_return_value)); } #endif TEST(MockReturnValueTest, WhenABooleanReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { bool default_return_value = true; bool expected_return_value = false; mock().expectOneCall("foo").andReturnValue(expected_return_value); CHECK_EQUAL(expected_return_value, mock().actualCall("foo").returnBoolValueOrDefault(default_return_value)); CHECK_EQUAL(expected_return_value, mock().returnBoolValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenNoBooleanReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { bool default_return_value = true; mock().expectOneCall("foo"); CHECK_EQUAL(default_return_value, mock().actualCall("foo").returnBoolValueOrDefault(default_return_value)); CHECK_EQUAL(default_return_value, mock().returnBoolValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenAIntegerReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { int default_return_value = 777; int expected_return_value = default_return_value + 1; mock().expectOneCall("foo").andReturnValue(expected_return_value); LONGS_EQUAL(expected_return_value, mock().actualCall("foo").returnIntValueOrDefault(default_return_value)); LONGS_EQUAL(expected_return_value, mock().returnIntValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenNoIntegerReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { int default_return_value = 777; mock().expectOneCall("foo"); LONGS_EQUAL(default_return_value, mock().actualCall("foo").returnIntValueOrDefault(default_return_value)); LONGS_EQUAL(default_return_value, mock().returnIntValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, BooleanReturnValue) { bool expected_value = true; mock().expectOneCall("foo").andReturnValue(true); MockActualCall& actual_call = mock().actualCall("foo"); CHECK_EQUAL(expected_value, actual_call.returnValue().getBoolValue()); CHECK_EQUAL(expected_value, actual_call.returnBoolValue()); CHECK_EQUAL(expected_value, mock().returnValue().getBoolValue()); CHECK_EQUAL(expected_value, mock().boolReturnValue()); } TEST(MockReturnValueTest, BooleanReturnValueSetsDifferentValues) { bool expected_value = true; bool another_expected_value = false; mock().expectOneCall("foo").andReturnValue(expected_value); mock().expectOneCall("foo").andReturnValue(another_expected_value); CHECK_EQUAL(expected_value, mock().actualCall("foo").returnValue().getBoolValue()); CHECK_EQUAL(expected_value, mock().returnValue().getBoolValue()); CHECK_EQUAL(another_expected_value, mock().actualCall("foo").returnValue().getBoolValue()); CHECK_EQUAL(another_expected_value, mock().returnValue().getBoolValue()); } TEST(MockReturnValueTest, BooleanReturnValueSetsDifferentValuesWhileParametersAreIgnored) { bool ret_value = true; bool another_ret_value = false; mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(ret_value); mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(another_ret_value); CHECK_EQUAL(ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getBoolValue()); CHECK_EQUAL(ret_value, mock().returnValue().getBoolValue()); CHECK_EQUAL(another_ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getBoolValue()); CHECK_EQUAL(another_ret_value, mock().returnValue().getBoolValue()); } TEST(MockReturnValueTest, IntegerReturnValue) { int expected_value = 1; mock().expectOneCall("foo").andReturnValue(1); MockActualCall& actual_call = mock().actualCall("foo"); LONGS_EQUAL(expected_value, actual_call.returnValue().getIntValue()); LONGS_EQUAL(expected_value, actual_call.returnIntValue()); LONGS_EQUAL(expected_value, mock().returnValue().getIntValue()); LONGS_EQUAL(expected_value, mock().intReturnValue()); } TEST(MockReturnValueTest, IntegerReturnValueSetsDifferentValues) { int expected_value = 1; int another_expected_value = -1; mock().expectOneCall("foo").andReturnValue(expected_value); mock().expectOneCall("foo").andReturnValue(another_expected_value); LONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getIntValue()); LONGS_EQUAL(expected_value, mock().returnValue().getIntValue()); LONGS_EQUAL(another_expected_value, mock().actualCall("foo").returnValue().getIntValue()); LONGS_EQUAL(another_expected_value, mock().returnValue().getIntValue()); } TEST(MockReturnValueTest, IntegerReturnValueSetsDifferentValuesWhileParametersAreIgnored) { int ret_value = 1; int another_ret_value = -1; mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(ret_value); mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(another_ret_value); LONGS_EQUAL(ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getIntValue()); LONGS_EQUAL(ret_value, mock().returnValue().getIntValue()); LONGS_EQUAL(another_ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getIntValue()); LONGS_EQUAL(another_ret_value, mock().returnValue().getIntValue()); } TEST(MockReturnValueTest, LongIntegerReturnValue) { long int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); MockActualCall& actual_call = mock().actualCall("foo"); LONGS_EQUAL(expected_value, actual_call.returnValue().getLongIntValue()); LONGS_EQUAL(expected_value, actual_call.returnLongIntValue()); LONGS_EQUAL(expected_value, mock().returnValue().getLongIntValue()); LONGS_EQUAL(expected_value, mock().longIntReturnValue()); } TEST(MockReturnValueTest, LongIntegerReturnValueSetsDifferentValues) { long int expected_value = 1; long int another_expected_value = 2; mock().expectOneCall("foo").andReturnValue(expected_value); mock().expectOneCall("foo").andReturnValue(another_expected_value); LONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongIntValue()); LONGS_EQUAL(expected_value, mock().returnValue().getLongIntValue()); LONGS_EQUAL(another_expected_value, mock().actualCall("foo").returnValue().getLongIntValue()); LONGS_EQUAL(another_expected_value, mock().returnValue().getLongIntValue()); } TEST(MockReturnValueTest, LongIntegerReturnValueSetsDifferentValuesWhileParametersAreIgnored) { long int ret_value = 1; long int another_ret_value = 2; mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(ret_value); mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(another_ret_value); LONGS_EQUAL(ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getLongIntValue()); LONGS_EQUAL(ret_value, mock().returnValue().getLongIntValue()); LONGS_EQUAL(another_ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getLongIntValue()); LONGS_EQUAL(another_ret_value, mock().returnValue().getLongIntValue()); } TEST(MockReturnValueTest, UnsignedLongIntegerReturnValue) { unsigned long int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); MockActualCall& actual_call = mock().actualCall("foo"); LONGS_EQUAL(expected_value, actual_call.returnValue().getUnsignedLongIntValue()); LONGS_EQUAL(expected_value, actual_call.returnUnsignedLongIntValue()); LONGS_EQUAL(expected_value, mock().returnValue().getUnsignedLongIntValue()); LONGS_EQUAL(expected_value, mock().unsignedLongIntReturnValue()); } TEST(MockReturnValueTest, UnsignedLongIntegerReturnValueSetsDifferentValues) { unsigned long int expected_value = 1; unsigned long int another_expected_value = 2; mock().expectOneCall("foo").andReturnValue(expected_value); mock().expectOneCall("foo").andReturnValue(another_expected_value); LONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongIntValue()); LONGS_EQUAL(expected_value, mock().returnValue().getUnsignedLongIntValue()); LONGS_EQUAL(another_expected_value, mock().actualCall("foo").returnValue().getUnsignedLongIntValue()); LONGS_EQUAL(another_expected_value, mock().returnValue().getUnsignedLongIntValue()); } TEST(MockReturnValueTest, UnsignedLongIntegerReturnValueSetsDifferentValuesWhileParametersAreIgnored) { unsigned long int ret_value = 1; unsigned long int another_ret_value = 2; mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(ret_value); mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(another_ret_value); LONGS_EQUAL(ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getUnsignedLongIntValue()); LONGS_EQUAL(ret_value, mock().returnValue().getUnsignedLongIntValue()); LONGS_EQUAL(another_ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getUnsignedLongIntValue()); LONGS_EQUAL(another_ret_value, mock().returnValue().getUnsignedLongIntValue()); } #if CPPUTEST_USE_LONG_LONG TEST(MockReturnValueTest, LongLongIntegerReturnValue) { long long int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); MockActualCall& actual_call = mock().actualCall("foo"); LONGLONGS_EQUAL(expected_value, actual_call.returnValue().getLongLongIntValue()); LONGLONGS_EQUAL(expected_value, actual_call.returnLongLongIntValue()); LONGLONGS_EQUAL(expected_value, mock().returnValue().getLongLongIntValue()); LONGLONGS_EQUAL(expected_value, mock().longLongIntReturnValue()); } TEST(MockReturnValueTest, LongLongIntegerReturnValueSetsDifferentValues) { long long int expected_value = 1; long long int another_expected_value = 2; mock().expectOneCall("foo").andReturnValue(expected_value); mock().expectOneCall("foo").andReturnValue(another_expected_value); LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); LONGLONGS_EQUAL(expected_value, mock().returnValue().getLongLongIntValue()); LONGLONGS_EQUAL(another_expected_value, mock().actualCall("foo").returnValue().getLongLongIntValue()); LONGLONGS_EQUAL(another_expected_value, mock().returnValue().getLongLongIntValue()); } TEST(MockReturnValueTest, LongLongIntegerReturnValueSetsDifferentValuesWhileParametersAreIgnored) { long long int ret_value = 1; long long int another_ret_value = 2; mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(ret_value); mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(another_ret_value); LONGLONGS_EQUAL(ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getLongLongIntValue()); LONGLONGS_EQUAL(ret_value, mock().returnValue().getLongLongIntValue()); LONGLONGS_EQUAL(another_ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getLongLongIntValue()); LONGLONGS_EQUAL(another_ret_value, mock().returnValue().getLongLongIntValue()); } TEST(MockReturnValueTest, UnsignedLongLongIntegerReturnValue) { unsigned long long int expected_value = 7; mock().expectOneCall("foo").andReturnValue(expected_value); MockActualCall& actual_call = mock().actualCall("foo"); UNSIGNED_LONGLONGS_EQUAL(expected_value, actual_call.returnValue().getUnsignedLongLongIntValue()); UNSIGNED_LONGLONGS_EQUAL(expected_value, actual_call.returnUnsignedLongLongIntValue()); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().returnValue().getUnsignedLongLongIntValue()); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().unsignedLongLongIntReturnValue()); } TEST(MockReturnValueTest, UnsignedLongLongIntegerReturnValueSetsDifferentValues) { unsigned long long int expected_value = 1; unsigned long long int another_expected_value = 2; mock().expectOneCall("foo").andReturnValue(expected_value); mock().expectOneCall("foo").andReturnValue(another_expected_value); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock().returnValue().getUnsignedLongLongIntValue()); UNSIGNED_LONGLONGS_EQUAL(another_expected_value, mock().actualCall("foo").returnValue().getUnsignedLongLongIntValue()); UNSIGNED_LONGLONGS_EQUAL(another_expected_value, mock().returnValue().getUnsignedLongLongIntValue()); } TEST(MockReturnValueTest, UnsignedLongLongIntegerReturnValueSetsDifferentValuesWhileParametersAreIgnored) { unsigned long long int ret_value = 1; unsigned long long int another_ret_value = 2; mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(ret_value); mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters().andReturnValue(another_ret_value); UNSIGNED_LONGLONGS_EQUAL(ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getUnsignedLongLongIntValue()); UNSIGNED_LONGLONGS_EQUAL(ret_value, mock().returnValue().getUnsignedLongLongIntValue()); UNSIGNED_LONGLONGS_EQUAL(another_ret_value, mock().actualCall("foo").withParameter("p1", 1).returnValue().getUnsignedLongLongIntValue()); UNSIGNED_LONGLONGS_EQUAL(another_ret_value, mock().returnValue().getUnsignedLongLongIntValue()); } #endif TEST(MockReturnValueTest, MatchingReturnValueOnWhileSignature) { mock().expectOneCall("foo").withParameter("p1", 1).andReturnValue(1); 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(MockReturnValueTest, WhenAStringReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { const char * default_return_value = "default"; const char * expected_return_value = "expected"; mock().expectOneCall("foo").andReturnValue(expected_return_value); STRCMP_EQUAL(expected_return_value, mock().actualCall("foo").returnStringValueOrDefault(default_return_value)); STRCMP_EQUAL(expected_return_value, mock().returnStringValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenNoStringReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { const char * default_return_value = "default"; mock().expectOneCall("foo"); STRCMP_EQUAL(default_return_value, mock().actualCall("foo").returnStringValueOrDefault(default_return_value)); STRCMP_EQUAL(default_return_value, mock().returnStringValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, StringReturnValue) { mock().expectOneCall("foo").andReturnValue("hello world"); MockActualCall& actual_call = mock().actualCall("foo"); STRCMP_EQUAL("hello world", actual_call.returnValue().getStringValue()); STRCMP_EQUAL("hello world", actual_call.returnStringValue()); STRCMP_EQUAL("hello world", mock().stringReturnValue()); } TEST(MockReturnValueTest, DoubleReturnValue) { double expected_return_value = 7.8; mock().expectOneCall("foo").andReturnValue(expected_return_value); MockActualCall& actual_call = mock().actualCall("foo"); DOUBLES_EQUAL(expected_return_value, actual_call.returnValue().getDoubleValue(), 0.05); DOUBLES_EQUAL(expected_return_value, actual_call.returnDoubleValue(), 0.05); DOUBLES_EQUAL(expected_return_value, mock().doubleReturnValue(), 0.05); } TEST(MockReturnValueTest, WhenAConstPointerReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { const void * default_return_value = (void*) 0x7778; const void * expected_return_value = (void*) 0x144010; mock().expectOneCall("foo").andReturnValue(expected_return_value); POINTERS_EQUAL(expected_return_value, mock().actualCall("foo").returnConstPointerValueOrDefault(default_return_value)); POINTERS_EQUAL(expected_return_value, mock().returnConstPointerValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenNoConstPointerReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { const void * default_return_value = (void*) 0x11; mock().expectOneCall("foo"); POINTERS_EQUAL(default_return_value, mock().actualCall("foo").returnConstPointerValueOrDefault(default_return_value)); POINTERS_EQUAL(default_return_value, mock().returnConstPointerValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenAPointerReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { void * default_return_value = (void*) 0x777; void * expected_return_value = (void*) 0x144000; mock().expectOneCall("foo").andReturnValue(expected_return_value); POINTERS_EQUAL(expected_return_value, mock().actualCall("foo").returnPointerValueOrDefault(default_return_value)); POINTERS_EQUAL(expected_return_value, mock().returnPointerValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenNoPointerReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { void * default_return_value = (void*) 0x10; mock().expectOneCall("foo"); POINTERS_EQUAL(default_return_value, mock().actualCall("foo").returnPointerValueOrDefault(default_return_value)); POINTERS_EQUAL(default_return_value, mock().returnPointerValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenAFunctionPointerReturnValueIsExpectedAndAlsoThereIsADefaultShouldlIgnoreTheDefault) { void (*default_return_value)() = (void(*)()) 0x777; void (*expected_return_value)() = (void(*)()) 0x144000; mock().expectOneCall("foo").andReturnValue(expected_return_value); FUNCTIONPOINTERS_EQUAL(expected_return_value, mock().actualCall("foo").returnFunctionPointerValueOrDefault(default_return_value)); FUNCTIONPOINTERS_EQUAL(expected_return_value, mock().returnFunctionPointerValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, WhenNoFunctionPointerReturnValueIsExpectedButThereIsADefaultShouldlUseTheDefaultValue) { void (*default_return_value)() = (void(*)()) 0x10; mock().expectOneCall("foo"); FUNCTIONPOINTERS_EQUAL(default_return_value, mock().actualCall("foo").returnFunctionPointerValueOrDefault(default_return_value)); FUNCTIONPOINTERS_EQUAL(default_return_value, mock().returnFunctionPointerValueOrDefault(default_return_value)); } TEST(MockReturnValueTest, PointerReturnValue) { void* ptr = (void*) 0x00107; mock().expectOneCall("foo").andReturnValue(ptr); MockActualCall& actual_call = mock().actualCall("foo"); POINTERS_EQUAL(ptr, actual_call.returnValue().getPointerValue()); POINTERS_EQUAL(ptr, actual_call.returnPointerValue()); POINTERS_EQUAL(ptr, mock().pointerReturnValue()); } TEST(MockReturnValueTest, ConstPointerReturnValue) { const void* ptr = (const void*) 0x001074; mock().expectOneCall("foo").andReturnValue(ptr); MockActualCall& actual_call = mock().actualCall("foo"); POINTERS_EQUAL(ptr, actual_call.returnValue().getConstPointerValue()); POINTERS_EQUAL(ptr, actual_call.returnConstPointerValue()); POINTERS_EQUAL(ptr, mock().constPointerReturnValue()); } TEST(MockReturnValueTest, FunctionPointerReturnValue) { void (*ptr)() = (void(*)()) 0x00107; mock().expectOneCall("foo").andReturnValue(ptr); MockActualCall& actual_call = mock().actualCall("foo"); FUNCTIONPOINTERS_EQUAL(ptr, actual_call.returnValue().getFunctionPointerValue()); FUNCTIONPOINTERS_EQUAL(ptr, actual_call.returnFunctionPointerValue()); FUNCTIONPOINTERS_EQUAL(ptr, mock().functionPointerReturnValue()); } TEST(MockReturnValueTest, whenCallingDisabledOrIgnoredActualCallsThenTheyDontReturnPreviousCallsValues) { mock().expectOneCall("boo").ignoreOtherParameters().andReturnValue(10); mock().ignoreOtherCalls(); mock().actualCall("boo"); mock().actualCall("An Ignored Call"); CHECK(!mock().hasReturnValue()); }
null
41
cpp
cpputest
IEEE754PluginTest_c.h
tests/CppUTestExt/IEEE754PluginTest_c.h
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. */ #ifndef IEEE754PLUGINTEST_C_H #define IEEE754PLUGINTEST_C_H #ifdef __cplusplus extern "C" { #endif void set_divisionbyzero_c(void); void set_overflow_c(void); void set_underflow_c(void); void set_inexact_c(void); void set_nothing_c(void); void set_everything_c(void); #ifdef __cplusplus } #endif #endif /* IEEE754PLUGINTEST_C_H */
null
42
cpp
cpputest
MockFailureTest.cpp
tests/CppUTestExt/MockFailureTest.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/MockCheckedExpectedCall.h" #include "CppUTestExt/MockExpectedCallsList.h" #include "MockFailureReporterForTest.h" TEST_GROUP(MockFailureTest) { MockFailureReporter reporter; MockExpectedCallsList *list; MockCheckedExpectedCall* call1; MockCheckedExpectedCall* call2; MockCheckedExpectedCall* call3; MockCheckedExpectedCall* call4; MockCheckedExpectedCall* call5; void setup () CPPUTEST_OVERRIDE { list = new MockExpectedCallsList; call1 = new MockCheckedExpectedCall; call2 = new MockCheckedExpectedCall; call3 = new MockCheckedExpectedCall; call4 = new MockCheckedExpectedCall; call5 = new MockCheckedExpectedCall; } void teardown () CPPUTEST_OVERRIDE { delete list; delete call1; delete call2; delete call3; delete call4; delete call5; CHECK_NO_MOCK_FAILURE(); MockFailureReporterForTest::clearReporter(); } void addThreeCallsToList() { list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); } void addFiveCallsToList() { list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); list->addExpectedCall(call4); list->addExpectedCall(call5); } void checkUnexpectedNthCallMessage(unsigned int count, const char* expectedOrdinal) { MockExpectedCallsList callList; MockCheckedExpectedCall expectedCallSingle(1); MockCheckedExpectedCall expectedCallMulti(count-1); expectedCallSingle.withName("bar"); expectedCallMulti.withName("bar"); if (count > 1) { callList.addExpectedCall(&expectedCallSingle); expectedCallSingle.callWasMade(1); } if (count > 2) { callList.addExpectedCall(&expectedCallMulti); for (unsigned int i = 1; i < (count - 1); i++) { expectedCallMulti.callWasMade(i+1); } } MockUnexpectedCallHappenedFailure failure(UtestShell::getCurrent(), "bar", callList); SimpleString expectedMessage = StringFromFormat("Mock Failure: Unexpected additional (%s) call to function: bar\n\tEXPECTED", expectedOrdinal); STRCMP_CONTAINS(expectedMessage.asCharString(), failure.getMessage().asCharString()); } }; TEST(MockFailureTest, noErrorFailureSomethingGoneWrong) { MockFailure failure(UtestShell::getCurrent()); STRCMP_EQUAL("Test failed with MockFailure without an error! Something went seriously wrong.", failure.getMessage().asCharString()); } TEST(MockFailureTest, unexpectedCallHappened) { MockUnexpectedCallHappenedFailure failure(UtestShell::getCurrent(), "foobar", *list); STRCMP_EQUAL("Mock Failure: Unexpected call to function: foobar\n" "\tEXPECTED calls that WERE NOT fulfilled:\n" "\t\t<none>\n" "\tEXPECTED calls that WERE fulfilled:\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); addThreeCallsToList(); MockExpectedCallsDidntHappenFailure failure(UtestShell::getCurrent(), *list); STRCMP_EQUAL("Mock Failure: Expected call WAS NOT fulfilled.\n" "\tEXPECTED calls that WERE NOT fulfilled:\n" "\t\tfoobar -> no parameters (expected 1 call, called 0 times)\n" "\t\tworld -> int boo: <2 (0x2)>, const char* hello: <world> (expected 1 call, called 0 times)\n" "\tEXPECTED calls that WERE fulfilled:\n" "\t\thaphaphap -> no parameters (expected 1 call, called 1 time)", failure.getMessage().asCharString()); } TEST(MockFailureTest, MockUnexpectedNthAdditionalCallFailure) { checkUnexpectedNthCallMessage(2, "2nd"); checkUnexpectedNthCallMessage(3, "3rd"); checkUnexpectedNthCallMessage(4, "4th"); checkUnexpectedNthCallMessage(11, "11th"); checkUnexpectedNthCallMessage(12, "12th"); checkUnexpectedNthCallMessage(13, "13th"); checkUnexpectedNthCallMessage(14, "14th"); checkUnexpectedNthCallMessage(21, "21st"); checkUnexpectedNthCallMessage(22, "22nd"); checkUnexpectedNthCallMessage(23, "23rd"); } TEST(MockFailureTest, MockUnexpectedInputParameterFailure) { call1->withName("foo").withParameter("boo", 2); call2->withName("foo").withParameter("boo", 3.3); call3->withName("unrelated"); addThreeCallsToList(); MockNamedValue actualParameter("bar"); actualParameter.setValue(2); MockUnexpectedInputParameterFailure failure(UtestShell::getCurrent(), "foo", actualParameter, *list); STRCMP_EQUAL("Mock Failure: Unexpected parameter name to function \"foo\": bar\n" "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" "\t\tfoo -> int boo: <2 (0x2)> (expected 1 call, called 0 times)\n" "\t\tfoo -> double boo: <3.3> (expected 1 call, called 0 times)\n" "\tEXPECTED calls that WERE fulfilled related to function: foo\n" "\t\t<none>\n" "\tACTUAL unexpected parameter passed to function: foo\n" "\t\tint bar: <2 (0x2)>", failure.getMessage().asCharString()); } TEST(MockFailureTest, MockUnexpectedOutputParameterFailure) { int out1; int out2; call1->withName("foo").withOutputParameterReturning("boo", &out1, sizeof(out1)); call2->withName("foo").withOutputParameterReturning("boo", &out2, sizeof(out2)); call3->withName("unrelated"); addThreeCallsToList(); MockNamedValue actualParameter("bar"); actualParameter.setValue((void *)0x123); MockUnexpectedOutputParameterFailure failure(UtestShell::getCurrent(), "foo", actualParameter, *list); STRCMP_EQUAL("Mock Failure: Unexpected output parameter name to function \"foo\": bar\n" "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" "\t\tfoo -> const void* boo: <output> (expected 1 call, called 0 times)\n" "\t\tfoo -> const void* boo: <output> (expected 1 call, called 0 times)\n" "\tEXPECTED calls that WERE fulfilled related to function: foo\n" "\t\t<none>\n" "\tACTUAL unexpected output parameter passed to function: foo\n" "\t\tvoid* bar", failure.getMessage().asCharString()); } TEST(MockFailureTest, MockUnexpectedUnmodifiedOutputParameterFailure) { int out1; call1->withName("foo").withOutputParameterReturning("boo", &out1, sizeof(out1)); call2->withName("foo").withUnmodifiedOutputParameter("boo"); call3->withName("unrelated"); addThreeCallsToList(); MockNamedValue actualParameter("bar"); actualParameter.setValue((void *)0x123); MockUnexpectedOutputParameterFailure failure(UtestShell::getCurrent(), "foo", actualParameter, *list); STRCMP_EQUAL("Mock Failure: Unexpected output parameter name to function \"foo\": bar\n" "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" "\t\tfoo -> const void* boo: <output> (expected 1 call, called 0 times)\n" "\t\tfoo -> const void* boo: <output> (expected 1 call, called 0 times)\n" "\tEXPECTED calls that WERE fulfilled related to function: foo\n" "\t\t<none>\n" "\tACTUAL unexpected output parameter passed to function: foo\n" "\t\tvoid* bar", failure.getMessage().asCharString()); } TEST(MockFailureTest, MockUnexpectedParameterValueFailure) { call1->withName("foo").withParameter("boo", 2); call2->withName("foo").withParameter("boo", 10); call3->withName("unrelated"); addThreeCallsToList(); MockNamedValue actualParameter("boo"); actualParameter.setValue(20); MockUnexpectedInputParameterFailure failure(UtestShell::getCurrent(), "foo", actualParameter, *list); STRCMP_EQUAL("Mock Failure: Unexpected parameter value to parameter \"boo\" to function \"foo\": <20 (0x14)>\n" "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" "\t\tfoo -> int boo: <2 (0x2)> (expected 1 call, called 0 times)\n" "\t\tfoo -> int boo: <10 (0xa)> (expected 1 call, called 0 times)\n" "\tEXPECTED calls that WERE fulfilled related to function: foo\n" "\t\t<none>\n" "\tACTUAL unexpected parameter passed to function: foo\n" "\t\tint boo: <20 (0x14)>", failure.getMessage().asCharString()); } TEST(MockFailureTest, MockExpectedParameterDidntHappenFailure) { call1->withName("foo").withParameter("bar", 2).withParameter("boo", "str"); call1->inputParameterWasPassed("bar"); call2->withName("foo").withParameter("bar", 10).withParameter("boo", "bleh"); call2->callWasMade(1); call2->inputParameterWasPassed("bar"); call2->inputParameterWasPassed("boo"); call3->withName("foo").withParameter("bar", 2).withParameter("boo", "blah").withParameter("baa", 0u); call3->inputParameterWasPassed("bar"); call4->withName("foo").withParameter("bar", 20); call5->withName("unrelated"); addFiveCallsToList(); MockExpectedCallsList matchingCalls; matchingCalls.addExpectedCall(call1); matchingCalls.addExpectedCall(call3); MockExpectedParameterDidntHappenFailure failure(UtestShell::getCurrent(), "foo", *list, matchingCalls); STRCMP_EQUAL("Mock Failure: Expected parameter for function \"foo\" did not happen.\n" "\tEXPECTED calls with MISSING parameters related to function: foo\n" "\t\tfoo -> int bar: <2 (0x2)>, const char* boo: <str> (expected 1 call, called 0 times)\n" "\t\t\tMISSING parameters: const char* boo\n" "\t\tfoo -> int bar: <2 (0x2)>, const char* boo: <blah>, unsigned int baa: <0 (0x0)> (expected 1 call, called 0 times)\n" "\t\t\tMISSING parameters: const char* boo, unsigned int baa\n" "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" "\t\tfoo -> int bar: <2 (0x2)>, const char* boo: <str> (expected 1 call, called 0 times)\n" "\t\tfoo -> int bar: <2 (0x2)>, const char* boo: <blah>, unsigned int baa: <0 (0x0)> (expected 1 call, called 0 times)\n" "\t\tfoo -> int bar: <20 (0x14)> (expected 1 call, called 0 times)\n" "\tEXPECTED calls that WERE fulfilled related to function: foo\n" "\t\tfoo -> int bar: <10 (0xa)>, const char* boo: <bleh> (expected 1 call, called 1 time)", failure.getMessage().asCharString()); } TEST(MockFailureTest, MockNoWayToCompareCustomTypeFailure) { MockNoWayToCompareCustomTypeFailure failure(UtestShell::getCurrent(), "myType"); STRCMP_EQUAL("MockFailure: No way to compare type <myType>. Please install a MockNamedValueComparator.", 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"); addThreeCallsToList(); MockUnexpectedObjectFailure failure(UtestShell::getCurrent(), "foo", (void*)0x1, *list); STRCMP_EQUAL(StringFromFormat ( "MockFailure: Function called on an unexpected object: foo\n" "\tActual object for call has address: <%p>\n" "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" "\t\t(object address: %p)::foo -> no parameters (expected 1 call, called 0 times)\n" "\tEXPECTED calls that WERE fulfilled related to function: foo\n" "\t\t(object address: %p)::foo -> no parameters (expected 1 call, called 1 time)", (void*) 0x01, (void*) 0x02, (void*) 0x03).asCharString(), failure.getMessage().asCharString()); } TEST(MockFailureTest, MockExpectedObjectDidntHappenFailure) { call1->withName("foo").onObject((void*) 0x02); call2->withName("foo").onObject((void*) 0x03); call2->callWasMade(1); call2->wasPassedToObject(); call3->withName("unrelated"); addThreeCallsToList(); MockExpectedObjectDidntHappenFailure failure(UtestShell::getCurrent(), "foo", *list); STRCMP_EQUAL(StringFromFormat( "Mock Failure: Expected call on object for function \"foo\" but it did not happen.\n" "\tEXPECTED calls that WERE NOT fulfilled related to function: foo\n" "\t\t(object address: %p)::foo -> no parameters (expected 1 call, called 0 times)\n" "\tEXPECTED calls that WERE fulfilled related to function: foo\n" "\t\t(object address: %p)::foo -> no parameters (expected 1 call, called 1 time)", (void*) 0x2, (void*) 0x3).asCharString(), failure.getMessage().asCharString()); }
null
43
cpp
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 "CppUTest/SimpleStringInternalCache.h" #include "CppUTestExt/MemoryReporterPlugin.h" #include "CppUTestExt/MockSupportPlugin.h" #ifdef CPPUTEST_INCLUDE_GTEST_TESTS #include "CppUTestExt/GTestConvertor.h" #endif int main(int ac, const char *const *av) { int result = 0; GlobalSimpleStringCache simpleStringCache; { #ifdef CPPUTEST_INCLUDE_GTEST_TESTS GTestConvertor convertor; convertor.addAllGTestToTestRegistry(); #endif MemoryReporterPlugin plugin; MockSupportPlugin mockPlugin; TestRegistry::getCurrentRegistry()->installPlugin(&plugin); TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin); #ifndef GMOCK_RENAME_MAIN result = CommandLineTestRunner::RunAllTests(ac, av); #else /* Don't have any memory leak detector when running the Google Test tests */ testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity; ConsoleTestOutput output; CommandLineTestRunner runner(ac, av, TestRegistry::getCurrentRegistry()); result = runner.runAllTestsMain(); #endif } return result; }
null
44
cpp
cpputest
OrderedTestTest.h
tests/CppUTestExt/OrderedTestTest.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 ORDEREDTESTTEST_H #define ORDEREDTESTTEST_H #ifdef __cplusplus extern "C" { #endif extern int orderedTestFixtureCWrapper(void); #ifdef __cplusplus } #endif #endif /* ORDEREDTESTTEST_H */
null
45
cpp
cpputest
GTest2ConvertorTest.cpp
tests/CppUTestExt/GTest2ConvertorTest.cpp
null
/* * Copyright (c) 2011, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef CPPUTEST_INCLUDE_GTEST_TESTS #include "CppUTestExt/GTestConvertor.h" class GTestTestingFixtureTest : public testing::Test { protected: bool setup_was_called; char* freed_during_teardown; void SetUp() CPPUTEST_OVERRIDE { setup_was_called = true; freed_during_teardown = NULL; } void TearDown() CPPUTEST_OVERRIDE { delete [] freed_during_teardown; } }; TEST_F(GTestTestingFixtureTest, setupBeenCalled) { EXPECT_TRUE(setup_was_called); } TEST_F(GTestTestingFixtureTest, teardownMustBeCalledOrElseThisWillLeak) { freed_during_teardown = new char[100]; } #endif #undef TEST #include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" #include "CppUTest/TestTestingFixture.h" TEST_GROUP(GTestConvertor) { }; #ifdef CPPUTEST_INCLUDE_GTEST_TESTS /* * These tests depend on the amount of GTests that are actually added (also in other files). * This is due to the singleton in gtest. * */ TEST(GTestConvertor, correctNumberOfTestCases) { LONGS_EQUAL(2, ::testing::UnitTest::GetInstance()->total_test_case_count()); CHECK(::testing::UnitTest::GetInstance()->GetTestCase(0)); CHECK(::testing::UnitTest::GetInstance()->GetTestCase(1)); CHECK(::testing::UnitTest::GetInstance()->GetTestCase(2) == NULL); } TEST(GTestConvertor, correctNumberOfTestsInTheTestCases) { const ::testing::TestCase* firstTestCase = ::testing::UnitTest::GetInstance()->GetTestCase(0); const ::testing::TestCase* secondTestCase = ::testing::UnitTest::GetInstance()->GetTestCase(1); STRCMP_EQUAL("GTestSimpleTest", firstTestCase->name()); STRCMP_EQUAL("GTestTestingFixtureTest", secondTestCase->name()); LONGS_EQUAL(7, firstTestCase->total_test_count()); LONGS_EQUAL(2, secondTestCase->total_test_count()); } TEST(GTestConvertor, testsGetAddedToCurrentTestRegistry) { TestTestingFixture fixture; TestRegistry::getCurrentRegistry()->unDoLastAddTest(); GTestConvertor convertor(false); convertor.addAllGTestToTestRegistry(); LONGS_EQUAL(9, TestRegistry::getCurrentRegistry()->countTests()); } #endif
null
46
cpp
cpputest
GTest1Test.cpp
tests/CppUTestExt/GTest1Test.cpp
null
/* * Copyright (c) 2011, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef CPPUTEST_INCLUDE_GTEST_TESTS #undef new #include "CppUTestExt/GTest.h" #include "CppUTestExt/GMock.h" static bool g_GTestEqual_has_been_called = false; TEST(GTestSimpleTest, GTestEqual) { EXPECT_EQ(1, 1); g_GTestEqual_has_been_called = true; } TEST(GTestSimpleTest, GTestAssertEq) { ASSERT_EQ(1, 1); } TEST(GTestSimpleTest, GTestExpectTrue) { EXPECT_TRUE(true); } TEST(GTestSimpleTest, GTestAssertTrue) { ASSERT_TRUE(true); } TEST(GTestSimpleTest, GTestExpectFalse) { EXPECT_FALSE(false); } TEST(GTestSimpleTest, GTestExpectStreq) { EXPECT_STREQ("hello world", "hello world"); } /* Death tests are IMHO not a good idea at all. But for compatibility reason, we'll support it */ static void crashMe () { fprintf(stderr, "Crash me!"); *((int*) 0) = 10; } TEST(GTestSimpleTest, GTestDeathTest) { #if defined(GTEST_VERSION_GTEST_1_7) CppuTestGTestIgnoreLeaksInTest(); #endif ASSERT_DEATH(crashMe(), "Crash me!"); } #undef TEST #include "CppUTest/TestHarness.h" #include "CppUTest/TestOutput.h" #include "CppUTest/TestTestingFixture.h" TEST_GROUP(gtest) { }; TEST(gtest, SimpleGoogleTestExists) { TestRegistry* registry = TestRegistry::getCurrentRegistry(); CHECK(registry->findTestWithName("GTestEqual")); } TEST(gtest, SimpleGoogleTestGroupExists) { TestRegistry* registry = TestRegistry::getCurrentRegistry(); CHECK(registry->findTestWithGroup("GTestSimpleTest")); } TEST(gtest, SimpleGoogleTestGetCalled) { StringBufferTestOutput output; TestResult result(output); TestPlugin plugin("dummy"); TestRegistry* registry = TestRegistry::getCurrentRegistry(); UtestShell * shell = registry->findTestWithName("GTestEqual"); g_GTestEqual_has_been_called = false; shell->runOneTest(&plugin, result); CHECK(g_GTestEqual_has_been_called); } static bool afterCheck; static void failMethodEXPECT_EQ_() { EXPECT_EQ(1, 2); afterCheck = true; } static void failMethodASSERT_EQ_() { ASSERT_EQ(1, 2); afterCheck = true; } static void failMethodEXPECT_TRUE_() { EXPECT_TRUE(false); afterCheck = true; } static void failMethodASSERT_TRUE_() { ASSERT_TRUE(false); afterCheck = true; } static void failMethodEXPECT_FALSE_() { EXPECT_FALSE(true); afterCheck = true; } static void failMethodEXPECT_STREQ_() { EXPECT_STREQ("hello", "world"); afterCheck = true; } TEST_GROUP(gtestMacros) { TestTestingFixture* fixture; void setup() CPPUTEST_OVERRIDE { fixture = new TestTestingFixture(); afterCheck = false; } void teardown() CPPUTEST_OVERRIDE { delete fixture; } void testFailureWith(void(*method)()) { fixture->setTestFunction(method); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); CHECK(!afterCheck); } }; TEST(gtestMacros, EXPECT_EQFails) { testFailureWith(failMethodEXPECT_EQ_); } TEST(gtestMacros, EXPECT_TRUEFails) { testFailureWith(failMethodEXPECT_TRUE_); } TEST(gtestMacros, EXPECT_FALSEFails) { testFailureWith(failMethodEXPECT_FALSE_); } TEST(gtestMacros, EXPECT_STREQFails) { testFailureWith(failMethodEXPECT_STREQ_); } TEST(gtestMacros, ASSERT_EQFails) { testFailureWith(failMethodASSERT_EQ_); } TEST(gtestMacros, ASSERT_TRUEFails) { testFailureWith(failMethodASSERT_TRUE_); } #endif
null
47
cpp
cpputest
MockNamedValueTest.cpp
tests/CppUTestExt/MockNamedValueTest.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" TEST_GROUP(ComparatorsAndCopiersRepository) { }; class MyComparator : public MockNamedValueComparator { public: MyComparator() {} virtual ~MyComparator() CPPUTEST_DESTRUCTOR_OVERRIDE {} virtual bool isEqual(const void*, const void*) CPPUTEST_OVERRIDE { return false; } virtual SimpleString valueToString(const void*) CPPUTEST_OVERRIDE { return ""; } }; class MyCopier : public MockNamedValueCopier { public: MyCopier() {} virtual ~MyCopier() CPPUTEST_DESTRUCTOR_OVERRIDE {} virtual void copy(void*, const void*) CPPUTEST_OVERRIDE {} }; TEST(ComparatorsAndCopiersRepository, InstallCopierAndRetrieveIt) { MyCopier copier; MockNamedValueComparatorsAndCopiersRepository repository; repository.installCopier("MyType", copier); POINTERS_EQUAL(&copier, repository.getCopierForType("MyType")); repository.clear(); } TEST(ComparatorsAndCopiersRepository, ComparatorAndCopierByTheSameNameShouldBothBeFound) { MyComparator comparator; MyCopier copier; MockNamedValueComparatorsAndCopiersRepository repository; repository.installCopier("MyType", copier); repository.installComparator("MyType", comparator); POINTERS_EQUAL(&comparator, repository.getComparatorForType("MyType")); POINTERS_EQUAL(&copier, repository.getCopierForType("MyType")); repository.clear(); } TEST(ComparatorsAndCopiersRepository, InstallComparatorsAndCopiersFromRepository) { MyComparator comparator; MyCopier copier; MockNamedValueComparatorsAndCopiersRepository source; MockNamedValueComparatorsAndCopiersRepository target; source.installCopier("MyType", copier); source.installComparator("MyType", comparator); target.installComparatorsAndCopiers(source); POINTERS_EQUAL(&comparator, target.getComparatorForType("MyType")); POINTERS_EQUAL(&copier, target.getCopierForType("MyType")); source.clear(); target.clear(); } TEST_GROUP(MockNamedValue) { MockNamedValue * value; void setup() CPPUTEST_OVERRIDE { value = new MockNamedValue("param"); } void teardown() CPPUTEST_OVERRIDE { delete value; } }; TEST(MockNamedValue, DefaultToleranceUsedWhenNoToleranceGiven) { value->setValue(0.2); DOUBLES_EQUAL(MockNamedValue::defaultDoubleTolerance, value->getDoubleTolerance(), 0.0); } TEST(MockNamedValue, GivenToleranceUsed) { value->setValue(0.2, 3.2); STRCMP_EQUAL("double", value->getType().asCharString()); DOUBLES_EQUAL(0.2, value->getDoubleValue(), 0.0); DOUBLES_EQUAL(3.2, value->getDoubleTolerance(), 0.0); } TEST(MockNamedValue, DoublesEqualIfWithinTolerance) { value->setValue(5.0, 0.4); MockNamedValue other("param2"); other.setValue(5.3); CHECK_TRUE(value->equals(other)); } TEST(MockNamedValue, DoublesNotEqualIfOutsideTolerance) { value->setValue(5.0, 0.4); MockNamedValue other("param2"); other.setValue(5.5); CHECK_FALSE(value->equals(other)); }
null
48
cpp
cpputest
MemoryReporterPluginTest.cpp
tests/CppUTestExt/MemoryReporterPluginTest.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 TestMemoryAllocator* previousNewAllocator; class TemporaryDefaultNewAllocator { TestMemoryAllocator* newAllocator; public: TemporaryDefaultNewAllocator(TestMemoryAllocator* oldAllocator) { newAllocator = getCurrentNewAllocator(); setCurrentNewAllocator(oldAllocator); } ~TemporaryDefaultNewAllocator() { setCurrentNewAllocator(newAllocator); } }; class MockMemoryReportFormatter : public MemoryReportFormatter { public: virtual void report_testgroup_start(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_testgroup_start").withParameter("result", result).withParameter("test", &test); } virtual void report_testgroup_end(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_testgroup_end").withParameter("result", result).withParameter("test", &test); } virtual void report_test_start(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_test_start").withParameter("result", result).withParameter("test", &test); } virtual void report_test_end(TestResult* result, UtestShell& test) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_test_end").withParameter("result", result).withParameter("test", &test); } virtual void report_alloc_memory(TestResult* result, TestMemoryAllocator* allocator, size_t, char* , const char* , size_t ) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", allocator); } virtual void report_free_memory(TestResult* result, TestMemoryAllocator* allocator, char* , const char* , size_t ) CPPUTEST_OVERRIDE { TemporaryDefaultNewAllocator tempAlloc(previousNewAllocator); mock("formatter").actualCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", allocator); } }; static MockMemoryReportFormatter formatterForPluginTest; class MemoryReporterPluginUnderTest : public MemoryReporterPlugin { public: MemoryReportFormatter* createMemoryFormatter(const SimpleString& type) CPPUTEST_OVERRIDE { mock("reporter").actualCall("createMemoryFormatter").onObject(this).withParameter("type", type.asCharString()); return new MockMemoryReportFormatter; } }; class TestMemoryAllocatorComparator : public MockNamedValueComparator { public: bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { return ((const TestMemoryAllocator*)object1)->name() == ((const TestMemoryAllocator*)object2)->name(); } SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { return ((const TestMemoryAllocator*)object)->name(); } }; TEST_GROUP(MemoryReporterPlugin) { MemoryReporterPluginUnderTest* reporter; StringBufferTestOutput output; TestMemoryAllocatorComparator memLeakAllocatorComparator; TestResult* result; UtestShell* test; void setup() CPPUTEST_OVERRIDE { previousNewAllocator = getCurrentNewAllocator(); result = new TestResult(output); test = new UtestShell("groupname", "testname", "filename", 1); reporter = new MemoryReporterPluginUnderTest; mock("formatter").installComparator("TestMemoryAllocator", memLeakAllocatorComparator); mock("reporter").disable(); const char *cmd_line[] = {"-pmemoryreport=normal"}; reporter->parseArguments(1, cmd_line, 0); mock("reporter").enable(); } void teardown() CPPUTEST_OVERRIDE { setCurrentNewAllocator(previousNewAllocator); mock().clear(); 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("TestMemoryAllocator", "allocator", reporter->getNewAllocator()); mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getNewAllocator()); mock("formatter").ignoreOtherCalls(); reporter->preTestAction(*test, *result); char *memory = getCurrentNewAllocator()->allocMemoryLeakNode(100); getCurrentNewAllocator()->free_memory(memory, 100, "unknown", 1); } TEST(MemoryReporterPlugin, whenUsingOnlyMallocAllocatorNoOtherOfTheAllocatorsAreUsed) { mock("formatter").expectOneCall("report_test_start").withParameter("result", result).withParameter("test", test); mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getMallocAllocator()); mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getMallocAllocator()); mock("formatter").ignoreOtherCalls(); reporter->preTestAction(*test, *result); char *memory = getCurrentMallocAllocator()->allocMemoryLeakNode(100); getCurrentMallocAllocator()->free_memory(memory, 100, "unknown", 1); } TEST(MemoryReporterPlugin, newArrayAllocationsAreReportedTest) { mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getNewArrayAllocator()); mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getNewArrayAllocator()); mock("formatter").ignoreOtherCalls(); reporter->preTestAction(*test, *result); char *memory = getCurrentNewArrayAllocator()->allocMemoryLeakNode(100); getCurrentNewArrayAllocator()->free_memory(memory, 100, "unknown", 1); } TEST(MemoryReporterPlugin, mallocAllocationsAreReportedTest) { mock("formatter").expectOneCall("report_alloc_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getMallocAllocator()); mock("formatter").expectOneCall("report_free_memory").withParameter("result", result).withParameterOfType("TestMemoryAllocator", "allocator", reporter->getMallocAllocator()); mock("formatter").ignoreOtherCalls(); reporter->preTestAction(*test, *result); char *memory = getCurrentMallocAllocator()->allocMemoryLeakNode(100); getCurrentMallocAllocator()->free_memory(memory, 100, "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 UtestShell { public: UtestForMemoryReportingPlugingTest(const char* groupname, UtestShell* test) : UtestShell(groupname, "testname", "filename", 1, test) { } }; TEST(MemoryReporterPlugin, endOfaTestGroupWillReportSo) { UtestForMemoryReportingPlugingTest fourthTest("differentGroupName", NULLPTR); 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(); TestMemoryAllocator* allocator = getCurrentMallocAllocator(); reporter->preTestAction(*test, *result); CHECK(allocator != getCurrentMallocAllocator()); } TEST(MemoryReporterPlugin, postActionRestoresAllocators) { mock("formatter").ignoreOtherCalls(); TestMemoryAllocator* allocator = getCurrentMallocAllocator(); reporter->preTestAction(*test, *result); reporter->postTestAction(*test, *result); CHECK(allocator == getCurrentMallocAllocator()); } TEST(MemoryReporterPlugin, shouldCreateNormalMemoryReportFormatterWithoutMock) { MemoryReporterPlugin realReporter; const char *cmd_line[] = {"-pmemoryreport=normal"}; CHECK(realReporter.parseArguments(1, cmd_line, 0)); } TEST(MemoryReporterPlugin, shouldCreateCodeMemoryReportFormatterWithoutMock) { MemoryReporterPlugin realReporter; const char *cmd_line[] = {"-pmemoryreport=code"}; CHECK(realReporter.parseArguments(1, cmd_line, 0)); } TEST(MemoryReporterPlugin, shouldntCrashCreateInvalidMemoryReportFormatterWithoutMock) { MemoryReporterPlugin realReporter; const char *cmd_line[] = {"-pmemoryreport=foo"}; CHECK(realReporter.parseArguments(1, cmd_line, 0)); realReporter.preTestAction(*test, *result); realReporter.postTestAction(*test, *result); }
null
49
cpp
cpputest
MockCheatSheetTest.cpp
tests/CppUTestExt/MockCheatSheetTest.cpp
null
/* Additional include from CppUTestExt */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" /* Stubbed out product code using linker, function pointer, or overriding */ static 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(); } static 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 */ static int productionCodeFooCalls() { int return_value; return_value = foo("value_string", 10); (void)return_value; return_value = foo("value_string", 10); return return_value; } static void productionCodeBarCalls() { bar(1.5, "more"); bar(1.5, "more"); } /* Actual test */ TEST_GROUP(MockCheatSheet) { void teardown() CPPUTEST_OVERRIDE { /* Check expectations. Alternatively use MockSupportPlugin */ mock().checkExpectations(); mock().clear(); } }; 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
50
cpp
cpputest
MockExpectedCallTest.cpp
tests/CppUTestExt/MockExpectedCallTest.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" #include "CppUTestExt/MockFailure.h" #include "MockFailureReporterForTest.h" class TypeForTestingExpectedFunctionCall { public: TypeForTestingExpectedFunctionCall(int val) { value = new int(val); } virtual ~TypeForTestingExpectedFunctionCall() { delete value; } int *value; }; class TypeForTestingExpectedFunctionCallComparator : public MockNamedValueComparator { public: virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { const TypeForTestingExpectedFunctionCall* obj1 = (const TypeForTestingExpectedFunctionCall*) object1; const TypeForTestingExpectedFunctionCall* obj2 = (const TypeForTestingExpectedFunctionCall*) object2; return *(obj1->value) == *(obj2->value); } virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { const TypeForTestingExpectedFunctionCall* obj = (const TypeForTestingExpectedFunctionCall*) object; return StringFrom(*(obj->value)); } }; class TypeForTestingExpectedFunctionCallCopier : public MockNamedValueCopier { public: virtual void copy(void* dst_, const void* src_) CPPUTEST_OVERRIDE { TypeForTestingExpectedFunctionCall* dst = (TypeForTestingExpectedFunctionCall*) dst_; const TypeForTestingExpectedFunctionCall* src = (const TypeForTestingExpectedFunctionCall*) src_; *(dst->value) = *(src->value); } }; TEST_GROUP(MockNamedValueHandlerRepository) { void teardown() CPPUTEST_OVERRIDE { CHECK_NO_MOCK_FAILURE(); MockFailureReporterForTest::clearReporter(); } }; TEST(MockNamedValueHandlerRepository, getComparatorForNonExistingName) { MockNamedValueComparatorsAndCopiersRepository repository; POINTERS_EQUAL(NULLPTR, repository.getComparatorForType("typeName")); } TEST(MockNamedValueHandlerRepository, installComparator) { TypeForTestingExpectedFunctionCallComparator comparator; MockNamedValueComparatorsAndCopiersRepository repository; repository.installComparator("typeName", comparator); POINTERS_EQUAL(&comparator, repository.getComparatorForType("typeName")); } TEST(MockNamedValueHandlerRepository, installMultipleComparators) { TypeForTestingExpectedFunctionCallComparator comparator1, comparator2, comparator3; MockNamedValueComparatorsAndCopiersRepository 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(MockNamedValueHandlerRepository, getCopierForNonExistingName) { MockNamedValueComparatorsAndCopiersRepository repository; POINTERS_EQUAL(NULLPTR, repository.getCopierForType("typeName")); } TEST(MockNamedValueHandlerRepository, installCopier) { TypeForTestingExpectedFunctionCallCopier copier; MockNamedValueComparatorsAndCopiersRepository repository; repository.installCopier("typeName", copier); POINTERS_EQUAL(&copier, repository.getCopierForType("typeName")); } TEST(MockNamedValueHandlerRepository, installMultipleCopiers) { TypeForTestingExpectedFunctionCallCopier copier1, copier2, copier3; MockNamedValueComparatorsAndCopiersRepository repository; repository.installCopier("type1", copier1); repository.installCopier("type2", copier2); repository.installCopier("type3", copier3); POINTERS_EQUAL(&copier3, repository.getCopierForType("type3")); POINTERS_EQUAL(&copier2, repository.getCopierForType("type2")); POINTERS_EQUAL(&copier1, repository.getCopierForType("type1")); } TEST(MockNamedValueHandlerRepository, installMultipleHandlers) { TypeForTestingExpectedFunctionCallCopier copier1, copier2, copier3; TypeForTestingExpectedFunctionCallComparator comparator1, comparator2, comparator3; MockNamedValueComparatorsAndCopiersRepository repository; repository.installCopier("type1", copier1); repository.installComparator("type1", comparator1); repository.installCopier("type2", copier2); repository.installCopier("type3", copier3); 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")); POINTERS_EQUAL(&copier3, repository.getCopierForType("type3")); POINTERS_EQUAL(&copier2, repository.getCopierForType("type2")); POINTERS_EQUAL(&copier1, repository.getCopierForType("type1")); } TEST_GROUP(MockExpectedCall) { MockCheckedExpectedCall* call; MockNamedValueComparatorsAndCopiersRepository* originalComparatorRepository; void setup() CPPUTEST_OVERRIDE { originalComparatorRepository = MockNamedValue::getDefaultComparatorsAndCopiersRepository(); call = new MockCheckedExpectedCall(1); call->withName("funcName"); } void teardown() CPPUTEST_OVERRIDE { MockNamedValue::setDefaultComparatorsAndCopiersRepository(originalComparatorRepository); delete call; CHECK_NO_MOCK_FAILURE(); MockFailureReporterForTest::clearReporter(); } }; TEST(MockExpectedCall, callWithoutParameterSetOrNotFound) { STRCMP_EQUAL("", call->getInputParameterType("nonexisting").asCharString()); LONGS_EQUAL(0, call->getInputParameter("nonexisting").getIntValue()); CHECK(!call->hasInputParameterWithName("nonexisting")); } TEST(MockExpectedCall, callWithUnsignedIntegerParameter) { const SimpleString paramName = "paramName"; unsigned int value = 356; call->withParameter(paramName, value); STRCMP_EQUAL("unsigned int", call->getInputParameterType(paramName).asCharString()); LONGS_EQUAL(value, call->getInputParameter(paramName).getUnsignedIntValue()); CHECK(call->hasInputParameterWithName(paramName)); STRCMP_CONTAINS("funcName -> unsigned int paramName: <356 (0x164)>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithIntegerParameter) { const SimpleString paramName = "paramName"; int value = 2; call->withParameter(paramName, value); STRCMP_EQUAL("int", call->getInputParameterType(paramName).asCharString()); LONGS_EQUAL(value, call->getInputParameter(paramName).getIntValue()); CHECK(call->hasInputParameterWithName(paramName)); STRCMP_CONTAINS("funcName -> int paramName: <2 (0x2)>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithBooleanParameter) { const SimpleString paramName = "paramName"; bool value = true; call->withParameter(paramName, value); STRCMP_EQUAL("bool", call->getInputParameterType(paramName).asCharString()); CHECK_EQUAL(value, call->getInputParameter(paramName).getBoolValue()); CHECK(call->hasInputParameterWithName(paramName)); STRCMP_CONTAINS("funcName -> bool paramName: <true>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithUnsignedLongIntegerParameter) { const SimpleString paramName = "paramName"; unsigned long value = 888; call->withParameter(paramName, value); STRCMP_EQUAL("unsigned long int", call->getInputParameterType(paramName).asCharString()); LONGS_EQUAL(value, call->getInputParameter(paramName).getUnsignedLongIntValue()); CHECK(call->hasInputParameterWithName(paramName)); STRCMP_CONTAINS("funcName -> unsigned long int paramName: <888 (0x378)>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithLongIntegerParameter) { const SimpleString paramName = "paramName"; long value = 777; call->withParameter(paramName, value); STRCMP_EQUAL("long int", call->getInputParameterType(paramName).asCharString()); LONGS_EQUAL(value, call->getInputParameter(paramName).getLongIntValue()); CHECK(call->hasInputParameterWithName(paramName)); STRCMP_CONTAINS("funcName -> long int paramName: <777 (0x309)>", call->callToString().asCharString()); } #if CPPUTEST_USE_LONG_LONG TEST(MockExpectedCall, callWithUnsignedLongLongIntegerParameter) { const SimpleString paramName = "paramName"; unsigned long long value = 888; call->withParameter(paramName, value); STRCMP_EQUAL("unsigned long long int", call->getInputParameterType(paramName).asCharString()); UNSIGNED_LONGLONGS_EQUAL(value, call->getInputParameter(paramName).getUnsignedLongLongIntValue()); CHECK(call->hasInputParameterWithName(paramName)); STRCMP_CONTAINS("funcName -> unsigned long long int paramName: <888 (0x378)>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithLongLongIntegerParameter) { const SimpleString paramName = "paramName"; long long value = 777; call->withParameter(paramName, value); STRCMP_EQUAL("long long int", call->getInputParameterType(paramName).asCharString()); LONGLONGS_EQUAL(value, call->getInputParameter(paramName).getLongLongIntValue()); CHECK(call->hasInputParameterWithName(paramName)); STRCMP_CONTAINS("funcName -> long long int paramName: <777 (0x309)>", call->callToString().asCharString()); } #endif TEST(MockExpectedCall, callWithDoubleParameter) { const SimpleString paramName = "paramName"; double value = 1.2; call->withParameter(paramName, value); STRCMP_EQUAL("double", call->getInputParameterType(paramName).asCharString()); DOUBLES_EQUAL(value, call->getInputParameter(paramName).getDoubleValue(), 0.0); STRCMP_CONTAINS("funcName -> double paramName: <1.2>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithDoubleParameterAndTolerance) { const SimpleString paramName = "paramName"; double value = 1.2; double tolerance = 0.2; call->withParameter(paramName, value, tolerance); STRCMP_EQUAL("double", call->getInputParameterType(paramName).asCharString()); DOUBLES_EQUAL(value, call->getInputParameter(paramName).getDoubleValue(), 0.0); DOUBLES_EQUAL(tolerance, call->getInputParameter(paramName).getDoubleTolerance(), 0.0); STRCMP_CONTAINS("funcName -> double paramName: <1.2>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithStringParameter) { const SimpleString paramName = "paramName"; const char* value = "hello world"; call->withParameter(paramName, value); STRCMP_EQUAL("const char*", call->getInputParameterType(paramName).asCharString()); STRCMP_EQUAL(value, call->getInputParameter(paramName).getStringValue()); STRCMP_CONTAINS("funcName -> const char* paramName: <hello world>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithPointerParameter) { const SimpleString paramName = "paramName"; void* value = (void*) 0x123; call->withParameter(paramName, value); STRCMP_EQUAL("void*", call->getInputParameterType(paramName).asCharString()); POINTERS_EQUAL(value, call->getInputParameter(paramName).getPointerValue()); STRCMP_CONTAINS("funcName -> void* paramName: <0x123>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithConstPointerParameter) { const SimpleString paramName = "paramName"; const void* value = (const void*) 0x345; call->withParameter(paramName, value); STRCMP_EQUAL("const void*", call->getInputParameterType(paramName).asCharString()); POINTERS_EQUAL(value, call->getInputParameter(paramName).getConstPointerValue()); STRCMP_CONTAINS("funcName -> const void* paramName: <0x345>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithFunctionPointerParameter) { const SimpleString paramName = "paramName"; void (*value)() = (void (*)()) 0xdead; call->withParameter(paramName, value); STRCMP_EQUAL("void (*)()", call->getInputParameterType(paramName).asCharString()); FUNCTIONPOINTERS_EQUAL(value, call->getInputParameter(paramName).getFunctionPointerValue()); STRCMP_CONTAINS("funcName -> void (*)() paramName: <0xdead>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithMemoryBuffer) { const SimpleString paramName = "paramName"; const unsigned char value[] = { 0x12, 0xFE, 0xA1 }; call->withParameter(paramName, value, sizeof(value)); STRCMP_EQUAL("const unsigned char*", call->getInputParameterType(paramName).asCharString()); POINTERS_EQUAL(value, call->getInputParameter(paramName).getMemoryBuffer()); LONGS_EQUAL(sizeof(value), call->getInputParameter(paramName).getSize()); STRCMP_CONTAINS("funcName -> const unsigned char* paramName: <Size = 3 | HexContents = 12 FE A1>", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithObjectParameter) { const SimpleString paramName = "paramName"; void* value = (void*) 0x123; call->withParameterOfType("ClassName", paramName, value); POINTERS_EQUAL(value, call->getInputParameter(paramName).getConstObjectPointer()); STRCMP_EQUAL("ClassName", call->getInputParameterType(paramName).asCharString()); STRCMP_CONTAINS("funcName -> ClassName paramName: <No comparator found for type: \"ClassName\">", call->callToString().asCharString()); } TEST(MockExpectedCall, callWithObjectParameterUnequalComparison) { TypeForTestingExpectedFunctionCall type(1), unequalType(2); MockNamedValue parameter("name"); parameter.setConstObjectPointer("type", &unequalType); call->withParameterOfType("type", "name", &type); CHECK(!call->hasInputParameter(parameter)); } TEST(MockExpectedCall, callWithObjectParameterEqualComparisonButFailsWithoutRepository) { TypeForTestingExpectedFunctionCall type(1), equalType(1); MockNamedValue parameter("name"); parameter.setConstObjectPointer("type", &equalType); call->withParameterOfType("type", "name", &type); CHECK(!call->hasInputParameter(parameter)); } TEST(MockExpectedCall, callWithObjectParameterEqualComparisonButFailsWithoutComparator) { MockNamedValueComparatorsAndCopiersRepository repository; MockNamedValue::setDefaultComparatorsAndCopiersRepository(&repository); TypeForTestingExpectedFunctionCall type(1), equalType(1); MockNamedValue parameter("name"); parameter.setConstObjectPointer("type", &equalType); call->withParameterOfType("type", "name", &type); CHECK(!call->hasInputParameter(parameter)); } TEST(MockExpectedCall, callWithObjectParameterEqualComparison) { TypeForTestingExpectedFunctionCallComparator comparator; MockNamedValueComparatorsAndCopiersRepository repository; MockNamedValue::setDefaultComparatorsAndCopiersRepository(&repository); repository.installComparator("type", comparator); TypeForTestingExpectedFunctionCall type(1), equalType(1); MockNamedValue parameter("name"); parameter.setConstObjectPointer("type", &equalType); call->withParameterOfType("type", "name", &type); CHECK(call->hasInputParameter(parameter)); } TEST(MockExpectedCall, getParameterValueOfObjectType) { TypeForTestingExpectedFunctionCallComparator comparator; MockNamedValueComparatorsAndCopiersRepository repository; MockNamedValue::setDefaultComparatorsAndCopiersRepository(&repository); repository.installComparator("type", comparator); TypeForTestingExpectedFunctionCall type(1); call->withParameterOfType("type", "name", &type); POINTERS_EQUAL(&type, call->getInputParameter("name").getConstObjectPointer()); STRCMP_EQUAL("1", call->getInputParameterValueString("name").asCharString()); } TEST(MockExpectedCall, getParameterValueOfObjectTypeWithoutRepository) { TypeForTestingExpectedFunctionCall type(1); call->withParameterOfType("type", "name", &type); STRCMP_EQUAL("No comparator found for type: \"type\"", call->getInputParameterValueString("name").asCharString()); } TEST(MockExpectedCall, getParameterValueOfObjectTypeWithoutComparator) { TypeForTestingExpectedFunctionCall type(1); MockNamedValueComparatorsAndCopiersRepository repository; MockNamedValue::setDefaultComparatorsAndCopiersRepository(&repository); call->withParameterOfType("type", "name", &type); STRCMP_EQUAL("No comparator found for type: \"type\"", call->getInputParameterValueString("name").asCharString()); } TEST(MockExpectedCall, callWithTwoUnsignedIntegerParameter) { unsigned int expected_value = 1; unsigned int another_expected_value = 2; call->withParameter("unsigned-integer1", expected_value); call->withParameter("unsigned-integer2", another_expected_value); STRCMP_EQUAL("unsigned int", call->getInputParameterType("unsigned-integer1").asCharString()); STRCMP_EQUAL("unsigned int", call->getInputParameterType("unsigned-integer2").asCharString()); LONGS_EQUAL(expected_value, call->getInputParameter("unsigned-integer1").getUnsignedIntValue()); LONGS_EQUAL(another_expected_value, call->getInputParameter("unsigned-integer2").getUnsignedIntValue()); } TEST(MockExpectedCall, callWithTwoIntegerParameter) { int expected_value = 1; int another_expected_value = -1; call->withParameter("integer1", expected_value); call->withParameter("integer2", another_expected_value); STRCMP_EQUAL("int", call->getInputParameterType("integer1").asCharString()); STRCMP_EQUAL("int", call->getInputParameterType("integer2").asCharString()); LONGS_EQUAL(expected_value, call->getInputParameter("integer1").getIntValue()); LONGS_EQUAL(another_expected_value, call->getInputParameter("integer2").getIntValue()); } TEST(MockExpectedCall, callWithThreeDifferentParameter) { call->withParameter("integer", 1); call->withParameter("string", "hello world"); call->withParameter("double", 0.12); STRCMP_EQUAL("int", call->getInputParameterType("integer").asCharString()); STRCMP_EQUAL("const char*", call->getInputParameterType("string").asCharString()); STRCMP_EQUAL("double", call->getInputParameterType("double").asCharString()); LONGS_EQUAL(1, call->getInputParameter("integer").getIntValue()); STRCMP_EQUAL("hello world", call->getInputParameter("string").getStringValue()); DOUBLES_EQUAL(0.12, call->getInputParameter("double").getDoubleValue(), 0.05); } TEST(MockExpectedCall, singleCallNotMadeIsNotFulfilledButCanMatchActualCalls) { MockCheckedExpectedCall expectedCall(1); expectedCall.withName("name"); CHECK(!expectedCall.isFulfilled()); CHECK(expectedCall.canMatchActualCalls()); } TEST(MockExpectedCall, singleCallMadeIsFulFilledAndCannotMatchActualCalls) { MockCheckedExpectedCall expectedCall(1); expectedCall.callWasMade(1); CHECK(expectedCall.isFulfilled()); CHECK(!expectedCall.canMatchActualCalls()); } TEST(MockExpectedCall, multiCallNotMadeIsNotFulfilledButCanMatchActualCalls) { MockCheckedExpectedCall expectedCall(2); expectedCall.withName("name"); CHECK(!expectedCall.isFulfilled()); CHECK(expectedCall.canMatchActualCalls()); } TEST(MockExpectedCall, multiCallNotMadeExpectedTimesIsNotFulfilledButCanMatchActualCalls) { MockCheckedExpectedCall expectedCall(2); expectedCall.withName("name"); expectedCall.callWasMade(1); CHECK(!expectedCall.isFulfilled()); CHECK(expectedCall.canMatchActualCalls()); } TEST(MockExpectedCall, multiCallsMadeExpectedTimesIsFulfilledAndCannotMatchActualCalls) { MockCheckedExpectedCall expectedCall(3); expectedCall.withName("name"); expectedCall.callWasMade(1); expectedCall.callWasMade(2); expectedCall.callWasMade(3); CHECK(expectedCall.isFulfilled()); CHECK(!expectedCall.canMatchActualCalls()); } TEST(MockExpectedCall, multiCallsMadeMoreThanExpectedTimesIsNotFulfilledAndCannotMatchActualCalls) { MockCheckedExpectedCall expectedCall(3); expectedCall.withName("name"); expectedCall.callWasMade(1); expectedCall.callWasMade(2); expectedCall.callWasMade(3); expectedCall.callWasMade(4); CHECK(!expectedCall.isFulfilled()); CHECK(!expectedCall.canMatchActualCalls()); } TEST(MockExpectedCall, callsWithoutParameterAlwaysMatch) { MockCheckedExpectedCall expectedCall(1); CHECK(expectedCall.isMatchingActualCall()); } TEST(MockExpectedCall, callsWithParameterNotFulfilledDontMatch) { MockCheckedExpectedCall expectedCall(1); expectedCall.withParameter("para", 1); CHECK(!expectedCall.isMatchingActualCall()); } TEST(MockExpectedCall, callsWithParameterFulfilledDoMatch) { MockCheckedExpectedCall expectedCall(1); expectedCall.withParameter("para", 1); expectedCall.inputParameterWasPassed("para"); CHECK(expectedCall.isMatchingActualCall()); } TEST(MockExpectedCall, callsWithSomeParametersNotFulfilledDontMatch) { MockCheckedExpectedCall expectedCall(1); expectedCall.withParameter("para", 1).withParameter("two", 2); expectedCall.inputParameterWasPassed("para"); CHECK(!expectedCall.isMatchingActualCall()); } TEST(MockExpectedCall, toStringForNoParametersSingleCallNotCalled) { MockCheckedExpectedCall expectedCall(1); expectedCall.withName("name"); STRCMP_EQUAL("name -> no parameters (expected 1 call, called 0 times)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForNoParametersMultiCallCalledLessThanExpectedTimes) { MockCheckedExpectedCall expectedCall(2); expectedCall.withName("name"); expectedCall.callWasMade(1); STRCMP_EQUAL("name -> no parameters (expected 2 calls, called 1 time)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForNoParametersMultiCallCalledExpectedTimes) { MockCheckedExpectedCall expectedCall(2); expectedCall.withName("name"); expectedCall.callWasMade(1); expectedCall.callWasMade(2); STRCMP_EQUAL("name -> no parameters (expected 2 calls, called 2 times)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForIgnoredParameters) { MockCheckedExpectedCall expectedCall(1); expectedCall.withName("name"); expectedCall.ignoreOtherParameters(); STRCMP_EQUAL("name -> all parameters ignored (expected 1 call, called 0 times)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForMultipleInputParameters) { int int_value = 10; unsigned int uint_value = 7; MockCheckedExpectedCall expectedCall(1); expectedCall.withName("name"); expectedCall.withParameter("string", "value"); expectedCall.withParameter("integer", int_value); expectedCall.withParameter("unsigned-integer", uint_value); expectedCall.callWasMade(1); STRCMP_EQUAL("name -> const char* string: <value>, int integer: <10 (0xa)>, unsigned int unsigned-integer: <7 (0x7)> " "(expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForMultipleInputAndOutputParameters) { int int_value = 10; unsigned int uint_value = 7; unsigned char buffer_value[3]; MockCheckedExpectedCall expectedCall(1); expectedCall.withName("name"); expectedCall.withParameter("string", "value"); expectedCall.withParameter("integer", int_value); expectedCall.withParameter("unsigned-integer", uint_value); expectedCall.withOutputParameterReturning("buffer", buffer_value, sizeof(buffer_value)); expectedCall.callWasMade(1); STRCMP_EQUAL("name -> const char* string: <value>, int integer: <10 (0xa)>, unsigned int unsigned-integer: <7 (0x7)>, " "const void* buffer: <output> (expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForMultipleOutputParameters) { unsigned char buffer_value[3]; MockCheckedExpectedCall expectedCall(1); expectedCall.withName("name"); expectedCall.withOutputParameterReturning("buffer1", buffer_value, sizeof(buffer_value)); expectedCall.withOutputParameterReturning("buffer2", buffer_value, sizeof(buffer_value)); expectedCall.callWasMade(1); STRCMP_EQUAL("name -> const void* buffer1: <output>, const void* buffer2: <output> (expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForUnmodifiedOutputParameter) { MockCheckedExpectedCall expectedCall(1); expectedCall.withName("name"); expectedCall.withUnmodifiedOutputParameter("buffer1"); expectedCall.callWasMade(1); STRCMP_EQUAL("name -> const void* buffer1: <output> (expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForParameterAndIgnored) { MockCheckedExpectedCall expectedCall(1); expectedCall.withName("name"); expectedCall.withParameter("string", "value"); expectedCall.ignoreOtherParameters(); expectedCall.callWasMade(1); STRCMP_EQUAL("name -> const char* string: <value>, other parameters are ignored (expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForCallOrderSingle) { MockCheckedExpectedCall expectedCall(1); expectedCall.withName("name"); expectedCall.withCallOrder(2); expectedCall.callWasMade(1); STRCMP_EQUAL("name -> expected call order: <2> -> no parameters (expected 1 call, called 1 time)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, toStringForCallOrderMultiple) { MockCheckedExpectedCall expectedCall(5); expectedCall.withName("name"); expectedCall.withCallOrder(5, 9); expectedCall.callWasMade(5); expectedCall.callWasMade(6); expectedCall.callWasMade(7); expectedCall.callWasMade(8); expectedCall.callWasMade(9); STRCMP_EQUAL("name -> expected calls order: <5..9> -> no parameters (expected 5 calls, called 5 times)", expectedCall.callToString().asCharString()); } TEST(MockExpectedCall, callOrderIsFulfilledButWithWrongOrderSingle) { call->withName("name"); call->withCallOrder(2); call->callWasMade(1); CHECK(call->isFulfilled()); CHECK(call->isOutOfOrder()); } TEST(MockExpectedCall, callOrderIsFulfilledButWithWrongOrderMultipleTooEarly) { MockCheckedExpectedCall expectedCall(3); expectedCall.withName("name"); expectedCall.withCallOrder(10, 12); expectedCall.callWasMade(9); expectedCall.callWasMade(10); expectedCall.callWasMade(11); CHECK(expectedCall.isFulfilled()); CHECK(expectedCall.isOutOfOrder()); } TEST(MockExpectedCall, callOrderIsFulfilledButWithWrongOrderMultipleTooLate) { MockCheckedExpectedCall expectedCall(3); expectedCall.withName("name"); expectedCall.withCallOrder(10, 12); expectedCall.callWasMade(11); expectedCall.callWasMade(12); expectedCall.callWasMade(13); CHECK(expectedCall.isFulfilled()); CHECK(expectedCall.isOutOfOrder()); } TEST(MockExpectedCall, callOrderIsFulfilledSingle) { call->withName("name"); call->withCallOrder(1); call->callWasMade(1); CHECK(call->isFulfilled()); CHECK_FALSE(call->isOutOfOrder()); } TEST(MockExpectedCall, callOrderIsFulfilledMultiple) { MockCheckedExpectedCall expectedCall(4); expectedCall.withName("name"); expectedCall.withCallOrder(150, 153); expectedCall.callWasMade(150); expectedCall.callWasMade(151); expectedCall.callWasMade(152); expectedCall.callWasMade(153); CHECK(expectedCall.isFulfilled()); CHECK_FALSE(expectedCall.isOutOfOrder()); } TEST(MockExpectedCall, hasOutputParameter) { const int value = 1; call->withOutputParameterReturning("foo", &value, sizeof(value)); MockNamedValue foo("foo"); foo.setValue(&value); CHECK(call->hasOutputParameter(foo)); } TEST(MockExpectedCall, hasUnmodifiedOutputParameter) { call->withUnmodifiedOutputParameter("foo"); MockNamedValue foo("foo"); foo.setValue((const void *)NULLPTR); foo.setSize(0); CHECK(call->hasOutputParameter(foo)); } TEST(MockExpectedCall, hasNoOutputParameter) { call->withIntParameter("foo", (int)1); MockNamedValue foo("foo"); foo.setValue((int)1); CHECK_FALSE(call->hasOutputParameter(foo)); } TEST(MockExpectedCall, hasOutputParameterOfType) { TypeForTestingExpectedFunctionCall object(6789); call->withOutputParameterOfTypeReturning("TypeForTestingExpectedFunctionCall", "foo", &object); MockNamedValue foo("foo"); foo.setConstObjectPointer("TypeForTestingExpectedFunctionCall", &object); CHECK(call->hasOutputParameter(foo)); } TEST(MockExpectedCall, hasNoOutputParameterOfTypeSameTypeButInput) { TypeForTestingExpectedFunctionCall object(543); call->withParameterOfType("TypeForTestingExpectedFunctionCall", "foo", &object); MockNamedValue foo("foo"); foo.setConstObjectPointer("TypeForTestingExpectedFunctionCall", &object); CHECK_FALSE(call->hasOutputParameter(foo)); } TEST(MockExpectedCall, hasNoOutputParameterOfTypeDifferentType) { TypeForTestingExpectedFunctionCall object(543); call->withOutputParameterOfTypeReturning("TypeForTestingExpectedFunctionCall", "foo", &object); MockNamedValue foo("foo"); foo.setConstObjectPointer("OtherTypeForTestingExpectedFunctionCall", &object); CHECK_FALSE(call->hasOutputParameter(foo)); } TEST_GROUP(MockIgnoredExpectedCall) { MockIgnoredExpectedCall ignored; }; TEST(MockIgnoredExpectedCall, worksAsItShould) { ignored.withName("func"); ignored.withCallOrder(1); ignored.withCallOrder(1, 1); ignored.onObject(NULLPTR); ignored.withBoolParameter("umm", true); ignored.withIntParameter("bla", (int) 1); ignored.withUnsignedIntParameter("foo", (unsigned int) 1); ignored.withLongIntParameter("hey", (long int) 1); ignored.withUnsignedLongIntParameter("bah", (unsigned long int) 1); #if CPPUTEST_USE_LONG_LONG ignored.withLongLongIntParameter("yo", (long long int) 1); ignored.withUnsignedLongLongIntParameter("grr", (unsigned long long int) 1); #endif ignored.withDoubleParameter("hah", (double) 1.1f); ignored.withDoubleParameter("gah", 2.1, 0.3); ignored.withStringParameter("goo", "hello"); ignored.withPointerParameter("pie", (void*) NULLPTR); ignored.withConstPointerParameter("woo", (const void*) NULLPTR); ignored.withFunctionPointerParameter("fop", (void(*)()) NULLPTR); ignored.withMemoryBufferParameter("waa", (const unsigned char*) NULLPTR, 0); ignored.withParameterOfType( "mytype", "top", (const void*) NULLPTR); ignored.withOutputParameterReturning("bar", (void*) NULLPTR, 1); ignored.withOutputParameterOfTypeReturning("mytype", "bar", (const void*) NULLPTR); ignored.withUnmodifiedOutputParameter("unmod"); ignored.ignoreOtherParameters(); ignored.andReturnValue(true); ignored.andReturnValue((double) 1.0f); ignored.andReturnValue((unsigned int) 1); ignored.andReturnValue((int) 1); ignored.andReturnValue((unsigned long int) 1); ignored.andReturnValue((long int) 1); #if CPPUTEST_USE_LONG_LONG ignored.andReturnValue((unsigned long long int) 1); ignored.andReturnValue((long long int) 1); #endif ignored.andReturnValue("boo"); ignored.andReturnValue((void*) NULLPTR); ignored.andReturnValue((const void*) NULLPTR); ignored.andReturnValue((void(*)()) NULLPTR); }
null
51
cpp
cpputest
GMockTest.cpp
tests/CppUTestExt/GMockTest.cpp
null
/* * Copyright (c) 2011, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef CPPUTEST_INCLUDE_GTEST_TESTS #include "CppUTestExt/GMock.h" #include "CppUTest/TestHarness.h" #include "CppUTest/TestOutput.h" #include "CppUTest/TestRegistry.h" #include "CppUTest/TestTestingFixture.h" TEST_GROUP(GMock) { TestTestingFixture *fixture; void setup() CPPUTEST_OVERRIDE { fixture = new TestTestingFixture; } void teardown() CPPUTEST_OVERRIDE { delete fixture; } }; class myMock { public: MOCK_METHOD0(methodName, int()); }; static void failedMockCall() { myMock mock; EXPECT_CALL(mock, methodName()).WillOnce(Return(1)); } TEST(GMock, GMockFailuresWorkAsExpected) { fixture->setTestFunction(failedMockCall); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); } static void failedMockCallAfterOneSuccess() { myMock mock; EXPECT_CALL(mock, methodName()).Times(2).WillRepeatedly(Return(1)); mock.methodName(); } TEST(GMock, GMockFailuresWorkAsExpectedWithTwoExpectedCallButJustOneActual) { fixture->setTestFunction(failedMockCallAfterOneSuccess); fixture->runAllTests(); LONGS_EQUAL(1, fixture->getFailureCount()); } TEST(GMock, GMockNiceMocksWorkFine) { NiceMock<myMock> mock; mock.methodName(); } #endif
null
52
cpp
cpputest
MockCallTest.cpp
tests/CppUTestExt/MockCallTest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestTestingFixture.h" #include "MockFailureReporterForTest.h" TEST_GROUP(MockCallTest) { void teardown() CPPUTEST_OVERRIDE { mock().checkExpectations(); mock().clear(); } }; TEST(MockCallTest, clear) { mock().expectOneCall("func"); mock().clear(); CHECK(! mock().expectedCallsLeft()); } TEST(MockCallTest, checkExpectationsDoesntFail) { mock().checkExpectations(); } TEST(MockCallTest, expectASingleCallThatHappens) { mock().expectOneCall("func"); MockCheckedActualCall& actualCall = (MockCheckedActualCall&) mock().actualCall("func"); actualCall.checkExpectations(); CHECK(! mock().expectedCallsLeft()); } TEST(MockCallTest, expectASingleCallThatDoesntHappen) { mock().expectOneCall("func"); CHECK(mock().expectedCallsLeft()); mock().clear(); } TEST(MockCallTest, expectAMultiCallThatHappensTheExpectedTimes) { mock().expectNCalls(2, "func"); mock().actualCall("func"); MockCheckedActualCall& actualCall = (MockCheckedActualCall&) mock().actualCall("func"); actualCall.checkExpectations(); CHECK(! mock().expectedCallsLeft()); } TEST(MockCallTest, expectAMultiCallThatDoesntHappenTheExpectedTimes) { mock().expectNCalls(2, "func"); MockCheckedActualCall& actualCall = (MockCheckedActualCall&) mock().actualCall("func"); actualCall.checkExpectations(); CHECK(mock().expectedCallsLeft()); mock().clear(); } TEST(MockCallTest, checkExpectationsClearsTheExpectations) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foobar"); MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); mock().expectOneCall("foobar"); mock().checkExpectations(); CHECK(! mock().expectedCallsLeft()); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, expectOneCallInScopeButNotHappen) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("scope::foobar"); MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); mock("scope").expectOneCall("foobar"); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, unexpectedCallHappened) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest emptyExpectations; MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "func", emptyExpectations); mock().actualCall("func"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, unexpectedScopeCallHappened) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest emptyExpectations; MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "scope::func", emptyExpectations); mock("scope").actualCall("func"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, expectOneCallInOneScopeButActualCallInAnotherScope) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest emptyExpectations; MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "class::foo", emptyExpectations); mock("scope").expectOneCall("foo"); mock("class").actualCall("foo"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); mock().clear(); } TEST(MockCallTest, expectOneCallInScopeButActualCallInGlobal) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest emptyExpectations; MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "foo", emptyExpectations); mock("scope").expectOneCall("foo"); mock().actualCall("foo"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); mock().clear(); } TEST(MockCallTest, expectMultipleSingleCallsThatHappen) { mock().expectOneCall("foo"); mock().expectOneCall("foo"); mock().actualCall("foo"); mock().actualCall("foo"); mock().checkExpectations(); } TEST(MockCallTest, expectOneCallHoweverMultipleHappened) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->callWasMade(1); expectations.addFunction("foo")->callWasMade(2); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "foo", expectations); mock().expectOneCall("foo"); mock().expectOneCall("foo"); mock().actualCall("foo"); mock().actualCall("foo"); mock().actualCall("foo"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, expectNoCallThatHappened) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction(0, "lazy"); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "lazy", expectations); mock().expectNoCall("lazy"); mock().actualCall("lazy"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, expectNoCallDoesntInfluenceExpectOneCall) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction(0, "lazy"); expectations.addFunction("influence")->callWasMade(1); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "lazy", expectations); mock().expectNoCall("lazy"); mock().expectOneCall("influence"); mock().actualCall("influence"); mock().actualCall("lazy"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, expectNoCallOnlyFailureOnceWhenMultipleHappened) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction(0, "lazy"); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "lazy", expectations); mock().expectNoCall("lazy"); mock().actualCall("lazy"); mock().actualCall("lazy"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, ignoreOtherCallsExceptForTheUnExpectedOne) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction(0, "lazy"); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "lazy", expectations); mock().expectNoCall("lazy"); mock().ignoreOtherCalls(); mock().actualCall("bar").withParameter("foo", 1); mock().actualCall("bar1").withParameter("foo", 1); mock().actualCall("bar2").withParameter("foo", 1); mock().actualCall("lazy"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, expectNoCallInScopeThatHappened) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction(0, "scope::lazy"); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "scope::lazy", expectations); mock("scope").expectNoCall("lazy"); mock("scope").actualCall("lazy"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, expectNoCallInScopeButActualCallInAnotherScope) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "scope2::lazy", expectations); mock("scope1").expectNoCall("lazy"); mock("scope2").actualCall("lazy"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, expectNoCallInScopeButActualCallInGlobal) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "lazy", expectations); mock("scope1").expectNoCall("lazy"); mock().actualCall("lazy"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, ignoreOtherCallsExceptForTheExpectedOne) { mock().expectOneCall("foo"); mock().ignoreOtherCalls(); mock().actualCall("bar").withParameter("foo", 1); mock().clear(); } TEST(MockCallTest, ignoreOtherCallsDoesntIgnoreMultipleCallsOfTheSameFunction) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->callWasMade(1); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "foo", expectations); mock().expectOneCall("foo"); mock().ignoreOtherCalls(); mock().actualCall("bar"); mock().actualCall("foo"); mock().actualCall("foo"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, ignoreOtherStillFailsIfExpectedOneDidntHappen) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo"); MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); mock().expectOneCall("foo"); mock().ignoreOtherCalls(); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, threeExpectedAndActual) { mock().expectOneCall("function1"); mock().expectOneCall("function2"); mock().expectOneCall("function3"); mock().actualCall("function1"); mock().actualCall("function2"); mock().actualCall("function3"); mock().checkExpectations(); } TEST(MockCallTest, disableEnable) { mock().disable(); mock().expectOneCall("function"); mock().actualCall("differenFunction"); CHECK(! mock().expectedCallsLeft()); mock().enable(); mock().expectOneCall("function"); CHECK(mock().expectedCallsLeft()); mock().actualCall("function"); mock().checkExpectations(); } TEST(MockCallTest, OnObject) { void* objectPtr = (void*) 0x001; mock().expectOneCall("boo").onObject(objectPtr); mock().actualCall("boo").onObject(objectPtr); } TEST(MockCallTest, OnObjectIgnored_MatchingAlreadyWhenObjectPassed) { void* objectPtr = (void*) 0x001; mock().expectOneCall("boo"); mock().actualCall("boo").onObject(objectPtr); } TEST(MockCallTest, OnObjectIgnored_NotMatchingYetWhenObjectPassed) { void* objectPtr = (void*) 0x001; mock().expectOneCall("boo").withBoolParameter("p", true); mock().actualCall("boo").onObject(objectPtr).withBoolParameter("p", true); } TEST(MockCallTest, OnObjectIgnored_InitialMatchDiscarded) { void* objectPtr1 = (void*) 0x001; void* objectPtr2 = (void*) 0x002; mock().expectOneCall("boo"); mock().expectOneCall("boo").withBoolParameter("p", true); mock().actualCall("boo").onObject(objectPtr2).withBoolParameter("p", true); mock().actualCall("boo").onObject(objectPtr1); } TEST(MockCallTest, OnObjectFails) { MockFailureReporterInstaller failureReporterInstaller; void* objectPtr = (void*) 0x001; void* objectPtr2 = (void*) 0x002; MockExpectedCallsListForTest expectations; expectations.addFunction("boo")->onObject(objectPtr); mock().expectOneCall("boo").onObject(objectPtr); mock().actualCall("boo").onObject(objectPtr2); MockUnexpectedObjectFailure expectedFailure(mockFailureTest(), "boo", objectPtr2, expectations); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, OnObjectExpectedButNotCalled) { MockFailureReporterInstaller failureReporterInstaller; void* objectPtr = (void*) 0x001; MockExpectedCallsListForTest expectations; expectations.addFunction("boo")->onObject(objectPtr); expectations.addFunction("boo")->onObject(objectPtr); mock().expectOneCall("boo").onObject(objectPtr); mock().expectOneCall("boo").onObject(objectPtr); mock().actualCall("boo"); mock().actualCall("boo"); MockExpectedObjectDidntHappenFailure expectedFailure(mockFailureTest(), "boo", expectations); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, expectNCalls_Fulfilled) { mock().expectNCalls(2, "boo"); mock().actualCall("boo"); mock().actualCall("boo"); mock().checkExpectations(); } TEST(MockCallTest, expectNCalls_NotFulfilled) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction(2, "boo")->callWasMade(1); MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); mock().expectNCalls(2, "boo"); mock().actualCall("boo"); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCallTest, shouldntFailTwice) { MockFailureReporterInstaller failureReporterInstaller; mock().strictOrder(); mock().expectOneCall("foo"); mock().expectOneCall("boo"); mock().actualCall("boo"); mock().actualCall("bar"); mock().checkExpectations(); CHECK(!MockFailureReporterForTest::getReporter()->mockFailureString.contains("bar")); CHECK(MockFailureReporterForTest::getReporter()->mockFailureString.contains("boo")); } TEST(MockCallTest, shouldReturnDefaultWhenThereIsntAnythingToReturn) { CHECK(mock().returnValue().equals(MockNamedValue(""))); } IGNORE_TEST(MockCallTest, testForPerformanceProfiling) { /* TO fix! */ mock().expectNCalls(2000, "SimpleFunction"); for (int i = 0; i < 2000; i++) { mock().actualCall("SimpleFunction"); } } static void mocksAreCountedAsChecksTestFunction_() { mock().expectOneCall("foo"); mock().expectNCalls(3, "bar"); mock().expectNoCall("lazy"); mock().clear(); } TEST(MockCallTest, mockExpectationShouldIncreaseNumberOfChecks) { TestTestingFixture fixture; fixture.setTestFunction(mocksAreCountedAsChecksTestFunction_); fixture.runAllTests(); LONGS_EQUAL(3, fixture.getCheckCount()); }
null
53
cpp
cpputest
CodeMemoryReporterTest.cpp
tests/CppUTestExt/CodeMemoryReporterTest.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 TESTOUTPUT_EQUAL(a) STRCMP_EQUAL_LOCATION(a, testOutput.getOutput().asCharString(), "", __FILE__, __LINE__) #define TESTOUTPUT_CONTAINS(a) STRCMP_CONTAINS_LOCATION(a, testOutput.getOutput().asCharString(), "", __FILE__, __LINE__) TEST_GROUP(CodeMemoryReportFormatter) { TestMemoryAllocator* cAllocator; TestMemoryAllocator* newAllocator; TestMemoryAllocator* newArrayAllocator; char* memory01; char* memory02; StringBufferTestOutput testOutput; TestResult* testResult; CodeMemoryReportFormatter* formatter; void setup() CPPUTEST_OVERRIDE { cAllocator = defaultMallocAllocator(); newAllocator = defaultNewAllocator(); newArrayAllocator= defaultNewArrayAllocator(); memory01 = (char*) 0x01; memory02 = (char*) 0x02; formatter = new CodeMemoryReportFormatter(cAllocator); testResult = new TestResult(testOutput); } void teardown() CPPUTEST_OVERRIDE { delete testResult; delete formatter; } }; TEST(CodeMemoryReportFormatter, mallocCreatesAnMallocCall) { formatter->report_alloc_memory(testResult, cAllocator, 10, memory01, "file", 9); TESTOUTPUT_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); TESTOUTPUT_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); TESTOUTPUT_CONTAINS("\tfree(file_2_1); /* at foo:6 */\n"); TESTOUTPUT_CONTAINS("\tfree(boo_4_1); /* at bar:8 */\n"); } TEST(CodeMemoryReportFormatter, variableNamesShouldNotContainSlahses) { formatter->report_alloc_memory(testResult, cAllocator, 10, memory01, "dir/file", 2); TESTOUTPUT_CONTAINS("\tvoid* file_2"); } TEST(CodeMemoryReportFormatter, variableNamesShouldNotContainDotButUseUnderscore) { formatter->report_alloc_memory(testResult, cAllocator, 10, memory01, "foo.cpp", 2); TESTOUTPUT_CONTAINS("foo_cpp"); } TEST(CodeMemoryReportFormatter, newArrayAllocatorGeneratesNewArrayCode) { formatter->report_alloc_memory(testResult, newArrayAllocator, 10, memory01, "file", 8); TESTOUTPUT_CONTAINS("char* file_8_1 = new char[10]; /* using new [] */"); } TEST(CodeMemoryReportFormatter, newArrayGeneratesNewCode) { formatter->report_alloc_memory(testResult, newAllocator, 6, memory01, "file", 4); TESTOUTPUT_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); TESTOUTPUT_CONTAINS("delete [] file_8_1; /* using delete at boo:4 */"); } TEST(CodeMemoryReportFormatter, DeleteNullWorksFine) { formatter->report_free_memory(testResult, newAllocator, NULLPTR, "boo", 4); TESTOUTPUT_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); TESTOUTPUT_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, *UtestShell::getCurrent()); testOutput.flush(); formatter->report_alloc_memory(testResult, newAllocator, 10, memory01, "file", 8); CHECK(testOutput.getOutput().contains("char*")); } TEST(CodeMemoryReportFormatter, testStartGeneratesTESTcode) { UtestShell test("groupName", "testName", "fileName", 1); formatter->report_test_start(testResult, test); TESTOUTPUT_EQUAL("*/\nTEST(groupName_memoryReport, testName)\n{ /* at fileName:1 */\n"); } TEST(CodeMemoryReportFormatter, testEndGeneratesTESTcode) { UtestShell test("groupName", "testName", "fileName", 1); formatter->report_test_end(testResult, test); TESTOUTPUT_EQUAL("}/*"); } TEST(CodeMemoryReportFormatter, TestGroupGeneratesTestGroupCode) { UtestShell test("groupName", "testName", "fileName", 1); formatter->report_testgroup_start(testResult, test); TESTOUTPUT_EQUAL("*/TEST_GROUP(groupName_memoryReport)\n{\n};\n/*"); } TEST(CodeMemoryReportFormatter, VariableFromFileLineInfoAlreadyExists) { for(int i = 1; i < 100; i++) { formatter->report_alloc_memory(testResult, newArrayAllocator, 10, memory01, "file", 8); } formatter->report_alloc_memory(testResult, newArrayAllocator, 10, memory01, "file", 8); testOutput.flush(); formatter->report_free_memory(testResult, newArrayAllocator, memory01, "boo", 8); TESTOUTPUT_CONTAINS("delete [] ; /* using delete [] at boo:8 */"); } // TODO: do! /* Dealloc without alloc */ /* Remove the ugly comments by controlling the output! */ /* Write tests for the variable name lengths */
null
54
cpp
cpputest
MockStrictOrderTest.cpp
tests/CppUTestExt/MockStrictOrderTest.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 "MockFailureReporterForTest.h" TEST_GROUP(MockStrictOrderTest) { void teardown() CPPUTEST_OVERRIDE { mock().clear(); } }; TEST(MockStrictOrderTest, OrderObserved) { mock().strictOrder(); mock().expectOneCall("foo1"); mock().expectOneCall("foo2"); mock().actualCall("foo1"); mock().actualCall("foo2"); mock().checkExpectations(); } TEST(MockStrictOrderTest, someOrderObserved) { mock().expectOneCall("foo3").withCallOrder(3); mock().expectOneCall("foo1"); mock().expectOneCall("foo2"); mock().actualCall("foo2"); mock().actualCall("foo1"); mock().actualCall("foo3"); mock().checkExpectations(); } TEST(MockStrictOrderTest, orderViolated) { MockFailureReporterInstaller failureReporterInstaller; mock().strictOrder(); MockExpectedCallsListForTest expectations; expectations.addFunctionOrdered("foo1", 1)->callWasMade(1); expectations.addFunctionOrdered("foo1", 2)->callWasMade(3); expectations.addFunctionOrdered("foo2", 3)->callWasMade(2); MockCallOrderFailure expectedFailure(mockFailureTest(), expectations); mock().expectOneCall("foo1"); mock().expectOneCall("foo1"); mock().expectOneCall("foo2"); mock().actualCall("foo1"); mock().actualCall("foo2"); mock().actualCall("foo1"); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockStrictOrderTest, orderViolatedWorksHierarchically) { MockFailureReporterInstaller failureReporterInstaller; mock().strictOrder(); mock("bla").strictOrder(); MockExpectedCallsListForTest expectations; expectations.addFunctionOrdered("foo::foo1", 1)->callWasMade(2); expectations.addFunctionOrdered("foo::foo2", 2)->callWasMade(1); MockCallOrderFailure expectedFailure(mockFailureTest(), expectations); mock("bla").expectOneCall("foo1"); mock("foo").expectOneCall("foo1"); mock("foo").expectOneCall("foo2"); mock("bla").actualCall("foo1"); mock("foo").actualCall("foo2"); mock("foo").actualCall("foo1"); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockStrictOrderTest, orderViolatedWorksWithExtraUnexpectedCall) { MockFailureReporterInstaller failureReporterInstaller; mock().strictOrder(); mock("bla").strictOrder(); mock().ignoreOtherCalls(); MockExpectedCallsListForTest expectations; expectations.addFunctionOrdered("foo::foo1", 1)->callWasMade(2); expectations.addFunctionOrdered("foo::foo2", 2)->callWasMade(1); MockCallOrderFailure expectedFailure(mockFailureTest(), expectations); mock("bla").expectOneCall("foo1"); mock("foo").expectOneCall("foo1"); mock("foo").expectOneCall("foo2"); mock("bla").actualCall("foo1"); mock("foo").actualCall("foo2"); mock("foo").actualCall("unexpected1"); mock("foo").actualCall("foo1"); mock("foo").actualCall("unexpected2"); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockStrictOrderTest, orderViolatedWithinAScope) { MockFailureReporterInstaller failureReporterInstaller; mock().strictOrder(); MockExpectedCallsListForTest expectations; expectations.addFunctionOrdered("scope::foo1", 1)->callWasMade(2); expectations.addFunctionOrdered("scope::foo2", 2)->callWasMade(1); MockCallOrderFailure expectedFailure(mockFailureTest(), expectations); mock("scope").expectOneCall("foo1"); mock("scope").expectOneCall("foo2"); mock("scope").actualCall("foo2"); mock("scope").actualCall("foo1"); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockStrictOrderTest, orderNotViolatedAcrossScopes) { 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(); } TEST(MockStrictOrderTest, orderViolatedAcrossScopes) { 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(); } TEST(MockStrictOrderTest, orderUsingNCalls) { mock().strictOrder(); mock().expectOneCall("foo1"); mock().expectNCalls(2, "foo2"); mock().expectOneCall("foo1"); mock().expectNCalls(3, "foo2"); mock().actualCall("foo1"); mock().actualCall("foo2"); mock().actualCall("foo2"); mock().actualCall("foo1"); mock().actualCall("foo2"); mock().actualCall("foo2"); mock().actualCall("foo2"); mock().checkExpectations(); }
null
55
cpp
cpputest
MockFakeLongLong.cpp
tests/CppUTestExt/MockFakeLongLong.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/TestTestingFixture.h" #include "CppUTestExt/MockCheckedActualCall.h" #include "CppUTestExt/MockCheckedExpectedCall.h" #include "CppUTestExt/MockExpectedCallsList.h" #include "CppUTestExt/MockFailure.h" #include "MockFailureReporterForTest.h" TEST_GROUP(FakeLongLongs) { TestTestingFixture fixture; }; #ifndef CPPUTEST_USE_LONG_LONG #define CHECK_TEST_FAILS_PROPER_WITH_TEXT(text) fixture.checkTestFailsWithProperTestLocation(text, __FILE__, __LINE__) static void actualCallWithFakeLongLongParameter_() { cpputest_longlong value = {0}; mock().expectOneCall("foo").withParameter("bar", 0); mock().actualCall("foo").withParameter("bar", value); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(FakeLongLongs, ActualCallWithFakeLongLongParameterFAILS) { fixture.runTestWithMethod(actualCallWithFakeLongLongParameter); mock().clear(); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported"); } static void actualCallWithFakeUnsignedLongLongParameter_() { cpputest_ulonglong value = {0}; mock().expectOneCall("foo").withParameter("bar", 0); mock().actualCall("foo").withParameter("bar", value); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(FakeLongLongs, ActualCallWithFakeUnsignedLongLongParameterFAILS) { fixture.runTestWithMethod(actualCallWithFakeUnsignedLongLongParameter_); mock().clear(); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported"); } static void actualCallWithFakeLongLongReturn_() { mock().expectOneCall("foo").andReturnValue(0); mock().actualCall("foo").returnLongLongIntValue(); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(FakeLongLongs, ActualCallWithFakeLongLongReturnFAILS) { fixture.runTestWithMethod(actualCallWithFakeLongLongReturn_); mock().clear(); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported"); } static void actualCallWithFakeUnsignedLongLongReturn_() { mock().expectOneCall("foo").andReturnValue(0); mock().actualCall("foo").returnUnsignedLongLongIntValue(); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(FakeLongLongs, ActualCallWithFakeUnsignedLongLongReturnFAILS) { fixture.runTestWithMethod(actualCallWithFakeUnsignedLongLongReturn_); mock().clear(); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported"); } static void expectOneCallWithFakeLongLongParameter_() { cpputest_longlong value = {0}; mock().expectOneCall("foo").withParameter("bar", value); mock().actualCall("foo").withParameter("bar", 0); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(FakeLongLongs, ExpectedCallWithFakeLongLongParameterFAILS) { fixture.runTestWithMethod(expectOneCallWithFakeLongLongParameter_); mock().clear(); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported"); } static void expectOneCallWithFakeUnsignedLongLongParameter_() { cpputest_ulonglong value = {0}; mock().expectOneCall("foo").withParameter("bar", value); mock().actualCall("foo").withParameter("bar", 0); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(FakeLongLongs, ExpectedCallWithFakeUnsignedLongLongParameterFAILS) { fixture.runTestWithMethod(expectOneCallWithFakeUnsignedLongLongParameter_); mock().clear(); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported"); } static void expectOneCallWithFakeLongLongReturn_() { cpputest_longlong value = {0}; mock().expectOneCall("foo").andReturnValue(value); mock().actualCall("foo").returnIntValue(); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(FakeLongLongs, ExpectedCallWithFakeLongLongReturnFAILS) { fixture.runTestWithMethod(expectOneCallWithFakeLongLongReturn_); mock().clear(); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported"); } static void expectOneCallWithFakeUnsignedLongLongReturn_() { cpputest_ulonglong value = {0}; mock().expectOneCall("foo").andReturnValue(value); mock().actualCall("foo").returnIntValue(); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(FakeLongLongs, ExpectedCallWithFakeUnsignedLongLongReturnFAILS) { fixture.runTestWithMethod(expectOneCallWithFakeUnsignedLongLongReturn_); mock().clear(); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported"); } #endif
null
56
cpp
cpputest
MockHierarchyTest.cpp
tests/CppUTestExt/MockHierarchyTest.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 "MockFailureReporterForTest.h" TEST_GROUP(MockHierarchyTest) { void teardown() CPPUTEST_OVERRIDE { mock().clear(); } }; TEST(MockHierarchyTest, 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(MockHierarchyTest, usingTwoMockSupportsByName) { mock("first").expectOneCall("boo"); LONGS_EQUAL(0, mock("other").expectedCallsLeft()); LONGS_EQUAL(1, mock("first").expectedCallsLeft()); mock("first").clear(); } TEST(MockHierarchyTest, 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(MockHierarchyTest, 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(MockHierarchyTest, ExpectedCallsLeftWorksHierarchically) { mock("first").expectOneCall("foobar"); LONGS_EQUAL(1, mock().expectedCallsLeft()); mock().clear(); } TEST(MockHierarchyTest, checkExpectationsWorksHierarchically) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("first::foobar"); expectations.addFunction("second::helloworld"); MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); mock("first").expectOneCall("foobar"); mock("second").expectOneCall("helloworld"); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockHierarchyTest, ignoreOtherCallsWorksHierarchically) { mock("first"); mock().ignoreOtherCalls(); mock("first").actualCall("boo"); mock().checkExpectations(); } TEST(MockHierarchyTest, ignoreOtherCallsWorksHierarchicallyWhenDynamicallyCreated) { mock().ignoreOtherCalls(); mock("first").actualCall("boo"); mock().checkExpectations(); } TEST(MockHierarchyTest, checkExpectationsWorksHierarchicallyForLastCallNotFinished) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("first::foobar")->withParameter("boo", 1); MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "first::foobar", expectations, expectations); mock("first").expectOneCall("foobar").withParameter("boo", 1); mock("first").actualCall("foobar"); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockHierarchyTest, reporterIsInheritedInHierarchicalMocks) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; mock("differentScope").actualCall("foobar"); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "differentScope::foobar", expectations); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); }
null
57
cpp
cpputest
MockFailureReporterForTest.cpp
tests/CppUTestExt/MockFailureReporterForTest.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 "MockFailureReporterForTest.h" void MockFailureReporterForTest::failTest(const MockFailure& failure) { mockFailureString = failure.getMessage(); } MockFailureReporterForTest* MockFailureReporterForTest::instance_ = NULLPTR; MockFailureReporterForTest* MockFailureReporterForTest::getReporter() { if (instance_ == NULLPTR) instance_ = new MockFailureReporterForTest; return instance_; } void MockFailureReporterForTest::clearReporter() { delete instance_; instance_ = NULLPTR; } MockFailureReporterInstaller::MockFailureReporterInstaller() { mock().setMockFailureStandardReporter(MockFailureReporterForTest::getReporter()); } MockFailureReporterInstaller::~MockFailureReporterInstaller() { mock().setMockFailureStandardReporter(NULLPTR); MockFailureReporterForTest::clearReporter(); } UtestShell* mockFailureTest() { return MockFailureReporterForTest::getReporter()->getTestToFail(); } SimpleString mockFailureString() { return MockFailureReporterForTest::getReporter()->mockFailureString; } void CLEAR_MOCK_FAILURE() { MockFailureReporterForTest::getReporter()->mockFailureString = ""; } void CHECK_EXPECTED_MOCK_FAILURE_LOCATION(const MockFailure& expectedFailure, const char* file, size_t line) { SimpleString expectedFailureString = expectedFailure.getMessage(); SimpleString actualFailureString = mockFailureString(); CLEAR_MOCK_FAILURE(); 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); } } void CHECK_NO_MOCK_FAILURE_LOCATION(const char* file, size_t line) { if (mockFailureString() != "") { SimpleString error = "Unexpected mock failure:\n"; error += mockFailureString(); CLEAR_MOCK_FAILURE(); FAIL_LOCATION(error.asCharString(), file, line); } CLEAR_MOCK_FAILURE(); } MockExpectedCallsListForTest::~MockExpectedCallsListForTest() { deleteAllExpectationsAndClearList(); } MockCheckedExpectedCall* MockExpectedCallsListForTest::addFunction(const SimpleString& name) { MockCheckedExpectedCall* newCall = new MockCheckedExpectedCall; newCall->withName(name); addExpectedCall(newCall); return newCall; } MockCheckedExpectedCall* MockExpectedCallsListForTest::addFunction(unsigned int numCalls, const SimpleString& name) { MockCheckedExpectedCall* newCall = new MockCheckedExpectedCall(numCalls); newCall->withName(name); addExpectedCall(newCall); return newCall; } MockCheckedExpectedCall* MockExpectedCallsListForTest::addFunctionOrdered(const SimpleString& name, unsigned int order) { MockCheckedExpectedCall* newCall = addFunction(name); newCall->withCallOrder(order); return newCall; }
null
58
cpp
cpputest
MockFailureReporterForTest.h
tests/CppUTestExt/MockFailureReporterForTest.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_MockFailureReporterForTest_h #define D_MockFailureReporterForTest_h #include "CppUTestExt/MockSupport.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) CPPUTEST_OVERRIDE; static MockFailureReporterForTest* getReporter(); static void clearReporter(); private: static MockFailureReporterForTest* instance_; }; class MockFailureReporterInstaller { public: MockFailureReporterInstaller(); ~MockFailureReporterInstaller(); }; UtestShell* mockFailureTest(); SimpleString mockFailureString(); void CLEAR_MOCK_FAILURE(); void CHECK_EXPECTED_MOCK_FAILURE_LOCATION(const MockFailure& expectedFailure, const char* file, size_t line); void CHECK_NO_MOCK_FAILURE_LOCATION(const char* file, size_t line); class MockExpectedCallsListForTest : public MockExpectedCallsList { public: ~MockExpectedCallsListForTest() CPPUTEST_DESTRUCTOR_OVERRIDE; MockCheckedExpectedCall* addFunction(const SimpleString& name); MockCheckedExpectedCall* addFunction(unsigned int numCalls, const SimpleString& name); MockCheckedExpectedCall* addFunctionOrdered(const SimpleString& name, unsigned int order); }; #endif
null
59
cpp
cpputest
MockComparatorCopierTest.cpp
tests/CppUTestExt/MockComparatorCopierTest.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 "MockFailureReporterForTest.h" TEST_GROUP(MockComparatorCopierTest) { void teardown() CPPUTEST_OVERRIDE { mock().checkExpectations(); mock().clear(); mock().removeAllComparatorsAndCopiers(); } }; class MyTypeForTesting { public: MyTypeForTesting(long val) { value = new long(val); } virtual ~MyTypeForTesting() { delete value; } long *value; }; class MyTypeForTestingComparator : public MockNamedValueComparator { public: virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { const MyTypeForTesting* obj1 = (const MyTypeForTesting*) object1; const MyTypeForTesting* obj2 = (const MyTypeForTesting*) object2; return *(obj1->value) == *(obj2->value); } virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { const MyTypeForTesting* obj = (const MyTypeForTesting*) object; return StringFrom(*(obj->value)); } }; class MyTypeForTestingCopier : public MockNamedValueCopier { public: virtual void copy(void* dst_, const void* src_) CPPUTEST_OVERRIDE { MyTypeForTesting* dst = (MyTypeForTesting*) dst_; const MyTypeForTesting* src = (const MyTypeForTesting*) src_; *(dst->value) = *(src->value); } }; TEST(MockComparatorCopierTest, customObjectParameterFailsWhenNotHavingAComparisonRepository) { MockFailureReporterInstaller failureReporterInstaller; 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(MockComparatorCopierTest, customObjectParameterFailsWhenNotHavingACopierRepository) { MockFailureReporterInstaller failureReporterInstaller; MyTypeForTesting object(1); mock().expectOneCall("function").withOutputParameterOfTypeReturning("MyTypeForTesting", "parameterName", &object); mock().actualCall("function").withOutputParameterOfType("MyTypeForTesting", "parameterName", &object); MockNoWayToCopyCustomTypeFailure expectedFailure(mockFailureTest(), "MyTypeForTesting"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockComparatorCopierTest, 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(); mock().removeAllComparatorsAndCopiers(); } static bool myTypeIsEqual(const void* object1, const void* object2) { return ((const MyTypeForTesting*)object1)->value == ((const MyTypeForTesting*)object2)->value; } static SimpleString myTypeValueToString(const void* object) { return StringFrom(((const MyTypeForTesting*)object)->value); } TEST(MockComparatorCopierTest, 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(); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, customObjectWithFunctionComparatorThatFailsCoversValueToString) { MockFailureReporterInstaller failureReporterInstaller; MyTypeForTesting object(5); MockFunctionComparator comparator(myTypeIsEqual, myTypeValueToString); mock().installComparator("MyTypeForTesting", comparator); MockExpectedCallsListForTest expectations; expectations.addFunction("function")->withParameterOfType("MyTypeForTesting", "parameterName", &object); MockExpectedCallsDidntHappenFailure failure(UtestShell::getCurrent(), expectations); mock().expectOneCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE_LOCATION(failure, __FILE__, __LINE__); } TEST(MockComparatorCopierTest, customTypeOutputParameterSucceeds) { MyTypeForTesting expectedObject(55); MyTypeForTesting actualObject(99); MyTypeForTestingCopier copier; mock().installCopier("MyTypeForTesting", copier); mock().expectOneCall("function").withOutputParameterOfTypeReturning("MyTypeForTesting", "parameterName", &expectedObject); mock().actualCall("function").withOutputParameterOfType("MyTypeForTesting", "parameterName", &actualObject); mock().checkExpectations(); CHECK_EQUAL(55, *(expectedObject.value)); CHECK_EQUAL(55, *(actualObject.value)); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, noActualCallForCustomTypeOutputParameter) { MockFailureReporterInstaller failureReporterInstaller; MyTypeForTesting expectedObject(1); MyTypeForTestingCopier copier; mock().installCopier("MyTypeForTesting", copier); MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); mock().expectOneCall("foo").withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, unexpectedCustomTypeOutputParameter) { MockFailureReporterInstaller failureReporterInstaller; MyTypeForTesting actualObject(8834); MyTypeForTestingCopier copier; mock().installCopier("MyTypeForTesting", copier); MockExpectedCallsListForTest expectations; expectations.addFunction("foo"); MockNamedValue parameter("parameterName"); parameter.setConstObjectPointer("MyTypeForTesting", &actualObject); MockUnexpectedOutputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo"); mock().actualCall("foo").withOutputParameterOfType("MyTypeForTesting", "parameterName", &actualObject); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, customTypeOutputParameterMissing) { MockFailureReporterInstaller failureReporterInstaller; MyTypeForTesting expectedObject(123464); MyTypeForTestingCopier copier; mock().installCopier("MyTypeForTesting", copier); MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations, expectations); mock().expectOneCall("foo").withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); mock().actualCall("foo"); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, customTypeOutputParameterOfWrongType) { MockFailureReporterInstaller failureReporterInstaller; MyTypeForTesting expectedObject(123464); MyTypeForTesting actualObject(75646); MyTypeForTestingCopier copier; mock().installCopier("MyTypeForTesting", copier); MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); MockNamedValue parameter("output"); parameter.setConstObjectPointer("OtherTypeForTesting", &actualObject); MockUnexpectedOutputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); mock().actualCall("foo").withOutputParameterOfType("OtherTypeForTesting", "output", &actualObject); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, noCopierForCustomTypeOutputParameter) { MockFailureReporterInstaller failureReporterInstaller; MyTypeForTesting expectedObject(123464); MyTypeForTesting actualObject(8834); MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); MockNoWayToCopyCustomTypeFailure expectedFailure(mockFailureTest(), "MyTypeForTesting"); mock().expectOneCall("foo").withOutputParameterOfTypeReturning("MyTypeForTesting", "output", &expectedObject); mock().actualCall("foo").withOutputParameterOfType("MyTypeForTesting", "output", &actualObject); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockComparatorCopierTest, twoCustomTypeOutputParameters) { MyTypeForTesting expectedObject1(545); MyTypeForTesting actualObject1(979); MyTypeForTesting expectedObject2(123); MyTypeForTesting actualObject2(4567); MyTypeForTestingCopier copier; mock().installCopier("MyTypeForTesting", copier); mock().expectOneCall("function").withOutputParameterOfTypeReturning("MyTypeForTesting", "parameterName", &expectedObject1).withParameter("id", 1); mock().expectOneCall("function").withOutputParameterOfTypeReturning("MyTypeForTesting", "parameterName", &expectedObject2).withParameter("id", 2); mock().actualCall("function").withOutputParameterOfType("MyTypeForTesting", "parameterName", &actualObject1).withParameter("id", 1); mock().actualCall("function").withOutputParameterOfType("MyTypeForTesting", "parameterName", &actualObject2).withParameter("id", 2); mock().checkExpectations(); CHECK_EQUAL(545, *(expectedObject1.value)); CHECK_EQUAL(545, *(actualObject1.value)); CHECK_EQUAL(123, *(expectedObject2.value)); CHECK_EQUAL(123, *(actualObject2.value)); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, twoInterleavedCustomTypeOutputParameters) { MyTypeForTesting expectedObject1(9545); MyTypeForTesting actualObject1(79); MyTypeForTesting expectedObject2(132); MyTypeForTesting actualObject2(743); MyTypeForTestingCopier copier; mock().installCopier("MyTypeForTesting", copier); mock().expectOneCall("function").withOutputParameterOfTypeReturning("MyTypeForTesting", "parameterName", &expectedObject1).withParameter("id", 1); mock().expectOneCall("function").withOutputParameterOfTypeReturning("MyTypeForTesting", "parameterName", &expectedObject2).withParameter("id", 2); mock().actualCall("function").withOutputParameterOfType("MyTypeForTesting", "parameterName", &actualObject2).withParameter("id", 2); mock().actualCall("function").withOutputParameterOfType("MyTypeForTesting", "parameterName", &actualObject1).withParameter("id", 1); mock().checkExpectations(); CHECK_EQUAL(9545, *(expectedObject1.value)); CHECK_EQUAL(9545, *(actualObject1.value)); CHECK_EQUAL(132, *(expectedObject2.value)); CHECK_EQUAL(132, *(actualObject2.value)); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, twoDifferentCustomTypeOutputParametersInSameFunctionCallSucceeds) { MyTypeForTesting expectedObject1(11); MyTypeForTesting actualObject1(22); MyTypeForTesting expectedObject2(33); MyTypeForTesting actualObject2(44); MyTypeForTestingCopier copier; mock().installCopier("MyTypeForTesting", copier); mock().expectOneCall("foo") .withOutputParameterOfTypeReturning("MyTypeForTesting", "bar", &expectedObject1) .withOutputParameterOfTypeReturning("MyTypeForTesting", "foobar", &expectedObject2); mock().actualCall("foo") .withOutputParameterOfType("MyTypeForTesting", "bar", &actualObject1) .withOutputParameterOfType("MyTypeForTesting", "foobar", &actualObject2); mock().checkExpectations(); CHECK_EQUAL(11, *(expectedObject1.value)); CHECK_EQUAL(11, *(actualObject1.value)); CHECK_EQUAL(33, *(expectedObject2.value)); CHECK_EQUAL(33, *(actualObject2.value)); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, customTypeOutputAndInputParametersOfSameNameInDifferentFunctionCallsOfSameFunctionSucceeds) { MyTypeForTesting expectedObject1(911); MyTypeForTesting actualObject1(6576878); MyTypeForTesting expectedObject2(123); MyTypeForTesting actualObject2(123); MyTypeForTestingCopier copier; MyTypeForTestingComparator comparator; mock().installCopier("MyTypeForTesting", copier); mock().installComparator("MyTypeForTesting", comparator); mock().expectOneCall("foo").withOutputParameterOfTypeReturning("MyTypeForTesting", "bar", &expectedObject1); mock().expectOneCall("foo").withParameterOfType("MyTypeForTesting", "bar", &expectedObject2); mock().actualCall("foo").withOutputParameterOfType("MyTypeForTesting", "bar", &actualObject1); mock().actualCall("foo").withParameterOfType("MyTypeForTesting", "bar", &actualObject2); mock().checkExpectations(); CHECK_EQUAL(911, *(expectedObject1.value)); CHECK_EQUAL(911, *(actualObject1.value)); CHECK_EQUAL(123, *(expectedObject2.value)); CHECK_EQUAL(123, *(actualObject2.value)); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, twoCustomTypeOutputParametersOfSameNameInDifferentFunctionsSucceeds) { MyTypeForTesting expectedObject1(657); MyTypeForTesting actualObject1(984465); MyTypeForTesting expectedObject2(987); MyTypeForTesting actualObject2(987); MyTypeForTestingCopier copier; MyTypeForTestingComparator comparator; mock().installCopier("MyTypeForTesting", copier); mock().installComparator("MyTypeForTesting", comparator); mock().expectOneCall("foo1").withOutputParameterOfTypeReturning("MyTypeForTesting", "bar", &expectedObject1); mock().expectOneCall("foo2").withParameterOfType("MyTypeForTesting", "bar", &expectedObject2); mock().actualCall("foo1").withOutputParameterOfType("MyTypeForTesting", "bar", &actualObject1); mock().actualCall("foo2").withParameterOfType("MyTypeForTesting", "bar", &actualObject2); mock().checkExpectations(); CHECK_EQUAL(657, *(expectedObject1.value)); CHECK_EQUAL(657, *(actualObject1.value)); CHECK_EQUAL(987, *(expectedObject2.value)); CHECK_EQUAL(987, *(actualObject2.value)); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, customTypeOutputAndInputParameterOfSameTypeInSameFunctionCall) { MyTypeForTesting expectedObject1(45); MyTypeForTesting actualObject1(45); MyTypeForTesting expectedObject2(987765443); MyTypeForTesting actualObject2(0); MyTypeForTestingCopier copier; MyTypeForTestingComparator comparator; mock().installCopier("MyTypeForTesting", copier); mock().installComparator("MyTypeForTesting", comparator); mock().expectOneCall("foo") .withParameterOfType("MyTypeForTesting", "bar", &expectedObject1) .withOutputParameterOfTypeReturning("MyTypeForTesting", "bar", &expectedObject2); mock().actualCall("foo") .withParameterOfType("MyTypeForTesting", "bar", &actualObject1) .withOutputParameterOfType("MyTypeForTesting", "bar", &actualObject2); mock().checkExpectations(); CHECK_EQUAL(45, *(expectedObject1.value)); CHECK_EQUAL(45, *(actualObject1.value)); CHECK_EQUAL(987765443, *(expectedObject2.value)); CHECK_EQUAL(987765443, *(actualObject2.value)); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, customTypeOutputParameterTraced) { MyTypeForTesting actualObject(676789); MyTypeForTestingCopier copier; mock().installCopier("MyTypeForTesting", copier); mock().tracing(true); mock().actualCall("someFunc").withOutputParameterOfType("MyTypeForTesting", "someParameter", &actualObject); mock().checkExpectations(); STRCMP_CONTAINS("Function name:someFunc MyTypeForTesting someParameter:", mock().getTraceOutput()); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, customTypeOutputParameterWithIgnoredParameters) { MyTypeForTesting expectedObject(444537909); MyTypeForTesting actualObject(98765); MyTypeForTestingCopier copier; mock().installCopier("MyTypeForTesting", copier); mock().expectOneCall("foo").withOutputParameterOfTypeReturning("MyTypeForTesting", "bar", &expectedObject).ignoreOtherParameters(); mock().actualCall("foo").withOutputParameterOfType("MyTypeForTesting", "bar", &actualObject).withParameter("other", 1); mock().checkExpectations(); CHECK_EQUAL(444537909, *(expectedObject.value)); CHECK_EQUAL(444537909, *(actualObject.value)); mock().removeAllComparatorsAndCopiers(); } static void myTypeCopy(void* dst_, const void* src_) { MyTypeForTesting* dst = (MyTypeForTesting*) dst_; const MyTypeForTesting* src = (const MyTypeForTesting*) src_; *(dst->value) = *(src->value); } TEST(MockComparatorCopierTest, customObjectWithFunctionCopier) { MyTypeForTesting expectedObject(9874452); MyTypeForTesting actualObject(2034); MockFunctionCopier copier(myTypeCopy); mock().installCopier("MyTypeForTesting", copier); mock().expectOneCall("function").withOutputParameterOfTypeReturning("MyTypeForTesting", "parameterName", &expectedObject); mock().actualCall("function").withOutputParameterOfType("MyTypeForTesting", "parameterName", &actualObject); mock().checkExpectations(); CHECK_EQUAL(9874452, *(expectedObject.value)); CHECK_EQUAL(9874452, *(actualObject.value)); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, removingComparatorsWorksHierachically) { MockFailureReporterInstaller failureReporterInstaller; MyTypeForTesting object(1); MyTypeForTestingComparator comparator; mock("scope").installComparator("MyTypeForTesting", comparator); mock().removeAllComparatorsAndCopiers(); 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(MockComparatorCopierTest, removingCopiersWorksHierachically) { MockFailureReporterInstaller failureReporterInstaller; MyTypeForTesting object(1); MyTypeForTestingCopier copier; mock("scope").installCopier("MyTypeForTesting", copier); mock().removeAllComparatorsAndCopiers(); mock("scope").expectOneCall("foo").withOutputParameterOfTypeReturning("MyTypeForTesting", "bar", &object); mock("scope").actualCall("foo").withOutputParameterOfType("MyTypeForTesting", "bar", &object); MockNoWayToCopyCustomTypeFailure expectedFailure(mockFailureTest(), "MyTypeForTesting"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockComparatorCopierTest, 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(); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, installComparatorsWorksHierarchical) { MyTypeForTesting object(1); MyTypeForTestingComparator comparator; MockNamedValueComparatorsAndCopiersRepository repos; repos.installComparator("MyTypeForTesting", comparator); mock("existing"); mock().installComparatorsAndCopiers(repos); mock("existing").expectOneCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object); mock("existing").actualCall("function").withParameterOfType("MyTypeForTesting", "parameterName", &object); mock().checkExpectations(); mock().removeAllComparatorsAndCopiers(); } TEST(MockComparatorCopierTest, installCopiersWorksHierarchically) { MyTypeForTesting object(1); MyTypeForTestingCopier copier; mock("existing"); mock().installCopier("MyTypeForTesting", copier); mock("existing").expectOneCall("function").withOutputParameterOfTypeReturning("MyTypeForTesting", "parameterName", &object); mock("existing").actualCall("function").withOutputParameterOfType("MyTypeForTesting", "parameterName", &object); mock().checkExpectations(); mock().removeAllComparatorsAndCopiers(); } class StubComparator : public MockNamedValueComparator { public: virtual bool isEqual(const void*, const void*) CPPUTEST_OVERRIDE { return true; } virtual SimpleString valueToString(const void*) CPPUTEST_OVERRIDE { return ""; } }; struct SomeClass { int someDummy_; }; static void functionWithConstParam(const SomeClass param) { mock().actualCall("functionWithConstParam").withParameterOfType("SomeClass", "param", &param); } TEST(MockComparatorCopierTest, shouldSupportConstParameters) { StubComparator comparator; mock().installComparator("SomeClass", comparator); SomeClass param; mock().expectOneCall("functionWithConstParam").withParameterOfType("SomeClass", "param", &param); functionWithConstParam(param); mock().checkExpectations(); }
null
60
cpp
cpputest
MockPluginTest.cpp
tests/CppUTestExt/MockPluginTest.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 "MockFailureReporterForTest.h" #include "CppUTest/TestTestingFixture.h" TEST_GROUP(MockPlugin) { StringBufferTestOutput output; UtestShell *test; TestResult *result; MockSupportPlugin plugin; void setup() CPPUTEST_OVERRIDE { test = new UtestShell("group", "name", "file", 1); result = new TestResult(output); } void teardown() CPPUTEST_OVERRIDE { delete test; delete result; mock().clear(); mock().removeAllComparatorsAndCopiers(); } }; TEST(MockPlugin, checkExpectationsAndClearAtEnd) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foobar"); MockExpectedCallsDidntHappenFailure expectedFailure(test, expectations); mock().expectOneCall("foobar"); plugin.postTestAction(*test, *result); STRCMP_CONTAINS(expectedFailure.getMessage().asCharString(), output.getOutput().asCharString()); LONGS_EQUAL(0, mock().expectedCallsLeft()); CHECK_NO_MOCK_FAILURE(); } TEST(MockPlugin, checkExpectationsWorksAlsoWithHierachicalObjects) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("differentScope::foobar")->onObject((void*) 1); MockExpectedObjectDidntHappenFailure expectedFailure(test, "differentScope::foobar", expectations); mock("differentScope").expectOneCall("foobar").onObject((void*) 1); mock("differentScope").actualCall("foobar"); plugin.postTestAction(*test, *result); STRCMP_CONTAINS(expectedFailure.getMessage().asCharString(), output.getOutput().asCharString()); CHECK_NO_MOCK_FAILURE(); } class DummyComparator : public MockNamedValueComparator { public: bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { return object1 == object2; } SimpleString valueToString(const void*) CPPUTEST_OVERRIDE { return "string"; } }; TEST(MockPlugin, installComparatorRecordsTheComparatorButNotInstallsItYet) { MockFailureReporterInstaller failureReporterInstaller; DummyComparator comparator; plugin.installComparator("myType", comparator); mock().expectOneCall("foo").withParameterOfType("myType", "name", NULLPTR); mock().actualCall("foo").withParameterOfType("myType", "name", NULLPTR); MockNoWayToCompareCustomTypeFailure failure(test, "myType"); CHECK_EXPECTED_MOCK_FAILURE(failure); plugin.clear(); } class DummyCopier : public MockNamedValueCopier { public: void copy(void* dst, const void* src) CPPUTEST_OVERRIDE { *(int*)dst = *(const int*)src; } }; TEST(MockPlugin, installCopierRecordsTheCopierButNotInstallsItYet) { MockFailureReporterInstaller failureReporterInstaller; DummyCopier copier; plugin.installCopier("myType", copier); mock().expectOneCall("foo").withOutputParameterOfTypeReturning("myType", "name", NULLPTR); mock().actualCall("foo").withOutputParameterOfType("myType", "name", NULLPTR); MockNoWayToCopyCustomTypeFailure failure(test, "myType"); CHECK_EXPECTED_MOCK_FAILURE(failure); plugin.clear(); } TEST(MockPlugin, preTestActionWillEnableMultipleComparatorsToTheGlobalMockSupportSpace) { 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(); LONGS_EQUAL(0, result->getFailureCount()); plugin.clear(); } static void failTwiceFunction_() { mock().expectOneCall("foobar"); FAIL("This failed"); } TEST(MockPlugin, shouldNotFailAgainWhenTestAlreadyFailed) { TestTestingFixture fixture; fixture.installPlugin(&plugin); fixture.setTestFunction(failTwiceFunction_); fixture.runAllTests(); fixture.assertPrintContains("1 failures, 1 tests, 1 ran, 2 checks,"); }
null
61
cpp
cpputest
MockActualCallTest.cpp
tests/CppUTestExt/MockActualCallTest.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/MockExpectedCallsList.h" #include "CppUTestExt/MockFailure.h" #include "MockFailureReporterForTest.h" TEST_GROUP(MockCheckedActualCall) { MockExpectedCallsList* emptyList; MockExpectedCallsList* list; MockFailureReporter* reporter; void setup() CPPUTEST_OVERRIDE { emptyList = new MockExpectedCallsList; list = new MockExpectedCallsList; reporter = MockFailureReporterForTest::getReporter(); } void teardown() CPPUTEST_OVERRIDE { CHECK_NO_MOCK_FAILURE(); MockFailureReporterForTest::clearReporter(); delete emptyList; delete list; } }; TEST(MockCheckedActualCall, unExpectedCall) { MockCheckedActualCall actualCall(1, reporter, *emptyList); actualCall.withName("unexpected"); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "unexpected", *list); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCheckedActualCall, unExpectedCallWithAParameter) { MockCheckedActualCall actualCall(1, reporter, *emptyList); actualCall.withName("unexpected").withParameter("bar", 0); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "unexpected", *list); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCheckedActualCall, unExpectedCallWithAnOutputParameter) { MockCheckedActualCall actualCall(1, reporter, *emptyList); actualCall.withName("unexpected").withOutputParameter("bar", NULLPTR); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "unexpected", *list); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCheckedActualCall, unExpectedCallOnObject) { int object; MockCheckedActualCall actualCall(1, reporter, *emptyList); actualCall.withName("unexpected").onObject(&object); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "unexpected", *list); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); CHECK(actualCall.hasFailed()); // Checks that onObject() doesn't "reset" call state } TEST(MockCheckedActualCall, actualCallWithNoReturnValueAndMeaninglessCallOrderForCoverage) { MockCheckedActualCall actualCall(1, reporter, *emptyList); actualCall.withName("noreturn").withCallOrder(0).returnValue(); MockUnexpectedCallHappenedFailure expectedFailure(mockFailureTest(), "noreturn", *list); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCheckedActualCall, unExpectedParameterName) { MockCheckedExpectedCall call1; call1.withName("func"); list->addExpectedCall(&call1); MockCheckedActualCall actualCall(1, reporter, *list); actualCall.withName("func").withParameter("integer", 1); MockNamedValue parameter("integer"); parameter.setValue(1); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "func", parameter, *list); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockCheckedActualCall, multipleSameFunctionsExpectingAndHappenGradually) { MockCheckedExpectedCall* call1 = new MockCheckedExpectedCall(); MockCheckedExpectedCall* call2 = new MockCheckedExpectedCall(); call1->withName("func"); call2->withName("func"); list->addExpectedCall(call1); list->addExpectedCall(call2); LONGS_EQUAL(2, list->amountOfUnfulfilledExpectations()); MockCheckedActualCall actualCall1(1, reporter, *list); actualCall1.withName("func"); actualCall1.checkExpectations(); LONGS_EQUAL(1, list->amountOfUnfulfilledExpectations()); MockCheckedActualCall actualCall2(2, reporter, *list); actualCall2.withName("func"); actualCall2.checkExpectations(); LONGS_EQUAL(0, list->amountOfUnfulfilledExpectations()); list->deleteAllExpectationsAndClearList(); } TEST(MockCheckedActualCall, MockIgnoredActualCallWorksAsItShould) { MockIgnoredActualCall actual; actual.withName("func"); actual.withCallOrder(1); CHECK(false == actual.returnBoolValue()); CHECK(true == actual.returnBoolValueOrDefault(true)); CHECK(false == actual.returnBoolValueOrDefault(false)); CHECK(0 == actual.returnUnsignedLongIntValue()); CHECK(0 == actual.returnIntValue()); CHECK(1ul == actual.returnUnsignedLongIntValueOrDefault(1ul)); CHECK(1 == actual.returnIntValueOrDefault(1)); CHECK(0 == actual.returnLongIntValue()); CHECK(1l == actual.returnLongIntValueOrDefault(1l)); CHECK(0 == actual.returnUnsignedIntValue()); CHECK(1u == actual.returnUnsignedIntValueOrDefault(1u)); #if CPPUTEST_USE_LONG_LONG CHECK(0 == actual.returnLongLongIntValue()); CHECK(1ll == actual.returnLongLongIntValueOrDefault(1ll)); CHECK(0 == actual.returnUnsignedLongLongIntValue()); CHECK(1ull == actual.returnUnsignedLongLongIntValueOrDefault(1ull)); #endif DOUBLES_EQUAL(0.0, actual.returnDoubleValue(), 0.0); DOUBLES_EQUAL(1.5, actual.returnDoubleValueOrDefault(1.5), 0.0); STRCMP_EQUAL("bla", actual.returnStringValueOrDefault("bla")); STRCMP_EQUAL("", actual.returnStringValue()); CHECK(NULLPTR == actual.returnPointerValue()); CHECK((void*) 0x2 == actual.returnPointerValueOrDefault((void*) 0x2)); CHECK(NULLPTR == actual.returnConstPointerValue()); CHECK((const void*) 0x2 == actual.returnConstPointerValueOrDefault((const void*) 0x2)); CHECK(NULLPTR == actual.returnFunctionPointerValue()); CHECK((void(*)()) 1 == actual.returnFunctionPointerValueOrDefault((void(*)()) 0x1)); CHECK_FALSE(actual.hasReturnValue()); CHECK(actual.returnValue().equals(MockNamedValue(""))); } TEST(MockCheckedActualCall, remainderOfMockActualCallTraceWorksAsItShould) { int value; const int const_value = 1; const unsigned char mem_buffer[] = { 0xFE, 0x15 }; void (*function_value)() = (void (*)())0xDEAD; MockActualCallTrace actual; actual.withName("func"); actual.withCallOrder(1); actual.onObject(&value); actual.withBoolParameter("bool", true); actual.withUnsignedIntParameter("unsigned_int", (unsigned int) 1); actual.withUnsignedLongIntParameter("unsigned_long", (unsigned long)1); actual.withLongIntParameter("long_int", (long int) 1); #if CPPUTEST_USE_LONG_LONG actual.withLongLongIntParameter("long_long_int", (long long int) 1); actual.withUnsignedLongLongIntParameter("unsigned_long_long_int", (unsigned long long int) 1); #endif actual.withPointerParameter("pointer", &value); actual.withConstPointerParameter("const_pointer", &const_value); actual.withFunctionPointerParameter("function_pointer", function_value); actual.withMemoryBufferParameter("mem_buffer", mem_buffer, sizeof(mem_buffer)); actual.withParameterOfType("int", "named_type", &const_value); SimpleString expectedString("\nFunction name:func"); expectedString += " withCallOrder:1"; expectedString += " onObject:0x"; expectedString += HexStringFrom(&value); expectedString += " bool:true"; expectedString += " unsigned_int:1 (0x1)"; expectedString += " unsigned_long:1 (0x1)"; expectedString += " long_int:1 (0x1)"; #if CPPUTEST_USE_LONG_LONG expectedString += " long_long_int:1 (0x1)"; expectedString += " unsigned_long_long_int:1 (0x1)"; #endif expectedString += " pointer:0x"; expectedString += HexStringFrom(&value); expectedString += " const_pointer:0x"; expectedString += HexStringFrom(&const_value); expectedString += " function_pointer:0x"; expectedString += HexStringFrom(function_value); expectedString += " mem_buffer:Size = 2 | HexContents = FE 15"; expectedString += " int named_type:0x"; expectedString += HexStringFrom(&const_value); STRCMP_EQUAL(expectedString.asCharString(), actual.getTraceOutput()); CHECK_FALSE(actual.hasReturnValue()); CHECK(actual.returnValue().equals(MockNamedValue(""))); CHECK(false == actual.returnBoolValue()); CHECK(false == actual.returnBoolValueOrDefault(true)); CHECK(0 == actual.returnLongIntValue()); CHECK(0 == actual.returnUnsignedLongIntValue()); CHECK(0 == actual.returnIntValue()); CHECK(0 == actual.returnUnsignedLongIntValueOrDefault(1ul)); CHECK(0 == actual.returnIntValueOrDefault(1)); CHECK(0 == actual.returnLongIntValue()); CHECK(0 == actual.returnLongIntValueOrDefault(1l)); #if CPPUTEST_USE_LONG_LONG CHECK(0 == actual.returnLongLongIntValue()); CHECK(0 == actual.returnLongLongIntValueOrDefault(1ll)); CHECK(0 == actual.returnUnsignedLongLongIntValue()); CHECK(0 == actual.returnUnsignedLongLongIntValueOrDefault(1ull)); #endif CHECK(0 == actual.returnUnsignedIntValue()); CHECK(0 == actual.returnUnsignedIntValueOrDefault(1u)); DOUBLES_EQUAL(0.0, actual.returnDoubleValue(), 0.0); DOUBLES_EQUAL(0.0, actual.returnDoubleValueOrDefault(1.0), 0.0); STRCMP_EQUAL("", actual.returnStringValueOrDefault("bla")); STRCMP_EQUAL("", actual.returnStringValue()); CHECK(NULLPTR == actual.returnPointerValue()); CHECK(NULLPTR == actual.returnPointerValueOrDefault((void*) NULLPTR)); CHECK(NULLPTR == actual.returnConstPointerValue()); CHECK(NULLPTR == actual.returnConstPointerValueOrDefault((const void*) NULLPTR)); CHECK(NULLPTR == actual.returnFunctionPointerValue()); CHECK(NULLPTR == actual.returnFunctionPointerValueOrDefault((void (*)()) NULLPTR)); } TEST(MockCheckedActualCall, MockActualCallTraceClear) { MockActualCallTrace actual; actual.withName("func"); actual.clear(); STRCMP_EQUAL("", actual.getTraceOutput()); }
null
62
cpp
cpputest
MockParameterTest.cpp
tests/CppUTestExt/MockParameterTest.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 "MockFailureReporterForTest.h" TEST_GROUP(MockParameterTest) { void teardown() CPPUTEST_OVERRIDE { mock().checkExpectations(); mock().clear(); } }; TEST(MockParameterTest, expectOneBooleanParameterAndValue) { mock().expectOneCall("foo").withParameter("parameter", true); mock().actualCall("foo").withParameter("parameter", true); mock().checkExpectations(); } TEST(MockParameterTest, expectOneUnsignedIntegerParameterAndValue) { unsigned int value = 14400; mock().expectOneCall("foo").withParameter("parameter", value); mock().actualCall("foo").withParameter("parameter", value); mock().checkExpectations(); } TEST(MockParameterTest, expectOneIntegerParameterAndValue) { mock().expectOneCall("foo").withParameter("parameter", 10); mock().actualCall("foo").withParameter("parameter", 10); mock().checkExpectations(); } #if CPPUTEST_USE_LONG_LONG TEST(MockParameterTest, expectOneUnsignedLongLongIntegerParameterAndValue) { unsigned long long value = 0xFFFFAAAAFFFFAAAAULL; mock().expectOneCall("foo").withParameter("parameter", value); mock().actualCall("foo").withParameter("parameter", value); mock().checkExpectations(); } TEST(MockParameterTest, expectOneLongLongIntegerParameterAndValue) { long long value = 0x7FFFAAAAFFFFAAAAULL; mock().expectOneCall("foo").withParameter("parameter", value); mock().actualCall("foo").withParameter("parameter", value); mock().checkExpectations(); } #endif TEST(MockParameterTest, mismatchedIntegerTypesIntAndLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (int)1); mock().actualCall("foo").withParameter("parameter", (long)1); mock().expectOneCall("foo").withParameter("parameter", (long)1); mock().actualCall("foo").withParameter("parameter", (int)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesIntAndUnsignedAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (int)1); mock().actualCall("foo").withParameter("parameter", (unsigned)1); mock().expectOneCall("foo").withParameter("parameter", (unsigned)1); mock().actualCall("foo").withParameter("parameter", (int)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesIntAndUnsignedLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (int)1); mock().actualCall("foo").withParameter("parameter", (unsigned long)1); mock().expectOneCall("foo").withParameter("parameter", (unsigned long)1); mock().actualCall("foo").withParameter("parameter", (int)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesUnsignedAndLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (unsigned)1); mock().actualCall("foo").withParameter("parameter", (long)1); mock().expectOneCall("foo").withParameter("parameter", (long)1); mock().actualCall("foo").withParameter("parameter", (unsigned)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesUnsignedAndUnsignedLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (unsigned)1); mock().actualCall("foo").withParameter("parameter", (unsigned long)1); mock().expectOneCall("foo").withParameter("parameter", (unsigned long)1); mock().actualCall("foo").withParameter("parameter", (unsigned)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesLongAndUnsignedLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (long)1); mock().actualCall("foo").withParameter("parameter", (unsigned long)1); mock().expectOneCall("foo").withParameter("parameter", (unsigned long)1); mock().actualCall("foo").withParameter("parameter", (long)1); mock().checkExpectations(); } #if CPPUTEST_USE_LONG_LONG TEST(MockParameterTest, mismatchedIntegerTypesIntAndLongLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (int)1); mock().actualCall("foo").withParameter("parameter", (long long)1); mock().expectOneCall("foo").withParameter("parameter", (long long)1); mock().actualCall("foo").withParameter("parameter", (int)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesIntAndUnsignedLongLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (int)1); mock().actualCall("foo").withParameter("parameter", (unsigned long long)1); mock().expectOneCall("foo").withParameter("parameter", (unsigned long long)1); mock().actualCall("foo").withParameter("parameter", (int)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesUnsignedAndLongLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (unsigned)1); mock().actualCall("foo").withParameter("parameter", (long long)1); mock().expectOneCall("foo").withParameter("parameter", (long long)1); mock().actualCall("foo").withParameter("parameter", (unsigned)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesUnsignedAndUnsignedLongLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (unsigned)1); mock().actualCall("foo").withParameter("parameter", (unsigned long long)1); mock().expectOneCall("foo").withParameter("parameter", (unsigned long long)1); mock().actualCall("foo").withParameter("parameter", (unsigned)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesUnsignedLongAndUnsignedLongLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (unsigned long)1); mock().actualCall("foo").withParameter("parameter", (unsigned long long)1); mock().expectOneCall("foo").withParameter("parameter", (unsigned long long)1); mock().actualCall("foo").withParameter("parameter", (unsigned long)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesLongAndLongLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (long)1); mock().actualCall("foo").withParameter("parameter", (long long)1); mock().expectOneCall("foo").withParameter("parameter", (long long)1); mock().actualCall("foo").withParameter("parameter", (long)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesLongAndUnsignedLongLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (long)1); mock().actualCall("foo").withParameter("parameter", (unsigned long long)1); mock().expectOneCall("foo").withParameter("parameter", (unsigned long long)1); mock().actualCall("foo").withParameter("parameter", (long)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesUnsignedLongAndLongLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (unsigned long)1); mock().actualCall("foo").withParameter("parameter", (long long)1); mock().expectOneCall("foo").withParameter("parameter", (long long)1); mock().actualCall("foo").withParameter("parameter", (unsigned long)1); mock().checkExpectations(); } TEST(MockParameterTest, mismatchedIntegerTypesLongLongAndUnsignedLongLongAreAllowed) { mock().expectOneCall("foo").withParameter("parameter", (long long)1); mock().actualCall("foo").withParameter("parameter", (unsigned long long)1); mock().expectOneCall("foo").withParameter("parameter", (unsigned long long)1); mock().actualCall("foo").withParameter("parameter", (long long)1); mock().checkExpectations(); } #endif TEST(MockParameterTest, longAndUnsignedLongWithSameBitRepresentationShouldNotBeTreatedAsEqual) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("parameter", (long)-1); MockNamedValue parameter("parameter"); parameter.setValue((unsigned long)-1); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withParameter("parameter", (long)-1); mock().actualCall("foo").withParameter("parameter", (unsigned long)-1); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, unsignedLongAndLongWithSameBitRepresentationShouldnotBeTreatedAsEqual) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("parameter", (unsigned long)-1); MockNamedValue parameter("parameter"); parameter.setValue((long)-1); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withParameter("parameter", (unsigned long)-1); mock().actualCall("foo").withParameter("parameter", (long)-1); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, expectOneDoubleParameterAndValue) { mock().expectOneCall("foo").withParameter("parameter", 1.0); mock().actualCall("foo").withParameter("parameter", 1.0); mock().checkExpectations(); } TEST(MockParameterTest, expectOneDoubleParameterAndValueAndTolerance) { mock( ).expectOneCall("foo").withParameter("parameter", 100.0, 5.0); mock( ).actualCall("foo").withParameter("parameter", 96.0); mock( ).checkExpectations(); } TEST(MockParameterTest, doubleParameterNotEqualIfOutsideTolerance) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("parameter", 100.0); MockNamedValue parameter("parameter"); parameter.setValue(106.0); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock( ).expectOneCall("foo").withParameter("parameter", 100.0, 5.0); mock( ).actualCall("foo").withParameter("parameter", 106.0); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, expectOneStringParameterAndValue) { mock().expectOneCall("foo").withParameter("parameter", "string"); mock().actualCall("foo").withParameter("parameter", "string"); mock().checkExpectations(); } TEST(MockParameterTest, expectOnePointerParameterAndValue) { mock().expectOneCall("foo").withParameter("parameter", (void*) 0x01); mock().actualCall("foo").withParameter("parameter", (void*) 0x01); mock().checkExpectations(); } TEST(MockParameterTest, expectOneConstPointerParameterAndValue) { mock().expectOneCall("foo").withParameter("parameter", (const void*) 0x01); mock().actualCall("foo").withParameter("parameter", (const void*) 0x01); mock().checkExpectations(); } TEST(MockParameterTest, expectOneFunctionPointerParameterAndValue) { mock().expectOneCall("foo").withParameter("parameter", (void(*)()) 0x01); mock().actualCall("foo").withParameter("parameter", (void(*)()) 0x01); mock().checkExpectations(); } TEST(MockParameterTest, expectOneMemBufferParameterAndValue) { unsigned char memBuffer1[] = { 0x12, 0x15, 0xFF }; unsigned char memBuffer2[] = { 0x12, 0x15, 0xFF }; mock().expectOneCall("foo").withParameter("parameter", memBuffer1, sizeof(memBuffer1)); mock().actualCall("foo").withParameter("parameter", memBuffer2, sizeof(memBuffer2)); mock().checkExpectations(); } TEST(MockParameterTest, expectOneMemBufferParameterAndValueFailsDueToContents) { MockFailureReporterInstaller failureReporterInstaller; unsigned char memBuffer1[] = { 0x12, 0x15, 0xFF }; unsigned char memBuffer2[] = { 0x12, 0x05, 0xFF }; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("parameter", memBuffer1, sizeof(memBuffer1)); MockNamedValue parameter("parameter"); parameter.setMemoryBuffer( memBuffer2, sizeof(memBuffer2) ); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withParameter("parameter", memBuffer1, sizeof(memBuffer1)); mock().actualCall("foo").withParameter("parameter", memBuffer2, sizeof(memBuffer2)); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, expectOneMemBufferParameterAndValueFailsDueToSize) { MockFailureReporterInstaller failureReporterInstaller; unsigned char memBuffer1[] = { 0x12, 0x15, 0xFF }; unsigned char memBuffer2[] = { 0x12, 0x15, 0xFF, 0x90 }; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("parameter", memBuffer1, sizeof(memBuffer1)); MockNamedValue parameter("parameter"); parameter.setMemoryBuffer( memBuffer2, sizeof(memBuffer2) ); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withParameter("parameter", memBuffer1, sizeof(memBuffer1)); mock().actualCall("foo").withParameter("parameter", memBuffer2, sizeof(memBuffer2)); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, expectOneStringParameterAndValueFails) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("parameter", "string"); MockNamedValue parameter("parameter"); parameter.setValue("different"); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withParameter("parameter", "string"); mock().actualCall("foo").withParameter("parameter", "different"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, expectOneUnsignedIntegerParameterAndFailsDueToParameterName) { MockFailureReporterInstaller failureReporterInstaller; unsigned int value = 7; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("parameter", value); MockNamedValue parameter("different"); parameter.setValue(value); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withParameter("parameter", value); mock().actualCall("foo").withParameter("different", value); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, expectOneIntegerParameterAndFailsDueToParameterName) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("parameter", 10); MockNamedValue parameter("different"); parameter.setValue(10); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withParameter("parameter", 10); mock().actualCall("foo").withParameter("different", 10); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, expectOneUnsignedIntegerParameterAndFailsDueToValue) { MockFailureReporterInstaller failureReporterInstaller; unsigned int actual_value = 8; unsigned int expected_value = actual_value + 1; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("parameter", expected_value); MockNamedValue parameter("parameter"); parameter.setValue(actual_value); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withParameter("parameter", expected_value); mock().actualCall("foo").withParameter("parameter", actual_value); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, expectOneIntegerParameterAndFailsDueToValue) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("parameter", 10); MockNamedValue parameter("parameter"); parameter.setValue(8); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withParameter("parameter", 10); mock().actualCall("foo").withParameter("parameter", 8); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, expectOneIntegerParameterAndFailsDueToTypes) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("parameter", 10); MockNamedValue parameter("parameter"); parameter.setValue("heh"); MockUnexpectedInputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().expectOneCall("foo").withParameter("parameter", 10); mock().actualCall("foo").withParameter("parameter", "heh"); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, 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(); } TEST(MockParameterTest, 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(); } TEST(MockParameterTest, 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(); } TEST(MockParameterTest, calledWithoutParameters) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("p1", 1); MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations, expectations); mock().expectOneCall("foo").withParameter("p1", 1); mock().actualCall("foo"); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, ignoreOtherParameters) { mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters(); mock().actualCall("foo").withParameter("p1", 1).withParameter("p2", 2); mock().checkExpectations(); } TEST(MockParameterTest, ignoreOtherParametersButStillPassAll) { mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters(); mock().actualCall("foo").withParameter("p1", 1); mock().checkExpectations(); } TEST(MockParameterTest, ignoreOtherParametersButExpectedParameterDidntHappen) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("p1", 1).ignoreOtherParameters(); MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations, expectations); mock().expectOneCall("foo").withParameter("p1", 1).ignoreOtherParameters(); mock().actualCall("foo").withParameter("p2", 2).withParameter("p3", 3).withParameter("p4", 4); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, 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(); } TEST(MockParameterTest, ignoreOtherParametersMultipleCallsButOneDidntHappen) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; MockCheckedExpectedCall* call = expectations.addFunction("boo"); call->ignoreOtherParameters(); call->callWasMade(1); call->finalizeActualCallMatch(); call->ignoreOtherParameters(); expectations.addFunction("boo")->ignoreOtherParameters(); MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); mock().expectOneCall("boo").ignoreOtherParameters(); mock().expectOneCall("boo").ignoreOtherParameters(); mock().actualCall("boo"); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, newCallStartsWhileNotAllParametersWerePassed) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; expectations.addFunction("foo")->withParameter("p1", 1); MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations, expectations); mock().expectOneCall("foo").withParameter("p1", 1); mock().actualCall("foo"); mock().actualCall("foo").withParameter("p1", 1); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, outputParameterSucceeds) { int param = 1; int retval = 2; mock().expectOneCall("function").withOutputParameterReturning("parameterName", &retval, sizeof(retval)); mock().actualCall("function").withOutputParameter("parameterName", &param); CHECK_EQUAL(param, 2); CHECK_EQUAL(retval, 2); mock().checkExpectations(); } TEST(MockParameterTest, unmodifiedOutputParameterSucceeds) { int param = 1; mock().expectOneCall("function").withUnmodifiedOutputParameter("parameterName"); mock().actualCall("function").withOutputParameter("parameterName", &param); CHECK_EQUAL(param, 1); mock().checkExpectations(); } TEST(MockParameterTest, noActualCallForOutputParameter) { MockFailureReporterInstaller failureReporterInstaller; int output; MockExpectedCallsListForTest expectations; mock().expectOneCall("foo").withOutputParameterReturning("output", &output, sizeof(output)); expectations.addFunction("foo")->withOutputParameterReturning("output", &output, sizeof(output)); MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, noActualCallForUnmodifiedOutputParameter) { MockFailureReporterInstaller failureReporterInstaller; MockExpectedCallsListForTest expectations; mock().expectOneCall("foo").withUnmodifiedOutputParameter("output"); expectations.addFunction("foo")->withUnmodifiedOutputParameter("output"); MockExpectedCallsDidntHappenFailure expectedFailure(mockFailureTest(), expectations); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, unexpectedOutputParameter) { MockFailureReporterInstaller failureReporterInstaller; int param; MockExpectedCallsListForTest expectations; mock().expectOneCall("foo"); mock().actualCall("foo").withOutputParameter("parameterName", &param); expectations.addFunction("foo"); MockNamedValue parameter("parameterName"); parameter.setValue(&param); MockUnexpectedOutputParameterFailure expectedFailure(mockFailureTest(), "foo", parameter, expectations); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, outputParameterMissing) { MockFailureReporterInstaller failureReporterInstaller; int output; MockExpectedCallsListForTest expectations; mock().expectOneCall("foo").withOutputParameterReturning("output", &output, sizeof(output)); mock().actualCall("foo"); expectations.addFunction("foo")->withOutputParameterReturning("output", &output, sizeof(output)); MockExpectedParameterDidntHappenFailure expectedFailure(mockFailureTest(), "foo", expectations, expectations); mock().checkExpectations(); CHECK_EXPECTED_MOCK_FAILURE(expectedFailure); } TEST(MockParameterTest, twoOutputParameters) { int param1 = 55; int retval1 = 1; int param2 = 77; int retval2 = 2; mock().expectOneCall("function").withOutputParameterReturning("parameterName", &retval1, sizeof(retval1)).withParameter("id", 1); mock().expectOneCall("function").withOutputParameterReturning("parameterName", &retval2, sizeof(retval2)).withParameter("id", 2); mock().actualCall("function").withOutputParameter("parameterName", &param1).withParameter("id", 1); mock().actualCall("function").withOutputParameter("parameterName", &param2).withParameter("id", 2); CHECK_EQUAL(retval1, param1); CHECK_EQUAL(retval2, param2); mock().checkExpectations(); } TEST(MockParameterTest, twoInterleavedOutputParameters) { int param1 = 55; int retval1 = 1; int param2 = 77; int retval2 = 2; mock().expectOneCall("function").withOutputParameterReturning("parameterName", &retval1, sizeof(retval1)).withParameter("id", 1); mock().expectOneCall("function").withOutputParameterReturning("parameterName", &retval2, sizeof(retval2)).withParameter("id", 2); mock().actualCall("function").withOutputParameter("parameterName", &param2).withParameter("id", 2); mock().actualCall("function").withOutputParameter("parameterName", &param1).withParameter("id", 1); CHECK_EQUAL(retval1, param1); CHECK_EQUAL(retval2, param2); mock().checkExpectations(); } TEST(MockParameterTest, twoDifferentOutputParametersInSameFunctionCallSucceeds) { int param1 = 1; int param2 = 1; int retval1 = 2; int retval2 = 3; mock().expectOneCall("foo") .withOutputParameterReturning("bar", &retval1, sizeof(retval1)) .withOutputParameterReturning("foobar", &retval2, sizeof(retval2)); mock().actualCall("foo") .withOutputParameter("bar", &param1) .withOutputParameter("foobar", &param2); CHECK_EQUAL(2, retval1); CHECK_EQUAL(2, param1); CHECK_EQUAL(3, retval2); CHECK_EQUAL(3, param2); mock().checkExpectations(); } TEST(MockParameterTest, outputAndIntParametersOfSameNameInDifferentFunctionCallsOfSameFunctionSucceeds) { int param = 1; int retval = 2; mock().expectOneCall("foo").withOutputParameterReturning("bar", &retval, sizeof(retval)); mock().expectOneCall("foo").withIntParameter("bar", 25); mock().actualCall("foo").withOutputParameter("bar", &param); mock().actualCall("foo").withIntParameter("bar", 25); CHECK_EQUAL(2, retval); CHECK_EQUAL(2, param); mock().checkExpectations(); } TEST(MockParameterTest, twoOutputParameterOfSameNameInDifferentFunctionCallsOfSameFunctionSucceeds) { int param1 = 1; int param2 = 1; int retval1 = 2; int retval2 = 3; mock().expectOneCall("foo").withOutputParameterReturning("bar", &retval1, sizeof(retval1)); mock().expectOneCall("foo").withOutputParameterReturning("bar", &retval2, sizeof(retval2)); mock().actualCall("foo").withOutputParameter("bar", &param1); mock().actualCall("foo").withOutputParameter("bar", &param2); CHECK_EQUAL(2, retval1); CHECK_EQUAL(2, param1); CHECK_EQUAL(3, retval2); CHECK_EQUAL(3, param2); mock().checkExpectations(); } TEST(MockParameterTest, twoOutputParametersOfSameNameInDifferentFunctionsSucceeds) { int param = 1; int retval = 2; mock().expectOneCall("foo1").withOutputParameterReturning("bar", &retval, sizeof(retval)); mock().expectOneCall("foo2").withIntParameter("bar", 25); mock().actualCall("foo1").withOutputParameter("bar", &param); mock().actualCall("foo2").withIntParameter("bar", 25); CHECK_EQUAL(2, retval); CHECK_EQUAL(2, param); mock().checkExpectations(); } TEST(MockParameterTest, outputAndInputParameter) { int return_value = 5; int returned_value = 7; mock().expectOneCall("foo").withParameter("bar", 10).withOutputParameterReturning("bar", &return_value, sizeof(return_value)); mock().actualCall("foo").withParameter("bar", 10).withOutputParameter("bar", &returned_value); LONGS_EQUAL(5, returned_value); mock().checkExpectations(); } TEST(MockParameterTest, outputParameterTraced) { mock().tracing(true); int param = 1; mock().actualCall("someFunc").withOutputParameter("someParameter", &param); mock().checkExpectations(); STRCMP_CONTAINS("Function name:someFunc someParameter:", mock().getTraceOutput()); mock().checkExpectations(); } TEST(MockParameterTest, outputParameterThatIsIgnoredShouldNotFail) { int param; mock().expectOneCall("function").ignoreOtherParameters(); mock().actualCall("function").withOutputParameter("parameterName", &param); mock().checkExpectations(); } TEST(MockParameterTest, outputParameterWithIgnoredParameters) { int param = 1; int retval = 2; mock().expectOneCall("foo").withOutputParameterReturning("bar", &param, sizeof(param)).ignoreOtherParameters(); mock().actualCall("foo").withOutputParameter("bar", &retval).withParameter("other", 1); LONGS_EQUAL(param, retval); mock().checkExpectations(); } /* * This test checks that the proper output parameters are copied when multiple calls to the same * function are expected. */ TEST(MockParameterTest, properOutputParametersAreCopied) { int expectedValue1 = 1; int expectedValue2 = 2; mock().expectOneCall("foo").withOutputParameterReturning("param", &expectedValue1, sizeof(expectedValue1)).ignoreOtherParameters(); mock().expectOneCall("foo").withOutputParameterReturning("param", &expectedValue2, sizeof(expectedValue2)); int returnedValue1 = 0; int returnedValue2 = 0; mock().actualCall("foo").withOutputParameter("param", &returnedValue1); mock().actualCall("foo").withOutputParameter("param", &returnedValue2).withParameter("optional", 50); CHECK_EQUAL_TEXT(expectedValue2, returnedValue1, "Wrong output value in 1st call"); CHECK_EQUAL_TEXT(expectedValue1, returnedValue2, "Wrong output value in 2nd call"); mock().checkExpectations(); } TEST(MockParameterTest, ignoreOtherCallsIgnoresWithAllKindsOfParameters) { mock().ignoreOtherCalls(); mock().actualCall("boo") .withParameter("umm", true) .withParameter("bar", 1u) .withParameter("foo", 1l) .withParameter("hey", 1ul) #if CPPUTEST_USE_LONG_LONG .withParameter("ick", 1ll) .withParameter("grr", 1ull) #endif .withParameter("duh", 1.0) .withParameter("yoo", (const void*) NULLPTR) .withParameter("func", (void(*)()) NULLPTR) .withParameter("mem", (const unsigned char*) NULLPTR, 0) .withParameterOfType("hoo", "int", (const void*) NULLPTR) .withOutputParameter("gah", (void*) NULLPTR) .withOutputParameterOfType("goo", "int", (void*) NULLPTR); mock().checkExpectations(); } TEST(MockParameterTest, expectMultipleCallsWithParameters) { int expected_int = -7; unsigned int expected_uint = 7; mock().expectNCalls(2, "boo").withParameter("double", 1.0).withParameter("int", expected_int). withParameter("string", "string").withParameter("uint", expected_uint); mock().actualCall("boo").withParameter("double", 1.0).withParameter("int", expected_int).withParameter("string", "string"). withParameter("uint", expected_uint); mock().actualCall("boo").withParameter("double", 1.0).withParameter("int", expected_int).withParameter("string", "string"). withParameter("uint", expected_uint); mock().checkExpectations(); } TEST(MockParameterTest, 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(); }
null
63
cpp
cpputest
IEEE754PluginTest.cpp
tests/CppUTestExt/IEEE754PluginTest.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/CommandLineTestRunner.h" #include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTestExt/IEEE754ExceptionsPlugin.h" #if CPPUTEST_HAVE_FENV #include "IEEE754PluginTest_c.h" TEST_GROUP(FE_with_Plugin) { TestTestingFixture fixture; IEEE754ExceptionsPlugin ieee754Plugin; void setup(void) CPPUTEST_OVERRIDE { fixture.installPlugin(&ieee754Plugin); } }; TEST(FE_with_Plugin, should_fail_when_FE_DIVBYZERO_is_set) { fixture.setTestFunction(set_divisionbyzero_c); fixture.runAllTests(); fixture.assertPrintContains("IEEE754_CHECK_CLEAR(FE_DIVBYZERO) failed"); } TEST(FE_with_Plugin, should_fail_when_FE_OVERFLOW_is_set) { fixture.setTestFunction(set_overflow_c); fixture.runAllTests(); fixture.assertPrintContains("IEEE754_CHECK_CLEAR(FE_OVERFLOW) failed"); } TEST(FE_with_Plugin, should_fail_when_FE_UNDERFLOW_is_set) { fixture.setTestFunction(set_underflow_c); fixture.runAllTests(); fixture.assertPrintContains("IEEE754_CHECK_CLEAR(FE_UNDERFLOW) failed"); } TEST(FE_with_Plugin, should_fail_when_FE_INEXACT_is_set_and_enabled) { IEEE754ExceptionsPlugin::enableInexact(); fixture.setTestFunction(set_inexact_c); fixture.runAllTests(); fixture.assertPrintContains("IEEE754_CHECK_CLEAR(FE_INEXACT) failed"); } TEST(FE_with_Plugin, should_succeed_when_FE_INEXACT_is_set_and_disabled) { IEEE754ExceptionsPlugin::enableInexact(); IEEE754ExceptionsPlugin::disableInexact(); fixture.setTestFunction(set_inexact_c); fixture.runAllTests(); fixture.assertPrintContains("OK"); } TEST(FE_with_Plugin, should_succeed_with_5_checks_when_no_flags_are_set) { IEEE754ExceptionsPlugin::enableInexact(); fixture.setTestFunction(set_nothing_c); fixture.runAllTests(); fixture.assertPrintContains("OK (1 tests, 1 ran, 5 checks, 0 ignored, 0 filtered out"); IEEE754ExceptionsPlugin::disableInexact(); } TEST(FE_with_Plugin, should_check_five_times_when_all_flags_are_set) { fixture.setTestFunction(set_everything_c); fixture.runAllTests(); LONGS_EQUAL(5, fixture.getCheckCount()); } TEST(FE_with_Plugin, should_fail_only_once_when_all_flags_are_set) { fixture.setTestFunction(set_everything_c); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); } static void set_everything_but_already_failed(void) { set_everything_c(); CHECK(1 == 2); } TEST(FE_with_Plugin, should_not_fail_again_when_test_has_already_failed) { fixture.setTestFunction(set_everything_but_already_failed); fixture.runAllTests(); CHECK(IEEE754ExceptionsPlugin::checkIeee754OverflowExceptionFlag()); CHECK(IEEE754ExceptionsPlugin::checkIeee754UnderflowExceptionFlag()); CHECK(IEEE754ExceptionsPlugin::checkIeee754InexactExceptionFlag()); CHECK(IEEE754ExceptionsPlugin::checkIeee754DivByZeroExceptionFlag()); LONGS_EQUAL(1, fixture.getCheckCount()); LONGS_EQUAL(1, fixture.getFailureCount()); } static IEEE754ExceptionsPlugin ip; TEST_GROUP(IEEE754ExceptionsPlugin2) { void setup(void) CPPUTEST_OVERRIDE { TestRegistry::getCurrentRegistry()->installPlugin(&ip); } }; IGNORE_TEST(IEEE754ExceptionsPlugin2, should_not_fail_in_ignored_test) { set_everything_c(); } #endif
null
64
cpp
cpputest
MockSupportTest.cpp
tests/CppUTestExt/MockSupportTest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTestExt/MockSupport.h" #include "CppUTestExt/MockExpectedCall.h" #include "CppUTestExt/MockFailure.h" #include "MockFailureReporterForTest.h" TEST_GROUP(MockSupportTest) { MockExpectedCallsListForTest expectations; MockFailureReporterInstaller failureReporterInstaller; void teardown() CPPUTEST_OVERRIDE { mock().checkExpectations(); CHECK_NO_MOCK_FAILURE(); MockFailureReporterForTest::clearReporter(); mock().clear(); } }; TEST(MockSupportTest, setDataForUnsignedIntegerValues) { unsigned int expected_data = 7; mock().setData("data", expected_data); LONGS_EQUAL(expected_data, mock().getData("data").getUnsignedIntValue()); } TEST(MockSupportTest, setDataForIntegerValues) { int expected_data = 10; mock().setData("data", expected_data); LONGS_EQUAL(expected_data, mock().getData("data").getIntValue()); } TEST(MockSupportTest, setDataForBooleanValues) { bool expected_data = true; mock().setData("data", expected_data); CHECK_EQUAL(expected_data, mock().getData("data").getBoolValue()); } 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, setConstDataPointer) { const void * ptr = (const void*) 0x001; mock().setData("data", ptr); POINTERS_EQUAL(ptr, mock().getData("data").getConstPointerValue()); } TEST(MockSupportTest, setDataFunctionPointer) { void (*ptr)() = (void(*)()) 0x001; mock().setData("data", ptr); FUNCTIONPOINTERS_EQUAL(ptr, mock().getData("data").getFunctionPointerValue()); } 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, setDataConstObject) { void * ptr = (void*) 0x011; mock().setDataConstObject("data", "type", ptr); POINTERS_EQUAL(ptr, mock().getData("data").getConstObjectPointer()); STRCMP_EQUAL("type", mock().getData("data").getType().asCharString()); } TEST(MockSupportTest, tracing) { mock().tracing(true); 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()); } TEST(MockSupportTest, tracingWorksHierarchically) { mock("scope").tracing(true); mock().tracing(true); mock().actualCall("boo"); mock("scope").actualCall("foo"); mock().checkExpectations(); STRCMP_CONTAINS("boo", mock().getTraceOutput()); STRCMP_CONTAINS("foo", mock().getTraceOutput()); } TEST_GROUP(MockSupportTestWithFixture) { TestTestingFixture fixture; void teardown() CPPUTEST_OVERRIDE { mock().clear(); MockFailureReporterForTest::clearReporter(); } }; static void CHECK_EXPECTED_MOCK_FAILURE_LOCATION_failedTestMethod_() { MockExpectedCallsList list; MockUnexpectedCallHappenedFailure expectedFailure(UtestShell::getCurrent(), "unexpected", list); mock().actualCall("boo"); CHECK_EXPECTED_MOCK_FAILURE_LOCATION(expectedFailure, "file", 1); } TEST(MockSupportTestWithFixture, CHECK_EXPECTED_MOCK_FAILURE_LOCATION_failed) { mock().setMockFailureStandardReporter(MockFailureReporterForTest::getReporter()); fixture.setTestFunction(CHECK_EXPECTED_MOCK_FAILURE_LOCATION_failedTestMethod_); fixture.runAllTests(); fixture.assertPrintContains("MockFailures are different."); fixture.assertPrintContains("Expected MockFailure:"); fixture.assertPrintContains("Mock Failure: Unexpected call to function: unexpected"); fixture.assertPrintContains("Actual MockFailure:"); fixture.assertPrintContains("Mock Failure: Unexpected call to function: boo"); } static void CHECK_NO_MOCK_FAILURE_LOCATION_failedTestMethod_() { mock().actualCall("boo"); CHECK_NO_MOCK_FAILURE_LOCATION("file", 1); } TEST(MockSupportTestWithFixture, CHECK_NO_MOCK_FAILURE_LOCATION_failed) { mock().setMockFailureStandardReporter(MockFailureReporterForTest::getReporter()); fixture.setTestFunction(CHECK_NO_MOCK_FAILURE_LOCATION_failedTestMethod_); fixture.runAllTests(); fixture.assertPrintContains("Unexpected mock failure:"); fixture.assertPrintContains("Mock Failure: Unexpected call to function: boo"); } static bool cpputestHasCrashed; static void crashMethod() { cpputestHasCrashed = true; } static void unexpectedCallTestFunction_(void) { mock().actualCall("unexpected"); } // LCOV_EXCL_LINE #include "CppUTestExt/OrderedTest.h" TEST(MockSupportTestWithFixture, shouldCrashOnFailure) { cpputestHasCrashed = false; mock().crashOnFailure(true); UtestShell::setCrashMethod(crashMethod); fixture.setTestFunction(unexpectedCallTestFunction_); fixture.runAllTests(); CHECK(cpputestHasCrashed); mock().crashOnFailure(false); UtestShell::resetCrashMethod(); } TEST(MockSupportTestWithFixture, ShouldNotCrashOnFailureAfterCrashMethodWasReset) { cpputestHasCrashed = false; UtestShell::setCrashMethod(crashMethod); fixture.setTestFunction(unexpectedCallTestFunction_); UtestShell::resetCrashMethod(); fixture.runAllTests(); fixture.assertPrintContains("Unexpected call to function: unexpected"); CHECK_FALSE(cpputestHasCrashed); } TEST(MockSupportTestWithFixture, shouldCrashOnFailureWithCppUTestSetting) { cpputestHasCrashed = false; UtestShell::setCrashOnFail(); UtestShell::setCrashMethod(crashMethod); fixture.setTestFunction(unexpectedCallTestFunction_); fixture.runAllTests(); CHECK(cpputestHasCrashed); UtestShell::restoreDefaultTestTerminator(); UtestShell::resetCrashMethod(); } TEST(MockSupportTestWithFixture, failedMockShouldFailAgainWhenRepeated) { fixture.setTestFunction(unexpectedCallTestFunction_); int repeatCount = 2; while(repeatCount--) { fixture.runAllTests(); fixture.assertPrintContains("Unexpected call to function: unexpected"); fixture.assertPrintContains("Errors (1 failures, 1 tests, 1 ran, 0 checks, 0 ignored, 0 filtered out"); fixture.flushOutputAndResetResult(); } }
null
65
cpp
cpputest
ExpectedFunctionsListTest.cpp
tests/CppUTestExt/ExpectedFunctionsListTest.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" #include "CppUTestExt/MockFailure.h" #include "MockFailureReporterForTest.h" TEST_GROUP(MockExpectedCallsList) { MockExpectedCallsList * list; MockCheckedExpectedCall* call1; MockCheckedExpectedCall* call2; MockCheckedExpectedCall* call3; MockCheckedExpectedCall* call4; void setup() CPPUTEST_OVERRIDE { list = new MockExpectedCallsList; call1 = new MockCheckedExpectedCall; call2 = new MockCheckedExpectedCall; call3 = new MockCheckedExpectedCall; call4 = new MockCheckedExpectedCall; call1->withName("foo"); call2->withName("bar"); call3->withName("boo"); } void teardown() CPPUTEST_OVERRIDE { delete call1; delete call2; delete call3; delete call4; delete list; CHECK_NO_MOCK_FAILURE(); MockFailureReporterForTest::clearReporter(); } }; TEST(MockExpectedCallsList, emptyList) { CHECK(! list->hasUnfulfilledExpectations()); CHECK(! list->hasFinalizedMatchingExpectations()); LONGS_EQUAL(0, list->size()); } TEST(MockExpectedCallsList, addingCalls) { list->addExpectedCall(call1); list->addExpectedCall(call2); LONGS_EQUAL(2, list->size()); } TEST(MockExpectedCallsList, listWithFulfilledExpectationHasNoUnfulfilledOnes) { call1->callWasMade(1); call2->callWasMade(2); list->addExpectedCall(call1); list->addExpectedCall(call2); CHECK(! list->hasUnfulfilledExpectations()); } TEST(MockExpectedCallsList, listWithFulfilledExpectationButOutOfOrder) { call1->withCallOrder(1); call2->withCallOrder(2); list->addExpectedCall(call1); list->addExpectedCall(call2); call2->callWasMade(1); call1->callWasMade(2); CHECK(! list->hasUnfulfilledExpectations()); CHECK(list->hasCallsOutOfOrder()); } TEST(MockExpectedCallsList, listWithUnFulfilledExpectationHasNoUnfillfilledOnes) { call1->callWasMade(1); call3->callWasMade(2); list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); CHECK(list->hasUnfulfilledExpectations()); } TEST(MockExpectedCallsList, deleteAllExpectationsAndClearList) { list->addExpectedCall(new MockCheckedExpectedCall); list->addExpectedCall(new MockCheckedExpectedCall); list->deleteAllExpectationsAndClearList(); } TEST(MockExpectedCallsList, onlyKeepUnmatchingExpectations) { call1->withName("relate"); call2->withName("unrelate"); call3->withName("relate").withParameter("param",1); list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); list->onlyKeepUnmatchingExpectations(); LONGS_EQUAL(1, list->size()); } TEST(MockExpectedCallsList, onlyKeepExpectationsRelatedTo) { call1->withName("relate"); call2->withName("unrelate"); call3->withName("unrelate"); list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); list->onlyKeepExpectationsRelatedTo("relate"); LONGS_EQUAL(1, list->size()); } TEST(MockExpectedCallsList, removeAllExpectationsExceptThisThatRelateToTheWoleList) { call1->withName("relate"); call2->withName("relate"); call3->withName("relate"); list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); list->onlyKeepExpectationsRelatedTo("unrelate"); LONGS_EQUAL(0, list->size()); } TEST(MockExpectedCallsList, removeAllExpectationsExceptThisThatRelateToFirstOne) { call1->withName("relate"); call2->withName("unrelate"); list->addExpectedCall(call1); list->addExpectedCall(call2); list->onlyKeepExpectationsRelatedTo("unrelate"); LONGS_EQUAL(1, list->size()); } TEST(MockExpectedCallsList, removeAllExpectationsExceptThisThatRelateToLastOne) { call1->withName("unrelate"); call2->withName("relate"); list->addExpectedCall(call1); list->addExpectedCall(call2); list->onlyKeepExpectationsRelatedTo("unrelate"); LONGS_EQUAL(1, list->size()); } TEST(MockExpectedCallsList, onlyKeepExpectationsWithInputParameterName) { 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->onlyKeepExpectationsWithInputParameterName("diffname"); LONGS_EQUAL(2, list->size()); } TEST(MockExpectedCallsList, onlyKeepExpectationsWithInputParameter) { 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->inputParameterWasPassed("diffname"); list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); list->addExpectedCall(call4); list->onlyKeepExpectationsWithInputParameter(parameter); LONGS_EQUAL(2, list->size()); } TEST(MockExpectedCallsList, addPotentiallyMatchingExpectationsWithEmptyList) { MockExpectedCallsList newList; newList.addPotentiallyMatchingExpectations(*list); LONGS_EQUAL(0, newList.size()); } TEST(MockExpectedCallsList, addPotentiallyMatchingExpectationsMultipleUnmatchedExpectations) { call2->callWasMade(1); list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); MockExpectedCallsList newList; newList.addPotentiallyMatchingExpectations(*list); LONGS_EQUAL(2, newList.size()); } TEST(MockExpectedCallsList, amountOfActualCallsFulfilledFor_HasOneRelated) { call1->withName("foo"); call1->callWasMade(1); call2->withName("bar"); call2->callWasMade(2); list->addExpectedCall(call1); list->addExpectedCall(call2); LONGS_EQUAL(1, list->amountOfActualCallsFulfilledFor("bar")); } TEST(MockExpectedCallsList, amountOfActualCallsFulfilledFor_HasNone) { call1->withName("foo"); call1->callWasMade(1); call2->withName("bar"); list->addExpectedCall(call1); LONGS_EQUAL(0, list->amountOfActualCallsFulfilledFor("bar")); } TEST(MockExpectedCallsList, 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->unfulfilledCallsToString().asCharString()); } TEST(MockExpectedCallsList, callsWithMissingParametersToString) { call1->withName("foo").withParameter("boo", 0); call2->withName("bar").withParameter("baa", 10).withParameter("baz", "blah"); call2->inputParameterWasPassed("baa"); list->addExpectedCall(call1); list->addExpectedCall(call2); SimpleString expectedString; expectedString = StringFromFormat("-%s\n-#%s\n-%s\n-#%s", call1->callToString().asCharString(), call1->missingParametersToString().asCharString(), call2->callToString().asCharString(), call2->missingParametersToString().asCharString()); STRCMP_EQUAL(expectedString.asCharString(), list->callsWithMissingParametersToString("-", "#").asCharString()); } TEST(MockExpectedCallsList, callToStringForFulfilledFunctions) { call1->withName("foo"); call2->withName("bar"); call2->callWasMade(1); call1->callWasMade(2); list->addExpectedCall(call1); list->addExpectedCall(call2); SimpleString expectedString; expectedString = StringFromFormat("%s\n%s", call1->callToString().asCharString(), call2->callToString().asCharString()); STRCMP_EQUAL(expectedString.asCharString(), list->fulfilledCallsToString().asCharString()); } TEST(MockExpectedCallsList, removeOneFinalizedMatchingExpectationFromEmptyList) { POINTERS_EQUAL(NULLPTR, list->removeFirstFinalizedMatchingExpectation()); } TEST(MockExpectedCallsList, getOneMatchingExpectationFromEmptyList) { POINTERS_EQUAL(NULLPTR, list->getFirstMatchingExpectation()); } TEST(MockExpectedCallsList, toStringOnEmptyList) { STRCMP_EQUAL("<none>", list->unfulfilledCallsToString().asCharString()); } TEST(MockExpectedCallsList, hasFinalizedMatchingExpectations_emptyList) { CHECK(! list->hasFinalizedMatchingExpectations()); } TEST(MockExpectedCallsList, hasFinalizedMatchingExpectations_listHasNonMatchingCalls) { call1->withParameter("param", 0); call2->withParameter("param", 0); call3->withParameter("param", 0); list->addExpectedCall(call1); list->addExpectedCall(call2); list->addExpectedCall(call3); CHECK(! list->hasFinalizedMatchingExpectations()); } TEST(MockExpectedCallsList, hasFinalizedMatchingExpectations_listHasMatchingButNotFinalizedCall) { list->addExpectedCall(call1); list->addExpectedCall(call2); call1->ignoreOtherParameters(); call2->withParameter("param", 0); CHECK(! list->hasFinalizedMatchingExpectations()); } TEST(MockExpectedCallsList, hasFinalizedMatchingExpectations_listHasFinalizedCallThatIgnoresParameters) { list->addExpectedCall(call1); list->addExpectedCall(call2); call1->ignoreOtherParameters(); call2->withParameter("param", 0); call1->finalizeActualCallMatch(); CHECK(list->hasFinalizedMatchingExpectations()); } TEST(MockExpectedCallsList, hasFinalizedMatchingExpectations_listHasFinalizedCallThatDoesntIgnoreParameters) { list->addExpectedCall(call1); list->addExpectedCall(call2); call1->withParameter("param", 1); call2->withParameter("param", 0); call1->inputParameterWasPassed("param"); CHECK(list->hasFinalizedMatchingExpectations()); }
null
66
cpp
cpputest
MemoryReportAllocatorTest.cpp
tests/CppUTestExt/MemoryReportAllocatorTest.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) { MemoryReportAllocator allocator; }; TEST(MemoryReportAllocator, FunctionsAreForwardedForMallocAllocator) { allocator.setRealAllocator(getCurrentMallocAllocator()); STRCMP_EQUAL("malloc", allocator.alloc_name()); STRCMP_EQUAL("free", allocator.free_name()); } TEST(MemoryReportAllocator, keepingTrackOfActualAllocator) { TestMemoryAllocator* originalAllocator = getCurrentMallocAllocator(); allocator.setRealAllocator(getCurrentMallocAllocator()); POINTERS_EQUAL(originalAllocator->actualAllocator(), allocator.actualAllocator()); }
null
67
cpp
cpputest
MockSupport_cTestCFile.h
tests/CppUTestExt/MockSupport_cTestCFile.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 #ifdef __cplusplus extern "C" { #endif extern void all_mock_support_c_calls(void); #ifdef __cplusplus } #endif #endif /* TESTMOCKSUPPORTC_CFILE_H */
null
68
cpp
cpputest
MemoryReportFormatterTest.cpp
tests/CppUTestExt/MemoryReportFormatterTest.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 TESTOUTPUT_EQUAL(a) STRCMP_EQUAL_LOCATION(a, testOutput.getOutput().asCharString(), "", __FILE__, __LINE__) TEST_GROUP(NormalMemoryReportFormatter) { char* memory01; StringBufferTestOutput testOutput; TestResult* testResult; NormalMemoryReportFormatter formatter; void setup() CPPUTEST_OVERRIDE { memory01 = (char*) 0x01; testResult = new TestResult(testOutput); } void teardown() CPPUTEST_OVERRIDE { delete testResult; } }; TEST(NormalMemoryReportFormatter, mallocCreatesAnMallocCall) { formatter.report_alloc_memory(testResult, defaultMallocAllocator(), 10, memory01, "file", 9); TESTOUTPUT_EQUAL(StringFromFormat("\tAllocation using malloc of size: 10 pointer: %p at file:9\n", (void*) memory01).asCharString()); } TEST(NormalMemoryReportFormatter, freeCreatesAnFreeCall) { formatter.report_free_memory(testResult, defaultMallocAllocator(), memory01, "boo", 6); TESTOUTPUT_EQUAL(StringFromFormat("\tDeallocation using free of pointer: %p at boo:6\n", (void*) memory01).asCharString()); } TEST(NormalMemoryReportFormatter, testStarts) { UtestShell test("groupName", "TestName", "file", 1); formatter.report_test_start(testResult, test); TESTOUTPUT_EQUAL("TEST(groupName, TestName)\n"); } TEST(NormalMemoryReportFormatter, testEnds) { UtestShell test("groupName", "TestName", "file", 1); formatter.report_test_end(testResult, test); TESTOUTPUT_EQUAL("ENDTEST(groupName, TestName)\n"); } TEST(NormalMemoryReportFormatter, testGroupStarts) { UtestShell test("groupName", "TestName", "file", 1); formatter.report_testgroup_start(testResult, test); TESTOUTPUT_EQUAL("------------------------------TEST GROUP(groupName)-----------------------------\n"); }
null
69
cpp
cpputest
MockSupport_cTest.cpp
tests/CppUTestExt/MockSupport_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. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestHarness_c.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTestExt/MockSupport_c.h" #include "MockSupport_cTestCFile.h" #include "CppUTestExt/OrderedTest.h" extern "C" { static void dummy_function_for_mock_c_test() { } static void dummy_function_for_mock_c_test_two() { } } TEST_GROUP(MockSupport_c) { void teardown() CPPUTEST_OVERRIDE { mock_c()->clear(); } }; TEST(MockSupport_c, OrderObserved) { mock_c()->strictOrder(); mock_c()->expectOneCall("foo1"); mock_c()->expectOneCall("foo2"); mock_c()->actualCall("foo1"); mock_c()->actualCall("foo2"); mock_c()->checkExpectations(); } TEST(MockSupport_c, hasReturnValue) { mock_c()->expectOneCall("foo"); CHECK(mock_c()->actualCall("foo")->hasReturnValue() == 0); CHECK(mock_c()->hasReturnValue() == 0); mock_c()->expectOneCall("foo2")->andReturnIntValue(1); CHECK(mock_c()->actualCall("foo2")->hasReturnValue() != 0); CHECK(mock_c()->hasReturnValue() != 0); } TEST(MockSupport_c, expectAndActualOneCall) { mock_c()->expectOneCall("boo"); mock_c()->actualCall("boo"); mock_c()->checkExpectations(); } TEST(MockSupport_c, expectAndActualThreeCalls) { mock_c()->expectNCalls(3, "boo"); mock_c()->actualCall("boo"); mock_c()->actualCall("boo"); mock_c()->actualCall("boo"); mock_c()->checkExpectations(); } TEST(MockSupport_c, expectNoCall) { mock_c()->expectNoCall("foo"); mock_c()->expectOneCall("bar"); mock_c()->actualCall("bar"); mock_c()->checkExpectations(); } TEST(MockSupport_c, expectAndActualParameters) { mock_c()->expectOneCall("boo")->withIntParameters("integer", 1)->withDoubleParameters("double", 1.0)-> withStringParameters("string", "string")->withPointerParameters("pointer", (void*) 1)-> withFunctionPointerParameters("functionPointer", dummy_function_for_mock_c_test); mock_c()->actualCall("boo")->withIntParameters("integer", 1)->withDoubleParameters("double", 1.0)-> withStringParameters("string", "string")->withPointerParameters("pointer", (void*) 1)-> withFunctionPointerParameters("functionPointer", dummy_function_for_mock_c_test); } extern "C"{ static int typeNameIsEqual(const void* object1, const void* object2) { return object1 == object2; } static const char* typeNameValueToString(const void* PUNUSED(object)) { return "valueToString"; } static void typeCopy(void* dst, const void* src) { *(int*) dst = *(const int*) src; } } TEST(MockSupport_c, expectAndActualParametersOnObject) { mock_c()->installComparator("typeName", typeNameIsEqual, typeNameValueToString); mock_c()->expectOneCall("boo")->withParameterOfType("typeName", "name", (const void*) 1); mock_c()->actualCall("boo")->withParameterOfType("typeName", "name", (const void*) 1); mock_c()->checkExpectations(); mock_c()->removeAllComparatorsAndCopiers(); } TEST(MockSupport_c, boolParameter) { mock_c()->expectOneCall("foo")->withBoolParameters("p", 1); mock_c()->actualCall("foo")->withBoolParameters("p", 1); } TEST(MockSupport_c, unsignedIntParameter) { mock_c()->expectOneCall("foo")->withUnsignedIntParameters("p", 1); mock_c()->actualCall("foo")->withUnsignedIntParameters("p", 1); } TEST(MockSupport_c, longIntParameter) { mock_c()->expectOneCall("foo")->withLongIntParameters("p", 1); mock_c()->actualCall("foo")->withLongIntParameters("p", 1); } TEST(MockSupport_c, unsignedLongIntParameter) { mock_c()->expectOneCall("foo")->withUnsignedLongIntParameters("p", 1); mock_c()->actualCall("foo")->withUnsignedLongIntParameters("p", 1); } TEST(MockSupport_c, doubleParameterWithTolerance) { mock_c( )->expectOneCall("foo")->withDoubleParametersAndTolerance("p", 2.0, 0.2); mock_c( )->actualCall("foo")->withDoubleParameters("p", 1.9); } #if CPPUTEST_USE_LONG_LONG TEST(MockSupport_c, longLongIntParameter) { mock_c()->expectOneCall("foo")->withLongLongIntParameters("p", 1); mock_c()->actualCall("foo")->withLongLongIntParameters("p", 1); } TEST(MockSupport_c, unsignedLongLongIntParameter) { mock_c()->expectOneCall("foo")->withUnsignedLongLongIntParameters("p", 1); mock_c()->actualCall("foo")->withUnsignedLongLongIntParameters("p", 1); } #endif TEST(MockSupport_c, memoryBufferParameter) { const unsigned char mem_buffer[] = { 1, 2, 3}; mock_c()->expectOneCall("foo")->withMemoryBufferParameter("out", mem_buffer, sizeof(mem_buffer)); mock_c()->actualCall("foo")->withMemoryBufferParameter("out", mem_buffer, sizeof(mem_buffer)); mock_c()->checkExpectations(); } TEST(MockSupport_c, outputParameters) { int param = 1; const int retval = 2; mock_c()->expectOneCall("foo")->withOutputParameterReturning("out", &retval, sizeof(retval)); mock_c()->actualCall("foo")->withOutputParameter("out", &param); mock_c()->checkExpectations(); LONGS_EQUAL(2, param); LONGS_EQUAL(2, retval); } TEST(MockSupport_c, unmodifiedOutputParameter) { int param = 1; mock_c()->expectOneCall("foo")->withUnmodifiedOutputParameter("out"); mock_c()->actualCall("foo")->withOutputParameter("out", &param); mock_c()->checkExpectations(); LONGS_EQUAL(1, param); } TEST(MockSupport_c, outputParameters_differentType) { long param = 1; const long retval = 2; mock_c()->expectOneCall("foo")->withOutputParameterReturning("out", &retval, sizeof(retval)); mock_c()->actualCall("foo")->withOutputParameter("out", &param); mock_c()->checkExpectations(); LONGS_EQUAL(2, param); LONGS_EQUAL(2, retval); } TEST(MockSupport_c, outputParametersOfType) { int param = 1; const int retval = 2; mock_c()->installCopier("typeName", typeCopy); mock_c()->expectOneCall("foo")->withOutputParameterOfTypeReturning("typeName", "out", &retval); mock_c()->actualCall("foo")->withOutputParameterOfType("typeName", "out", &param); LONGS_EQUAL(2, param); LONGS_EQUAL(2, retval); mock_c()->checkExpectations(); mock_c()->removeAllComparatorsAndCopiers(); } TEST(MockSupport_c, ignoreOtherParameters) { mock_c()->expectOneCall("foo")->withIntParameters("int", 1)->ignoreOtherParameters(); mock_c()->actualCall("foo")->withIntParameters("int", 1)->withDoubleParameters("double", 0.01); mock_c()->checkExpectations(); } TEST(MockSupport_c, returnBoolValue) { int expected_value = 1; mock_c()->expectOneCall("boo")->andReturnBoolValue(expected_value); CHECK_EQUAL(expected_value, mock_c()->actualCall("boo")->boolReturnValue()); CHECK_EQUAL(expected_value, mock_c()->boolReturnValue()); LONGS_EQUAL(MOCKVALUETYPE_BOOL, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnBoolValueOrDefaultShouldIgnoreTheDefault) { int defaultValue = 1; int expectedValue = 0; mock_c()->expectOneCall("foo")->andReturnBoolValue(expectedValue); LONGS_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnBoolValueOrDefault(defaultValue)); LONGS_EQUAL(expectedValue, mock_c()->returnBoolValueOrDefault(defaultValue)); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnBoolValueOrDefaultShouldlUseTheDefaultValue) { int defaultValue = 1; mock_c()->expectOneCall("foo"); LONGS_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnBoolValueOrDefault(defaultValue)); LONGS_EQUAL(defaultValue, mock_c()->returnBoolValueOrDefault(defaultValue)); } TEST(MockSupport_c, returnIntValue) { int expected_value = -10; mock_c()->expectOneCall("boo")->andReturnIntValue(expected_value); LONGS_EQUAL(expected_value, mock_c()->actualCall("boo")->intReturnValue()); LONGS_EQUAL(expected_value, mock_c()->intReturnValue()); LONGS_EQUAL(MOCKVALUETYPE_INTEGER, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnIntValueOrDefaultShouldIgnoreTheDefault) { int defaultValue = -10; int expectedValue = defaultValue - 1; mock_c()->expectOneCall("foo")->andReturnIntValue(expectedValue); LONGS_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnIntValueOrDefault(defaultValue)); LONGS_EQUAL(expectedValue, mock_c()->returnIntValueOrDefault(defaultValue)); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnIntValueOrDefaultShouldlUseTheDefaultValue) { int defaultValue = -10; mock_c()->expectOneCall("foo"); LONGS_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnIntValueOrDefault(defaultValue)); LONGS_EQUAL(defaultValue, mock_c()->returnIntValueOrDefault(defaultValue)); } TEST(MockSupport_c, returnUnsignedIntValue) { unsigned int expected_value = 7; mock_c()->expectOneCall("boo")->andReturnUnsignedIntValue(expected_value); LONGS_EQUAL(expected_value, mock_c()->actualCall("boo")->unsignedIntReturnValue()); LONGS_EQUAL(expected_value, mock_c()->unsignedIntReturnValue()); LONGS_EQUAL(MOCKVALUETYPE_UNSIGNED_INTEGER, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnUnsignedIntValueOrDefaultShouldIgnoreTheDefault) { unsigned int defaultValue = 10; unsigned int expectedValue = defaultValue + 1; mock_c()->expectOneCall("foo")->andReturnUnsignedIntValue(expectedValue); LONGS_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnUnsignedIntValueOrDefault(defaultValue)); LONGS_EQUAL(expectedValue, mock_c()->returnUnsignedIntValueOrDefault(defaultValue)); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnUnsignedIntValueOrDefaultShouldlUseTheDefaultValue) { unsigned int defaultValue = 10; mock_c()->expectOneCall("foo"); LONGS_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnUnsignedIntValueOrDefault(defaultValue)); LONGS_EQUAL(defaultValue, mock_c()->returnUnsignedIntValueOrDefault(defaultValue)); } TEST(MockSupport_c, returnLongIntValue) { long int expected_value = -10L; mock_c()->expectOneCall("boo")->andReturnLongIntValue(expected_value); LONGS_EQUAL(expected_value, mock_c()->actualCall("boo")->longIntReturnValue()); LONGS_EQUAL(expected_value, mock_c()->longIntReturnValue()); LONGS_EQUAL(MOCKVALUETYPE_LONG_INTEGER, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnLongIntValueOrDefaultShouldIgnoreTheDefault) { long int defaultValue = -10L; long int expectedValue = defaultValue - 1L; mock_c()->expectOneCall("foo")->andReturnLongIntValue(expectedValue); LONGS_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnLongIntValueOrDefault(defaultValue)); LONGS_EQUAL(expectedValue, mock_c()->returnLongIntValueOrDefault(defaultValue)); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnLongIntValueOrDefaultShouldlUseTheDefaultValue) { long int defaultValue = -10L; mock_c()->expectOneCall("foo"); LONGS_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnLongIntValueOrDefault(defaultValue)); LONGS_EQUAL(defaultValue, mock_c()->returnLongIntValueOrDefault(defaultValue)); } TEST(MockSupport_c, returnUnsignedLongIntValue) { unsigned long int expected_value = 10; mock_c()->expectOneCall("boo")->andReturnUnsignedLongIntValue(expected_value); LONGS_EQUAL(expected_value, mock_c()->actualCall("boo")->unsignedLongIntReturnValue()); LONGS_EQUAL(expected_value, mock_c()->unsignedLongIntReturnValue()); LONGS_EQUAL(MOCKVALUETYPE_UNSIGNED_LONG_INTEGER, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnUnsignedLongIntValueOrDefaultShouldIgnoreTheDefault) { unsigned long int defaultValue = 10L; unsigned long int expectedValue = defaultValue + 1L; mock_c()->expectOneCall("foo")->andReturnUnsignedLongIntValue(expectedValue); LONGS_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnUnsignedLongIntValueOrDefault(defaultValue)); LONGS_EQUAL(expectedValue, mock_c()->returnUnsignedLongIntValueOrDefault(defaultValue)); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnUnsignedLongIntValueOrDefaultShouldlUseTheDefaultValue) { unsigned long int defaultValue = 10L; mock_c()->expectOneCall("foo"); LONGS_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnUnsignedLongIntValueOrDefault(defaultValue)); LONGS_EQUAL(defaultValue, mock_c()->returnUnsignedLongIntValueOrDefault(defaultValue)); } #if CPPUTEST_USE_LONG_LONG TEST(MockSupport_c, returnLongLongIntValue) { long long int expected_value = -10L; mock_c()->expectOneCall("boo")->andReturnLongLongIntValue(expected_value); LONGLONGS_EQUAL(expected_value, mock_c()->actualCall("boo")->longLongIntReturnValue()); LONGLONGS_EQUAL(expected_value, mock_c()->longLongIntReturnValue()); LONGLONGS_EQUAL(MOCKVALUETYPE_LONG_LONG_INTEGER, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnLongLongIntValueOrDefaultShouldIgnoreTheDefault) { long long int defaultValue = -10L; long long int expectedValue = defaultValue - 1L; mock_c()->expectOneCall("foo")->andReturnLongLongIntValue(expectedValue); LONGLONGS_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnLongLongIntValueOrDefault(defaultValue)); LONGLONGS_EQUAL(expectedValue, mock_c()->returnLongLongIntValueOrDefault(defaultValue)); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnLongLongIntValueOrDefaultShouldlUseTheDefaultValue) { long long int defaultValue = -10L; mock_c()->expectOneCall("foo"); LONGLONGS_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnLongLongIntValueOrDefault(defaultValue)); LONGLONGS_EQUAL(defaultValue, mock_c()->returnLongLongIntValueOrDefault(defaultValue)); } TEST(MockSupport_c, returnUnsignedLongLongIntValue) { unsigned long long int expected_value = 10; mock_c()->expectOneCall("boo")->andReturnUnsignedLongLongIntValue(expected_value); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock_c()->actualCall("boo")->unsignedLongLongIntReturnValue()); UNSIGNED_LONGLONGS_EQUAL(expected_value, mock_c()->unsignedLongLongIntReturnValue()); UNSIGNED_LONGLONGS_EQUAL(MOCKVALUETYPE_UNSIGNED_LONG_LONG_INTEGER, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnUnsignedLongLongIntValueOrDefaultShouldIgnoreTheDefault) { unsigned long long int defaultValue = 10L; unsigned long long int expectedValue = defaultValue + 1L; mock_c()->expectOneCall("foo")->andReturnUnsignedLongLongIntValue(expectedValue); UNSIGNED_LONGLONGS_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnUnsignedLongLongIntValueOrDefault(defaultValue)); UNSIGNED_LONGLONGS_EQUAL(expectedValue, mock_c()->returnUnsignedLongLongIntValueOrDefault(defaultValue)); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnUnsignedLongLongIntValueOrDefaultShouldlUseTheDefaultValue) { unsigned long long int defaultValue = 10L; mock_c()->expectOneCall("foo"); UNSIGNED_LONGLONGS_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnUnsignedLongLongIntValueOrDefault(defaultValue)); UNSIGNED_LONGLONGS_EQUAL(defaultValue, mock_c()->returnUnsignedLongLongIntValueOrDefault(defaultValue)); } #endif TEST(MockSupport_c, returnStringValue) { mock_c()->expectOneCall("boo")->andReturnStringValue("hello world"); STRCMP_EQUAL("hello world", mock_c()->actualCall("boo")->stringReturnValue()); STRCMP_EQUAL("hello world", mock_c()->stringReturnValue()); LONGS_EQUAL(MOCKVALUETYPE_STRING, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnStringValueOrDefaultShouldIgnoreTheDefault) { const char defaultValue[] = "bar"; const char expectedValue[] = "bla"; mock_c()->expectOneCall("foo")->andReturnStringValue(expectedValue); STRCMP_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnStringValueOrDefault(defaultValue)); STRCMP_EQUAL(expectedValue, mock_c()->returnStringValueOrDefault(defaultValue)); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnStringValueOrDefaultShouldlUseTheDefaultValue) { const char defaultValue[] = "bar"; mock_c()->expectOneCall("foo"); STRCMP_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnStringValueOrDefault(defaultValue)); STRCMP_EQUAL(defaultValue, mock_c()->returnStringValueOrDefault(defaultValue)); } TEST(MockSupport_c, returnDoubleValue) { mock_c()->expectOneCall("boo")->andReturnDoubleValue(1.0); DOUBLES_EQUAL(1.0, mock_c()->actualCall("boo")->doubleReturnValue(), 0.005); DOUBLES_EQUAL(1.0, mock_c()->doubleReturnValue(), 0.005); LONGS_EQUAL(MOCKVALUETYPE_DOUBLE, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnDoubleValueOrDefaultShouldIgnoreTheDefault) { double defaultValue = 2.2; double expectedValue = defaultValue + 0.1; mock_c()->expectOneCall("foo")->andReturnDoubleValue(expectedValue); DOUBLES_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnDoubleValueOrDefault(defaultValue), 0.005); DOUBLES_EQUAL(expectedValue, mock_c()->returnDoubleValueOrDefault(defaultValue), 0.005); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnDoubleValueOrDefaultShouldlUseTheDefaultValue) { double defaultValue = 2.2; mock_c()->expectOneCall("foo"); DOUBLES_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnDoubleValueOrDefault(defaultValue), 0.005); DOUBLES_EQUAL(defaultValue, mock_c()->returnDoubleValueOrDefault(defaultValue), 0.005); } TEST(MockSupport_c, returnPointerValue) { mock_c()->expectOneCall("boo")->andReturnPointerValue((void*) 10); POINTERS_EQUAL((void*) 10, mock_c()->actualCall("boo")->pointerReturnValue()); POINTERS_EQUAL((void*) 10, mock_c()->pointerReturnValue()); LONGS_EQUAL(MOCKVALUETYPE_POINTER, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnPointerValueOrDefaultShouldIgnoreTheDefault) { void* defaultValue = (void*) 10; void* expectedValue = (void*) 27; mock_c()->expectOneCall("foo")->andReturnPointerValue(expectedValue); POINTERS_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnPointerValueOrDefault(defaultValue)); POINTERS_EQUAL(expectedValue, mock_c()->returnPointerValueOrDefault(defaultValue)); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnPointerValueOrDefaultShouldlUseTheDefaultValue) { void* defaultValue = (void*) 10; mock_c()->expectOneCall("foo"); POINTERS_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnPointerValueOrDefault(defaultValue)); POINTERS_EQUAL(defaultValue, mock_c()->returnPointerValueOrDefault(defaultValue)); } TEST(MockSupport_c, returnConstPointerValue) { mock_c()->expectOneCall("boo")->andReturnConstPointerValue((const void*) 10); POINTERS_EQUAL((const void*) 10, mock_c()->actualCall("boo")->constPointerReturnValue()); POINTERS_EQUAL((const void*) 10, mock_c()->constPointerReturnValue()); LONGS_EQUAL(MOCKVALUETYPE_CONST_POINTER, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnConstPointerValueOrDefaultShouldIgnoreTheDefault) { const void* defaultValue = (void*) 10; const void* expectedValue = (void*) 27; mock_c()->expectOneCall("foo")->andReturnConstPointerValue(expectedValue); POINTERS_EQUAL(expectedValue, mock_c()->actualCall("foo")->returnConstPointerValueOrDefault(defaultValue)); POINTERS_EQUAL(expectedValue, mock_c()->returnConstPointerValueOrDefault(defaultValue)); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnConstPointerValueOrDefaultShouldlUseTheDefaultValue) { const void* defaultValue = (void*) 10; mock_c()->expectOneCall("foo"); POINTERS_EQUAL(defaultValue, mock_c()->actualCall("foo")->returnConstPointerValueOrDefault(defaultValue)); POINTERS_EQUAL(defaultValue, mock_c()->returnConstPointerValueOrDefault(defaultValue)); } TEST(MockSupport_c, returnFunctionPointerValue) { mock_c()->expectOneCall("boo")->andReturnFunctionPointerValue(dummy_function_for_mock_c_test); FUNCTIONPOINTERS_EQUAL(dummy_function_for_mock_c_test, mock_c()->actualCall("boo")->functionPointerReturnValue()); FUNCTIONPOINTERS_EQUAL(dummy_function_for_mock_c_test, mock_c()->functionPointerReturnValue()); LONGS_EQUAL(MOCKVALUETYPE_FUNCTIONPOINTER, mock_c()->returnValue().type); } TEST(MockSupport_c, whenReturnValueIsGivenReturnFunctionPointerValueOrDefaultShouldIgnoreTheDefault) { mock_c()->expectOneCall("foo")->andReturnFunctionPointerValue(dummy_function_for_mock_c_test); FUNCTIONPOINTERS_EQUAL(dummy_function_for_mock_c_test, mock_c()->actualCall("foo")->returnFunctionPointerValueOrDefault(dummy_function_for_mock_c_test_two)); FUNCTIONPOINTERS_EQUAL(dummy_function_for_mock_c_test, mock_c()->returnFunctionPointerValueOrDefault(dummy_function_for_mock_c_test_two)); } TEST(MockSupport_c, whenNoReturnValueIsGivenReturnFunctionPointerValueOrDefaultShouldlUseTheDefaultValue) { mock_c()->expectOneCall("foo"); FUNCTIONPOINTERS_EQUAL(dummy_function_for_mock_c_test_two, mock_c()->actualCall("foo")->returnFunctionPointerValueOrDefault(dummy_function_for_mock_c_test_two)); FUNCTIONPOINTERS_EQUAL(dummy_function_for_mock_c_test_two, mock_c()->returnFunctionPointerValueOrDefault(dummy_function_for_mock_c_test_two)); } 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, MockSupportSetBoolData) { mock_c()->setBoolData("boolean", 1); CHECK_EQUAL(1, mock_c()->getData("boolean").value.boolValue); } 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, MockSupportSetConstPointerData) { mock_c()->setConstPointerData("constPointer", (const void*) 1); POINTERS_EQUAL((const void*) 1, mock_c()->getData("constPointer").value.constPointerValue); } TEST(MockSupport_c, MockSupportMemoryBufferData) { mock_c()->setDataObject("name", "const unsigned char*", (void *) 0xDEAD); POINTERS_EQUAL(0xDEAD, mock_c()->getData("name").value.memoryBufferValue); LONGS_EQUAL(MOCKVALUETYPE_MEMORYBUFFER, mock_c()->getData("name").type); } TEST(MockSupport_c, MockSupportSetFunctionPointerData) { mock_c()->setFunctionPointerData("functionPointer", dummy_function_for_mock_c_test); FUNCTIONPOINTERS_EQUAL(dummy_function_for_mock_c_test, mock_c()->getData("functionPointer").value.functionPointerValue); } TEST(MockSupport_c, MockSupportSetDataObject) { mock_c()->setDataObject("name", "type", (void*) 1); POINTERS_EQUAL((void*) 1, mock_c()->getData("name").value.objectValue); } TEST(MockSupport_c, MockSupportSetDataConstObject) { mock_c()->setDataConstObject("name", "type", (const void*) 5); POINTERS_EQUAL((void*) 5, mock_c()->getData("name").value.constObjectValue); } TEST(MockSupport_c, WorksInCFile) { all_mock_support_c_calls(); } static bool destructorWasCalled = false; static void failedCallToMockC() { SetBooleanOnDestructorCall setOneDestructor(destructorWasCalled); mock_c()->actualCall("Not a call"); } // LCOV_EXCL_LINE // Silly wrapper because of a test that only fails in Visual C++ due to different // destructor behaviors #ifdef _MSC_VER #define MSC_SWITCHED_TEST(testGroup, testName) IGNORE_TEST(testGroup, testName) #else #define MSC_SWITCHED_TEST(testGroup, testName) TEST(testGroup, testName) #endif MSC_SWITCHED_TEST(MockSupport_c, NoExceptionsAreThrownWhenAMock_cCallFailed) { TestTestingFixture fixture; fixture.setTestFunction(failedCallToMockC); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); // Odd behavior in Visual C++, destructor still gets called here CHECK(!destructorWasCalled); } static bool cpputestHasCrashed; static void crashMethod() { cpputestHasCrashed = true; } TEST_ORDERED(MockSupport_c, shouldCrashOnFailure, 21) { cpputestHasCrashed = false; TestTestingFixture fixture; UtestShell::setCrashMethod(crashMethod); mock_c()->crashOnFailure(true); fixture.setTestFunction(failedCallToMockC); fixture.runAllTests(); CHECK(cpputestHasCrashed); UtestShell::resetCrashMethod(); mock_c()->crashOnFailure(false); } TEST_ORDERED(MockSupport_c, nextTestShouldNotCrashOnFailure, 22) { cpputestHasCrashed = false; TestTestingFixture fixture; UtestShell::setCrashMethod(crashMethod); fixture.setTestFunction(failedCallToMockC); fixture.runAllTests(); CHECK_FALSE(cpputestHasCrashed); UtestShell::resetCrashMethod(); } TEST(MockSupport_c, FailWillNotCrashIfNotEnabled) { cpputestHasCrashed = false; TestTestingFixture fixture; UtestShell::setCrashMethod(crashMethod); fixture.setTestFunction(failedCallToMockC); fixture.runAllTests(); CHECK_FALSE(cpputestHasCrashed); LONGS_EQUAL(1, fixture.getFailureCount()); UtestShell::resetCrashMethod(); } TEST(MockSupport_c, FailWillCrashIfEnabled) { cpputestHasCrashed = false; TestTestingFixture fixture; UtestShell::setCrashOnFail(); UtestShell::setCrashMethod(crashMethod); fixture.setTestFunction(failedCallToMockC); fixture.runAllTests(); CHECK(cpputestHasCrashed); LONGS_EQUAL(1, fixture.getFailureCount()); UtestShell::restoreDefaultTestTerminator(); UtestShell::resetCrashMethod(); } static void failingCallToMockCWithParameterOfType_() { mock_c()->expectOneCall("bar")->withParameterOfType("typeName", "name", (const void*) 1); mock_c()->actualCall("bar")->withParameterOfType("typeName", "name", (const void*) 2); } // LCOV_EXCL_LINE TEST(MockSupport_c, failureWithParameterOfTypeCoversValueToString) { TestTestingFixture fixture; mock_c()->installComparator("typeName", typeNameIsEqual, typeNameValueToString); fixture.setTestFunction(failingCallToMockCWithParameterOfType_); fixture.runAllTests(); fixture.assertPrintContains("typeName name: <valueToString>"); mock_c()->removeAllComparatorsAndCopiers(); } static void callToMockCWithOutputParameterOfType_() { int value1 = 7; const int value2 = 9; mock_c()->expectOneCall("bar")->withOutputParameterOfTypeReturning("intType", "bla", &value2); mock_c()->actualCall("bar")->withOutputParameterOfType("intType", "bla", &value1); LONGS_EQUAL(value1, value2); } TEST(MockSupport_c, successWithOutputParameterOfType) { TestTestingFixture fixture; mock_c()->installCopier("intType", typeCopy); fixture.setTestFunction(callToMockCWithOutputParameterOfType_); fixture.runAllTests(); LONGS_EQUAL(2, fixture.getCheckCount()); LONGS_EQUAL(0, fixture.getFailureCount()); mock_c()->removeAllComparatorsAndCopiers(); } static void failingCallToMockCWithMemoryBuffer_() { unsigned char memBuffer1[] = { 0x12, 0x15, 0xFF }; unsigned char memBuffer2[] = { 0x12, 0x05, 0xFF }; mock_c()->expectOneCall("bar")->withMemoryBufferParameter("name", memBuffer1, sizeof(memBuffer1)); mock_c()->actualCall("bar")->withMemoryBufferParameter("name", memBuffer2, sizeof(memBuffer2)); } // LCOV_EXCL_LINE TEST(MockSupport_c, expectOneMemBufferParameterAndValueFailsDueToContents) { TestTestingFixture fixture; fixture.setTestFunction(failingCallToMockCWithMemoryBuffer_); fixture.runAllTests(); fixture.assertPrintContains("Unexpected parameter value to parameter \"name\" " "to function \"bar\": <Size = 3 | HexContents = 12 05 FF>"); } TEST(MockSupport_c, ignoreOtherCalls) { mock_c()->expectOneCall("foo"); mock_c()->ignoreOtherCalls(); mock_c()->actualCall("foo"); mock_c()->actualCall("bar"); mock_c()->checkExpectations(); }
null
70
cpp
cpputest
PrinterTest.cpp
examples/AllTests/PrinterTest.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 "Printer.h" #include "MockPrinter.h" TEST_GROUP(Printer) { Printer* printer; MockPrinter* mockPrinter; void setup() CPPUTEST_OVERRIDE { mockPrinter = new MockPrinter(); printer = mockPrinter; } void teardown() CPPUTEST_OVERRIDE { delete printer; } }; TEST(Printer, PrintConstCharStar) { printer->Print("hello"); printer->Print("hello\n"); const char* expected = "hellohello\n"; CHECK_EQUAL(expected, mockPrinter->getOutput()); } TEST(Printer, PrintLong) { printer->Print(1234); const char* expected = "1234"; CHECK_EQUAL(expected, mockPrinter->getOutput()); } TEST(Printer, StreamOperators) { *printer << "n=" << 1234; const char* expected = "n=1234"; CHECK_EQUAL(expected, mockPrinter->getOutput()); }
null
71
cpp
cpputest
AllTests.cpp
examples/AllTests/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/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/IEEE754ExceptionsPlugin.h" #include "CppUTestExt/MockSupportPlugin.h" class MyDummyComparator : public MockNamedValueComparator { public: virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { return object1 == object2; } virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { return StringFrom(object); } }; int main(int ac, char** av) { MyDummyComparator dummyComparator; MockSupportPlugin mockPlugin; IEEE754ExceptionsPlugin ieee754Plugin; mockPlugin.installComparator("MyDummyType", dummyComparator); TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin); TestRegistry::getCurrentRegistry()->installPlugin(&ieee754Plugin); return CommandLineTestRunner::RunAllTests(ac, av); } #include "AllTests.h"
null
72
cpp
cpputest
HelloTest.cpp
examples/AllTests/HelloTest.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 "hello.h" #include <stdio.h> #include <stdarg.h> #include "CppUTest/TestHarness.h" static SimpleString* buffer; TEST_GROUP(HelloWorld) { static int output_method(const char* output, ...) { va_list arguments; va_start(arguments, output); *buffer = VStringFromFormat(output, arguments); va_end(arguments); return 1; } void setup() CPPUTEST_OVERRIDE { buffer = new SimpleString(); UT_PTR_SET(PrintFormated, &output_method); } void teardown() CPPUTEST_OVERRIDE { delete buffer; } }; TEST(HelloWorld, PrintOk) { printHelloWorld(); STRCMP_EQUAL("Hello World!\n", buffer->asCharString()); }
null
73
cpp
cpputest
FEDemoTest.cpp
examples/AllTests/FEDemoTest.cpp
null
/* * Copyright (c) 2016, Michael Feathers, James Grenning, Bas Vodde * and Arnd Strube. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" #if CPPUTEST_HAVE_FENV #include "CppUTestExt/IEEE754ExceptionsPlugin.h" /* * To see a demonstration of tests failing as a result of IEEE754ExceptionsPlugin * picking up floating point errors, run the test executable with the -ri option. * */ extern "C" { #include <fenv.h> } #include <limits> TEST_GROUP(FE_Demo) { void setup() CPPUTEST_OVERRIDE { IEEE754ExceptionsPlugin::disableInexact(); } }; IGNORE_TEST(FE_Demo, should_fail_when_FE_DIVBYZERO_is_set) { float f = 1.0f; CHECK((f /= 0.0f) >= std::numeric_limits<float>::infinity()); } IGNORE_TEST(FE_Demo, should_fail_when_FE_UNDERFLOW_is_set) { volatile float f = 0.01f; while (f > 0.0f) f = f * f; CHECK(f == 0.0f); } IGNORE_TEST(FE_Demo, should_fail_when_FE_OVERFLOW_is_set) { volatile float f = 1000.0f; while (f < std::numeric_limits<float>::infinity()) f = f * f; CHECK(f >= std::numeric_limits<float>::infinity()); } IGNORE_TEST(FE_Demo, should_fail_when_FE_INEXACT_is_set) { IEEE754ExceptionsPlugin::enableInexact(); float f = 10.0f; DOUBLES_EQUAL((double)(f / 3.0f), (double)3.333f, (double)0.001f); } TEST(FE_Demo, should_succeed_when_no_flags_are_set) { CHECK(5.0f == 15.0f / 3.0f); } #endif
null
74
cpp
cpputest
EventDispatcherTest.cpp
examples/AllTests/EventDispatcherTest.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. */ #if CPPUTEST_USE_NEW_MACROS #undef realloc #undef new #endif #include "EventDispatcher.h" #if CPPUTEST_USE_NEW_MACROS #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" class ObserverMock : public EventObserver { public: virtual void notify(const Event& event, int timeOutInSeconds) CPPUTEST_OVERRIDE { mock() .actualCall("notify") .onObject(this) .withParameterOfType("Event", "event", (void*)&event) .withParameter("timeOutInSeconds", timeOutInSeconds); } virtual void notifyRegistration(EventObserver* newObserver) CPPUTEST_OVERRIDE { mock().actualCall("notifyRegistration").onObject(this).withParameter("newObserver", newObserver); } }; class EventComparator : public MockNamedValueComparator { public: virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { return ((const Event*)object1)->type == ((const Event*)object2)->type; } virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { return StringFrom(((const Event*)object)->type); } }; TEST_GROUP(EventDispatcher) { Event event; EventDispatcher* dispatcher; ObserverMock observer; ObserverMock observer2; EventComparator eventComparator; void setup() CPPUTEST_OVERRIDE { dispatcher = new EventDispatcher; mock().installComparator("Event", eventComparator); } void teardown() CPPUTEST_OVERRIDE { delete dispatcher; mock().removeAllComparatorsAndCopiers(); } }; TEST(EventDispatcher, EventWithoutRegistrationsResultsIntoNoCalls) { dispatcher->dispatchEvent(event, 10); } TEST(EventDispatcher, EventWithRegistrationForEventResultsIntoCallback) { mock() .expectOneCall("notify") .onObject(&observer) .withParameterOfType("Event", "event", &event) .withParameter("timeOutInSeconds", 10); event.type = IMPORTANT_EVENT; dispatcher->registerObserver(IMPORTANT_EVENT, &observer); dispatcher->dispatchEvent(event, 10); } TEST(EventDispatcher, DifferentEventWithRegistrationDoesNotResultIntoCallback) { event.type = LESS_IMPORTANT_EVENT; dispatcher->registerObserver(IMPORTANT_EVENT, &observer); dispatcher->dispatchEvent(event, 10); } TEST(EventDispatcher, RegisterTwoObserversResultIntoTwoCallsAndARegistrationNotification) { mock() .expectOneCall("notify") .onObject(&observer) .withParameterOfType("Event", "event", &event) .withParameter("timeOutInSeconds", 10); mock() .expectOneCall("notify") .onObject(&observer2) .withParameterOfType("Event", "event", &event) .withParameter("timeOutInSeconds", 10); mock().expectOneCall("notifyRegistration").onObject(&observer).withParameter("newObserver", &observer2); event.type = IMPORTANT_EVENT; dispatcher->registerObserver(IMPORTANT_EVENT, &observer); dispatcher->registerObserver(IMPORTANT_EVENT, &observer2); dispatcher->dispatchEvent(event, 10); }
null
75
cpp
cpputest
MockPrinter.h
examples/AllTests/MockPrinter.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_MockPrinter_H #define D_MockPrinter_H /////////////////////////////////////////////////////////////////////////////// // // MockPrinter.h // // MockPrinter is responsible for providing a test stub for Printer // /////////////////////////////////////////////////////////////////////////////// #include "Printer.h" #include "CppUTest/SimpleString.h" #include <stdlib.h> #include <string> class MockPrinter : public Printer { public: explicit MockPrinter() {} virtual ~MockPrinter() CPPUTEST_DESTRUCTOR_OVERRIDE {} virtual void Print(const char* s) CPPUTEST_OVERRIDE { savedOutput.append(s); } virtual void Print(long int value) CPPUTEST_OVERRIDE { SimpleString buffer; buffer = StringFromFormat("%ld", value); savedOutput.append(buffer.asCharString()); } std::string getOutput() const { return savedOutput; } private: std::string savedOutput; MockPrinter(const MockPrinter&); MockPrinter& operator=(const MockPrinter&); }; #endif // D_MockPrinter_H
null
76
cpp
cpputest
AllTests.h
examples/AllTests/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. */ IMPORT_TEST_GROUP(Printer); IMPORT_TEST_GROUP(CircularBuffer); IMPORT_TEST_GROUP(HelloWorld); IMPORT_TEST_GROUP(EventDispatcher); IMPORT_TEST_GROUP(MockDocumentation);
null
77
cpp
cpputest
CircularBufferTest.cpp
examples/AllTests/CircularBufferTest.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 "MockPrinter.h" #include "CircularBuffer.h" TEST_GROUP(CircularBuffer) { CircularBuffer* buffer; void setup() CPPUTEST_OVERRIDE { buffer = new CircularBuffer(); } void teardown() CPPUTEST_OVERRIDE { delete buffer; } void fillTheQueue(int seed, int howMany) { for (int i = 0; i < howMany; i++) buffer->Put(seed + i); } void removeFromQueue(int howMany) { for (int i = 0; i < howMany; i++) buffer->Get(); } }; TEST(CircularBuffer, EmptyAfterCreation) { CHECK(buffer->IsEmpty()); } TEST(CircularBuffer, NotEmpty) { buffer->Put(10046); CHECK(!buffer->IsEmpty()); } TEST(CircularBuffer, NotEmptyThenEmpty) { buffer->Put(4567); CHECK(!buffer->IsEmpty()); buffer->Get(); CHECK(buffer->IsEmpty()); } TEST(CircularBuffer, GetPutOneValue) { buffer->Put(4567); LONGS_EQUAL(4567, buffer->Get()); } TEST(CircularBuffer, GetPutAFew) { buffer->Put(1); buffer->Put(2); buffer->Put(3); LONGS_EQUAL(1, buffer->Get()); LONGS_EQUAL(2, buffer->Get()); LONGS_EQUAL(3, buffer->Get()); } TEST(CircularBuffer, Capacity) { CircularBuffer b(2); LONGS_EQUAL(2, b.Capacity()); } TEST(CircularBuffer, IsFull) { fillTheQueue(0, buffer->Capacity()); CHECK(buffer->IsFull()); } TEST(CircularBuffer, EmptyToFullToEmpty) { fillTheQueue(100, buffer->Capacity()); CHECK(buffer->IsFull()); removeFromQueue(buffer->Capacity()); CHECK(buffer->IsEmpty()); } TEST(CircularBuffer, WrapAround) { fillTheQueue(100, buffer->Capacity()); CHECK(buffer->IsFull()); LONGS_EQUAL(100, buffer->Get()); CHECK(!buffer->IsFull()); buffer->Put(1000); CHECK(buffer->IsFull()); removeFromQueue(buffer->Capacity() - 1); LONGS_EQUAL(1000, buffer->Get()); CHECK(buffer->IsEmpty()); } TEST(CircularBuffer, PutToFull) { int capacity = buffer->Capacity(); fillTheQueue(900, capacity); buffer->Put(9999); for (int i = 0; i < buffer->Capacity() - 1; i++) LONGS_EQUAL(i + 900 + 1, buffer->Get()); LONGS_EQUAL(9999, buffer->Get()); CHECK(buffer->IsEmpty()); } // Sometime people ask what tests the tests. // Do you know the answer TEST(CircularBuffer, GetFromEmpty) { LONGS_EQUAL(-1, buffer->Get()); CHECK(buffer->IsEmpty()); } /* * the next tests demonstrate using a mock object for * capturing output * */ TEST(CircularBuffer, PrintEmpty) { MockPrinter mock; Printer* p = &mock; buffer->Print(p); STRCMP_EQUAL("Circular buffer content:\n<>\n", mock.getOutput().c_str()); } TEST(CircularBuffer, PrintAfterOnePut) { MockPrinter mock; buffer->Put(1); buffer->Print(&mock); STRCMP_EQUAL("Circular buffer content:\n<1>\n", mock.getOutput().c_str()); } TEST(CircularBuffer, PrintNotYetWrappedOrFull) { MockPrinter mock; buffer->Put(1); buffer->Put(2); buffer->Put(3); buffer->Print(&mock); STRCMP_EQUAL("Circular buffer content:\n<1, 2, 3>\n", mock.getOutput().c_str()); } TEST(CircularBuffer, PrintNotYetWrappedAndIsFull) { MockPrinter mock; fillTheQueue(200, buffer->Capacity()); buffer->Print(&mock); const char* expected = "Circular buffer content:\n" "<200, 201, 202, 203, 204>\n"; STRCMP_EQUAL(expected, mock.getOutput().c_str()); } TEST(CircularBuffer, PrintWrappedAndIsFullOldestToNewest) { MockPrinter mock; fillTheQueue(200, buffer->Capacity()); buffer->Get(); buffer->Put(999); buffer->Print(&mock); const char* expected = "Circular buffer content:\n" "<201, 202, 203, 204, 999>\n"; STRCMP_EQUAL(expected, mock.getOutput().c_str()); } TEST(CircularBuffer, PrintWrappedAndFullOverwriteOldest) { MockPrinter mock; fillTheQueue(200, buffer->Capacity()); buffer->Put(9999); buffer->Print(&mock); const char* expected = "Circular buffer content:\n" "<201, 202, 203, 204, 9999>\n"; STRCMP_EQUAL(expected, mock.getOutput().c_str()); } TEST(CircularBuffer, PrintBoundary) { MockPrinter mock; fillTheQueue(200, buffer->Capacity()); removeFromQueue(buffer->Capacity() - 2); buffer->Put(888); fillTheQueue(300, buffer->Capacity() - 1); buffer->Print(&mock); const char* expected = "Circular buffer content:\n" "<888, 300, 301, 302, 303>\n"; STRCMP_EQUAL(expected, mock.getOutput().c_str()); } TEST(CircularBuffer, FillEmptyThenPrint) { MockPrinter mock; fillTheQueue(200, buffer->Capacity()); removeFromQueue(buffer->Capacity()); buffer->Print(&mock); const char* expected = "Circular buffer content:\n" "<>\n"; STRCMP_EQUAL(expected, mock.getOutput().c_str()); }
null
78
cpp
cpputest
MockDocumentationTest.cpp
examples/AllTests/MockDocumentationTest.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/MockSupport_c.h" TEST_GROUP(FirstTestGroup) { }; TEST(FirstTestGroup, FirsTest) { // FAIL("Fail me!"); } TEST(FirstTestGroup, SecondTest) { // STRCMP_EQUAL("hello", "world"); } TEST_GROUP(MockDocumentation) { }; static void productionCode() { mock().actualCall("productionCode"); } TEST(MockDocumentation, SimpleScenario) { mock().expectOneCall("productionCode"); productionCode(); mock().checkExpectations(); } class ClassFromProductionCode { public: virtual void importantFunction() {} virtual ~ClassFromProductionCode() {} }; class ClassFromProductionCodeMock : public ClassFromProductionCode { public: virtual void importantFunction() CPPUTEST_OVERRIDE { mock().actualCall("importantFunction").onObject(this); } }; TEST(MockDocumentation, SimpleScenarioObject) { ClassFromProductionCode* object = new ClassFromProductionCodeMock; /* create mock instead of real thing */ mock().expectOneCall("importantFunction").onObject(object); object->importantFunction(); mock().checkExpectations(); delete object; } static void parameters_function(int p1, const char* p2) { void* object = (void*)1; mock().actualCall("function").onObject(object).withParameter("p1", p1).withParameter("p2", p2); } TEST(MockDocumentation, parameters) { void* object = (void*)1; mock().expectOneCall("function").onObject(object).withParameter("p1", 2).withParameter("p2", "hah"); parameters_function(2, "hah"); } class MyTypeComparator : public MockNamedValueComparator { public: virtual bool isEqual(const void* object1, const void* object2) CPPUTEST_OVERRIDE { return object1 == object2; } virtual SimpleString valueToString(const void* object) CPPUTEST_OVERRIDE { return StringFrom(object); } }; TEST(MockDocumentation, ObjectParameters) { void* object = (void*)1; MyTypeComparator comparator; mock().installComparator("myType", comparator); mock().expectOneCall("function").withParameterOfType("myType", "parameterName", object); mock().clear(); mock().removeAllComparatorsAndCopiers(); } TEST(MockDocumentation, returnValue) { mock().expectOneCall("function").andReturnValue(10); mock().actualCall("function").returnValue().getIntValue(); int value = mock().returnValue().getIntValue(); LONGS_EQUAL(10, value); } TEST(MockDocumentation, setData) { ClassFromProductionCode object; mock().setData("importantValue", 10); mock().setDataObject("importantObject", "ClassFromProductionCode", &object); ClassFromProductionCode* pobject; int value = mock().getData("importantValue").getIntValue(); pobject = (ClassFromProductionCode*)mock().getData("importantObject").getObjectPointer(); LONGS_EQUAL(10, value); POINTERS_EQUAL(pobject, &object); } static void doSomethingThatWouldOtherwiseBlowUpTheMockingFramework() {} TEST(MockDocumentation, otherMockSupport) { mock().crashOnFailure(); // mock().actualCall("unex"); mock().expectOneCall("foo"); mock().ignoreOtherCalls(); mock().disable(); doSomethingThatWouldOtherwiseBlowUpTheMockingFramework(); mock().enable(); mock().clear(); } TEST(MockDocumentation, scope) { mock("xmlparser").expectOneCall("open"); mock("filesystem").ignoreOtherCalls(); mock("xmlparser").actualCall("open"); } static int equalMethod(const void* object1, const void* object2) { return object1 == object2; } static const char* toStringMethod(const void*) { return "string"; } TEST(MockDocumentation, CInterface) { void* object = (void*)0x1; mock_c()->expectOneCall("foo")->withIntParameters("integer", 10)->andReturnDoubleValue(1.11); double d = mock_c()->actualCall("foo")->withIntParameters("integer", 10)->returnValue().value.doubleValue; DOUBLES_EQUAL(1.11, d, 0.00001); mock_c()->installComparator("type", equalMethod, toStringMethod); mock_scope_c("scope")->expectOneCall("bar")->withParameterOfType("type", "name", object); mock_scope_c("scope")->actualCall("bar")->withParameterOfType("type", "name", object); mock_c()->removeAllComparatorsAndCopiers(); mock_c()->setIntData("important", 10); mock_c()->checkExpectations(); mock_c()->clear(); } TEST_GROUP(FooTestGroup) { void setup() CPPUTEST_OVERRIDE { // Init stuff } void teardown() CPPUTEST_OVERRIDE { // Uninit stuff } }; TEST(FooTestGroup, Foo) { // Test FOO } TEST(FooTestGroup, MoreFoo) { // Test more FOO } TEST_GROUP(BarTestGroup) { void setup() CPPUTEST_OVERRIDE { // Init Bar } }; TEST(BarTestGroup, Bar) { // Test Bar }
null
79
cpp
cpputest
CircularBuffer.cpp
examples/ApplicationLib/CircularBuffer.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 "CircularBuffer.h" #include "Printer.h" #include <stddef.h> CircularBuffer::CircularBuffer(int _capacity) : index(0), outdex(0), capacity(_capacity), empty(true), full(false) { buffer = new int[(size_t)this->capacity]; } CircularBuffer::~CircularBuffer() { delete[] buffer; } bool CircularBuffer::IsEmpty() { return empty; } bool CircularBuffer::IsFull() { return full; } void CircularBuffer::Put(int i) { empty = false; buffer[index] = i; index = Next(index); if (full) outdex = Next(outdex); else if (index == outdex) full = true; } int CircularBuffer::Get() { int result = -1; full = false; if (!empty) { result = buffer[outdex]; outdex = Next(outdex); if (outdex == index) empty = true; } return result; } int CircularBuffer::Capacity() { return capacity; } int CircularBuffer::Next(int i) { if (++i >= capacity) i = 0; return i; } void CircularBuffer::Print(Printer* p) { p->Print("Circular buffer content:\n<"); int printIndex = outdex; int count = index - outdex; if (!empty && (index <= outdex)) count = capacity - (outdex - index); for (int i = 0; i < count; i++) { p->Print(buffer[printIndex]); printIndex = Next(printIndex); if (i + 1 != count) p->Print(", "); } p->Print(">\n"); }
null
80
cpp
cpputest
hello.h
examples/ApplicationLib/hello.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 HELLO_H_ #define HELLO_H_ #ifdef __cplusplus extern "C" { #endif extern void printHelloWorld(void); extern int (*PrintFormated)(const char*, ...); #ifdef __cplusplus } #endif #endif /*HELLO_H_*/
null
81
cpp
cpputest
Printer.h
examples/ApplicationLib/Printer.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_Printer_H #define D_Printer_H /////////////////////////////////////////////////////////////////////////////// // // Printer is responsible for ... // /////////////////////////////////////////////////////////////////////////////// class Printer { public: explicit Printer(); virtual ~Printer(); virtual void Print(const char*); virtual void Print(long int); private: Printer(const Printer&); Printer& operator=(const Printer&); }; Printer& operator<<(Printer&, const char*); Printer& operator<<(Printer&, long int); #endif // D_Printer_H
null
82
cpp
cpputest
ExamplesNewOverrides.h
examples/ApplicationLib/ExamplesNewOverrides.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 <list> #include "CppUTest/MemoryLeakDetectorNewMacros.h"
null
83
cpp
cpputest
EventDispatcher.cpp
examples/ApplicationLib/EventDispatcher.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 "EventDispatcher.h" using namespace std; EventDispatcher::EventDispatcher() {} void EventDispatcher::registerObserver(EventType type, EventObserver* observer) { for (list<pair<EventType, EventObserver*> >::iterator i = observerList_.begin(); i != observerList_.end(); i++) i->second->notifyRegistration(observer); observerList_.push_back(make_pair(type, observer)); } void EventDispatcher::dispatchEvent(const Event& event, int timeoutSeconds) { for (list<pair<EventType, EventObserver*> >::iterator i = observerList_.begin(); i != observerList_.end(); i++) { if (i->first == event.type) i->second->notify(event, timeoutSeconds); } }
null
84
cpp
cpputest
EventDispatcher.h
examples/ApplicationLib/EventDispatcher.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 EVENTDISPATCHER_H #define EVENTDISPATCHER_H #include <list> enum EventType { IMPORTANT_EVENT, LESS_IMPORTANT_EVENT }; class Event { public: EventType type; }; class EventObserver { public: virtual void notify(const Event& event, int timeOutInSeconds) = 0; virtual void notifyRegistration(EventObserver* newObserver) = 0; virtual ~EventObserver() {} }; class EventDispatcher { std::list<std::pair<EventType, EventObserver*> > observerList_; public: EventDispatcher(); void registerObserver(EventType type, EventObserver* observer); void dispatchEvent(const Event& event, int timeoutSeconds); }; #endif
null
85
cpp
cpputest
Printer.cpp
examples/ApplicationLib/Printer.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 "Printer.h" #include <stdio.h> Printer::Printer() {} Printer::~Printer() {} void Printer::Print(const char* s) { for (const char* p = s; *p; p++) putchar(*p); } void Printer::Print(long int n) { printf("%ld", n); } Printer& operator<<(Printer& p, const char* s) { p.Print(s); return p; } Printer& operator<<(Printer& p, long int i) { p.Print(i); return p; }
null
86
cpp
cpputest
CircularBuffer.h
examples/ApplicationLib/CircularBuffer.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_CircularBuffer_H #define D_CircularBuffer_H /////////////////////////////////////////////////////////////////////////////// // // CircularBuffer.h // // CircularBuffer is responsible for ... // /////////////////////////////////////////////////////////////////////////////// class Printer; class CircularBuffer { public: explicit CircularBuffer(int capacity = CAPACITY); virtual ~CircularBuffer(); void Put(int); int Get(); bool IsEmpty(); bool IsFull(); int Capacity(); int Next(int i); void Print(Printer*); private: int index; int outdex; int* buffer; int capacity; enum { CAPACITY = 5 }; bool empty; bool full; CircularBuffer(const CircularBuffer&); CircularBuffer& operator=(const CircularBuffer&); }; #endif // D_CircularBuffer_H
null
87
cpp
cpputest
AllTestsForTarget.cpp
platforms/CCStudio/tests/CppUTest/AllTestsForTarget.cpp
null
/* * Copyright (c) 2013, Michael Feathers, James Grenning, Bas Vodde * and Arnd Strube * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/CommandLineTestRunner.h" int main(int ac, char** av) { /* Specify commandline arguments here as needed */ char* argv[] = { (char*) 0, (char*) "-v", // (char*) "-gSimpleStringBuffer", // (char*) "-ojunit", }; ac = sizeof(argv) / sizeof(char*); /* These checks are here to make sure assertions outside test runs don't crash */ CHECK(true); LONGS_EQUAL(1, 1); return CommandLineTestRunner::RunAllTests(ac, argv); }
null
88
cpp
cpputest
AllTestsForTarget.cpp
platforms/CCStudio/tests/CppUTestExt/AllTestsForTarget.cpp
null
/* * Copyright (c) 2013, Michael Feathers, James Grenning, Bas Vodde * and Arnd Strube * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MemoryReporterPlugin.h" #include "CppUTestExt/MockSupportPlugin.h" int main(int ac, char** av) { /* Specify commandline arguments here as needed */ char* argv[] = { (char*) 0, (char*) "-v", // (char*) "-gSimpleStringBuffer", // (char*) "-ojunit", }; ac = sizeof(argv) / sizeof(char*); MemoryReporterPlugin plugin; MockSupportPlugin mockPlugin; TestRegistry::getCurrentRegistry()->installPlugin(&plugin); TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin); return CommandLineTestRunner::RunAllTests(ac, argv); }
null
89
cpp
cpputest
PlatformSpecificFunctions_c.h
include/CppUTest/PlatformSpecificFunctions_c.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /****************************************************************************** * * PlatformSpecificFunctions_c.H * * Provides an interface for when working with pure C * *******************************************************************************/ #ifndef PLATFORMSPECIFICFUNCTIONS_C_H_ #define PLATFORMSPECIFICFUNCTIONS_C_H_ #ifdef __cplusplus extern "C" { #endif /* Jumping operations. They manage their own jump buffers */ extern int (*PlatformSpecificSetJmp)(void (*function) (void*), void* data); extern void (*PlatformSpecificLongJmp)(void); extern void (*PlatformSpecificRestoreJumpBuffer)(void); /* Time operations */ extern unsigned long (*GetPlatformSpecificTimeInMillis)(void); extern const char* (*GetPlatformSpecificTimeString)(void); /* String operations */ extern int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list); /* Misc */ extern double (*PlatformSpecificFabs)(double d); extern int (*PlatformSpecificIsNan)(double d); extern int (*PlatformSpecificIsInf)(double d); extern int (*PlatformSpecificAtExit)(void(*func)(void)); /* IO operations */ typedef void* PlatformSpecificFile; extern PlatformSpecificFile PlatformSpecificStdOut; extern PlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag); extern void (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file); extern void (*PlatformSpecificFClose)(PlatformSpecificFile file); extern void (*PlatformSpecificFlush)(void); /* Random operations */ extern void (*PlatformSpecificSrand)(unsigned int); extern int (*PlatformSpecificRand)(void); /* Dynamic Memory operations */ extern void* (*PlatformSpecificMalloc)(size_t size); extern void* (*PlatformSpecificRealloc)(void* memory, size_t size); extern void (*PlatformSpecificFree)(void* memory); extern void* (*PlatformSpecificMemCpy)(void* s1, const void* s2, size_t size); extern void* (*PlatformSpecificMemset)(void* mem, int c, size_t size); typedef void* PlatformSpecificMutex; extern PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void); extern void (*PlatformSpecificSrand)(unsigned int); extern int (*PlatformSpecificRand)(void); extern void (*PlatformSpecificMutexLock)(PlatformSpecificMutex mtx); extern void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex mtx); extern void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex mtx); extern void (*PlatformSpecificAbort)(void); #ifdef __cplusplus } #endif #endif /* PLATFORMSPECIFICFUNCTIONS_C_H_ */
null
90
cpp
cpputest
TestPlugin.h
include/CppUTest/TestPlugin.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_TestPlugin_h #define D_TestPlugin_h #include "SimpleString.h" class UtestShell; class TestResult; class TestPlugin { public: TestPlugin(const SimpleString& name); virtual ~TestPlugin(); virtual void preTestAction(UtestShell&, TestResult&) { } virtual void postTestAction(UtestShell&, TestResult&) { } virtual bool parseArguments(int /* ac */, const char *const * /* av */, int /* index */ ) { return false; } virtual void runAllPreTestAction(UtestShell&, TestResult&); virtual void runAllPostTestAction(UtestShell&, TestResult&); virtual bool parseAllArguments(int ac, const char *const *av, int index); virtual bool parseAllArguments(int ac, char** av, int index); virtual TestPlugin* addPlugin(TestPlugin*); virtual TestPlugin* removePluginByName(const SimpleString& name); virtual TestPlugin* getNext(); virtual void disable(); virtual void enable(); virtual bool isEnabled(); const SimpleString& getName(); TestPlugin* getPluginByName(const SimpleString& name); protected: TestPlugin(TestPlugin* next_); private: TestPlugin* next_; SimpleString name_; bool enabled_; }; /////////////////////////////////////////////////////////////////////////////// // // SetPointerPlugin // // This is a very small plugin_ that resets pointers to their original value. // /////////////////////////////////////////////////////////////////////////////// extern void CppUTestStore(void **location); class SetPointerPlugin: public TestPlugin { public: SetPointerPlugin(const SimpleString& name); virtual void postTestAction(UtestShell&, TestResult&) CPPUTEST_OVERRIDE; enum { MAX_SET = 32 }; }; #define UT_PTR_SET(a, b) \ do { \ CppUTestStore((void**)&(a)); \ (a) = b; \ } while (0) ///////////// Null Plugin class NullTestPlugin: public TestPlugin { public: NullTestPlugin(); virtual void runAllPreTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; virtual void runAllPostTestAction(UtestShell& test, TestResult& result) CPPUTEST_OVERRIDE; static NullTestPlugin* instance(); }; #endif
null
91
cpp
cpputest
PlatformSpecificFunctions.h
include/CppUTest/PlatformSpecificFunctions.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PLATFORMSPECIFICFUNCTIONS_H_ #define PLATFORMSPECIFICFUNCTIONS_H_ #include "CppUTest/TestOutput.h" TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment(); class TestPlugin; extern void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result); extern int (*PlatformSpecificFork)(void); extern int (*PlatformSpecificWaitPid)(int pid, int* status, int options); /* Platform specific interface we use in order to minimize dependencies with LibC. * This enables porting to different embedded platforms. * */ #include "CppUTest/PlatformSpecificFunctions_c.h" #endif
null
92
cpp
cpputest
TestResult.h
include/CppUTest/TestResult.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /////////////////////////////////////////////////////////////////////////////// // // A TestResult is a collection of the history of some test runs. Right now // it just collects failures. Really it just prints the failures. // #ifndef D_TestResult_h #define D_TestResult_h class TestFailure; class TestOutput; class UtestShell; class TestResult { public: TestResult(TestOutput&); DEFAULT_COPY_CONSTRUCTOR(TestResult) virtual ~TestResult(); virtual void testsStarted(); virtual void testsEnded(); virtual void currentGroupStarted(UtestShell* test); virtual void currentGroupEnded(UtestShell* test); virtual void currentTestStarted(UtestShell* test); virtual void currentTestEnded(UtestShell* test); virtual void countTest(); virtual void countRun(); virtual void countCheck(); virtual void countFilteredOut(); virtual void countIgnored(); virtual void addFailure(const TestFailure& failure); virtual void print(const char* text); virtual void printVeryVerbose(const char* text); size_t getTestCount() const { return testCount_; } size_t getRunCount() const { return runCount_; } size_t getCheckCount() const { return checkCount_; } size_t getFilteredOutCount() const { return filteredOutCount_; } size_t getIgnoredCount() const { return ignoredCount_; } size_t getFailureCount() const { return failureCount_; } bool isFailure() const { return (getFailureCount() != 0) || (getRunCount() + getIgnoredCount() == 0); } size_t getTotalExecutionTime() const; void setTotalExecutionTime(size_t exTime); size_t getCurrentTestTotalExecutionTime() const; size_t getCurrentGroupTotalExecutionTime() const; private: TestOutput& output_; size_t testCount_; size_t runCount_; size_t checkCount_; size_t failureCount_; size_t filteredOutCount_; size_t ignoredCount_; size_t totalExecutionTime_; size_t timeStarted_; size_t currentTestTimeStarted_; size_t currentTestTotalExecutionTime_; size_t currentGroupTimeStarted_; size_t currentGroupTotalExecutionTime_; }; #endif
null
93
cpp
cpputest
SimpleMutex.h
include/CppUTest/SimpleMutex.h
null
/* * Copyright (c) 2014, Michael Feathers, James Grenning, Bas Vodde and Chen YewMing * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_SimpleMutex_h #define D_SimpleMutex_h #include "CppUTest/PlatformSpecificFunctions.h" class SimpleMutex { public: SimpleMutex(void); ~SimpleMutex(void); void Lock(void); void Unlock(void); private: PlatformSpecificMutex psMtx; }; class ScopedMutexLock { public: ScopedMutexLock(SimpleMutex *); ~ScopedMutexLock(void); private: SimpleMutex * mutex; }; #endif
null
94
cpp
cpputest
CommandLineArguments.h
include/CppUTest/CommandLineArguments.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_CommandLineArguments_H #define D_CommandLineArguments_H #include "SimpleString.h" #include "TestOutput.h" #include "TestFilter.h" class TestPlugin; class CommandLineArguments { public: explicit CommandLineArguments(int ac, const char *const *av); virtual ~CommandLineArguments(); bool parse(TestPlugin* plugin); bool needHelp() const; bool isVerbose() const; bool isVeryVerbose() const; bool isColor() const; bool isListingTestGroupNames() const; bool isListingTestGroupAndCaseNames() const; bool isListingTestLocations() const; bool isRunIgnored() const; size_t getRepeatCount() const; bool isShuffling() const; bool isReversing() const; bool isCrashingOnFail() const; bool isRethrowingExceptions() const; size_t getShuffleSeed() const; const TestFilter* getGroupFilters() const; const TestFilter* getNameFilters() const; bool isJUnitOutput() const; bool isEclipseOutput() const; bool isTeamCityOutput() const; bool runTestsInSeperateProcess() const; const SimpleString& getPackageName() const; const char* usage() const; const char* help() const; private: enum OutputType { OUTPUT_ECLIPSE, OUTPUT_JUNIT, OUTPUT_TEAMCITY }; int ac_; const char *const *av_; bool needHelp_; bool verbose_; bool veryVerbose_; bool color_; bool runTestsAsSeperateProcess_; bool listTestGroupNames_; bool listTestGroupAndCaseNames_; bool listTestLocations_; bool runIgnored_; bool reversing_; bool crashOnFail_; bool rethrowExceptions_; bool shuffling_; bool shufflingPreSeeded_; size_t repeat_; size_t shuffleSeed_; TestFilter* groupFilters_; TestFilter* nameFilters_; OutputType outputType_; SimpleString packageName_; SimpleString getParameterField(int ac, const char *const *av, int& i, const SimpleString& parameterName); void setRepeatCount(int ac, const char *const *av, int& index); bool setShuffle(int ac, const char *const *av, int& index); void addGroupFilter(int ac, const char *const *av, int& index); bool addGroupDotNameFilter(int ac, const char *const *av, int& index, const SimpleString& parameterName, bool strict, bool exclude); void addStrictGroupFilter(int ac, const char *const *av, int& index); void addExcludeGroupFilter(int ac, const char *const *av, int& index); void addExcludeStrictGroupFilter(int ac, const char *const *av, int& index); void addNameFilter(int ac, const char *const *av, int& index); void addStrictNameFilter(int ac, const char *const *av, int& index); void addExcludeNameFilter(int ac, const char *const *av, int& index); void addExcludeStrictNameFilter(int ac, const char *const *av, int& index); void addTestToRunBasedOnVerboseOutput(int ac, const char *const *av, int& index, const char* parameterName); bool setOutputType(int ac, const char *const *av, int& index); void setPackageName(int ac, const char *const *av, int& index); CommandLineArguments(const CommandLineArguments&); CommandLineArguments& operator=(const CommandLineArguments&); }; #endif
null
95
cpp
cpputest
TestHarness.h
include/CppUTest/TestHarness.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_TestHarness_h #define D_TestHarness_h #include "CppUTestConfig.h" /* original value was 9973 which works well with large programs. Now set to smaller since it takes * a lot of memory in embedded apps. Change it if you experience the memory leak detector to be slow. */ #define MEMORY_LEAK_HASH_TABLE_SIZE 73 #include "Utest.h" #include "UtestMacros.h" #include "SimpleString.h" #include "TestResult.h" #include "TestFailure.h" #include "TestPlugin.h" #include "MemoryLeakWarningPlugin.h" #endif
null
96
cpp
cpputest
JUnitTestOutput.h
include/CppUTest/JUnitTestOutput.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_JUnitTestOutput_h #define D_JUnitTestOutput_h #include "TestOutput.h" #include "SimpleString.h" struct JUnitTestOutputImpl; struct JUnitTestCaseResultNode; class JUnitTestOutput: public TestOutput { public: JUnitTestOutput(); virtual ~JUnitTestOutput() CPPUTEST_DESTRUCTOR_OVERRIDE; virtual void printTestsStarted() CPPUTEST_OVERRIDE; virtual void printTestsEnded(const TestResult& result) CPPUTEST_OVERRIDE; virtual void printCurrentTestStarted(const UtestShell& test) CPPUTEST_OVERRIDE; virtual void printCurrentTestEnded(const TestResult& res) CPPUTEST_OVERRIDE; virtual void printCurrentGroupStarted(const UtestShell& test) CPPUTEST_OVERRIDE; virtual void printCurrentGroupEnded(const TestResult& res) CPPUTEST_OVERRIDE; virtual void printBuffer(const char*) CPPUTEST_OVERRIDE; virtual void print(const char*) CPPUTEST_OVERRIDE; virtual void print(long) CPPUTEST_OVERRIDE; virtual void print(size_t) CPPUTEST_OVERRIDE; virtual void printFailure(const TestFailure& failure) CPPUTEST_OVERRIDE; virtual void flush() CPPUTEST_OVERRIDE; virtual SimpleString createFileName(const SimpleString& group); void setPackageName(const SimpleString &package); protected: JUnitTestOutputImpl* impl_; void resetTestGroupResult(); virtual void openFileForWrite(const SimpleString& fileName); virtual void writeTestGroupToFile(); virtual void writeToFile(const SimpleString& buffer); virtual void closeFile(); virtual void writeXmlHeader(); virtual void writeTestSuiteSummary(); virtual void writeProperties(); virtual void writeTestCases(); virtual SimpleString encodeXmlText(const SimpleString& textbody); virtual SimpleString encodeFileName(const SimpleString& fileName); virtual void writeFailure(JUnitTestCaseResultNode* node); virtual void writeFileEnding(); }; #endif
null
97
cpp
cpputest
TestTestingFixture.h
include/CppUTest/TestTestingFixture.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_TestTestingFixture_H #define D_TestTestingFixture_H #include "TestRegistry.h" #include "TestOutput.h" class TestTestingFixture { public: TestTestingFixture(); virtual ~TestTestingFixture(); void flushOutputAndResetResult(); void addTest(UtestShell * test); void installPlugin(TestPlugin* plugin); void setTestFunction(void(*testFunction)()); void setTestFunction(ExecFunction* testFunction); void setSetup(void(*setupFunction)()); void setTeardown(void(*teardownFunction)()); void setOutputVerbose(); void setRunTestsInSeperateProcess(); void runTestWithMethod(void(*method)()); void runAllTests(); size_t getFailureCount(); size_t getCheckCount(); size_t getIgnoreCount(); size_t getRunCount(); size_t getTestCount(); const SimpleString& getOutput(); TestRegistry* getRegistry(); bool hasTestFailed(); void assertPrintContains(const SimpleString& contains); void assertPrintContainsNot(const SimpleString& contains); void checkTestFailsWithProperTestLocation(const char* text, const char* file, size_t line); static void lineExecutedAfterCheck(); private: void clearExecFunction(); static bool lineOfCodeExecutedAfterCheck; TestRegistry* registry_; ExecFunctionTestShell* genTest_; bool ownsExecFunction_; StringBufferTestOutput* output_; TestResult * result_; }; class SetBooleanOnDestructorCall { bool& booleanToSet_; public: SetBooleanOnDestructorCall(bool& booleanToSet) : booleanToSet_(booleanToSet) { } virtual ~SetBooleanOnDestructorCall() { booleanToSet_ = true; } }; #endif
null
98
cpp
cpputest
TestFailure.h
include/CppUTest/TestFailure.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /////////////////////////////////////////////////////////////////////////////// // // Failure is a class which holds information for a specific // test failure. It can be overriden for more complex failure messages // /////////////////////////////////////////////////////////////////////////////// #ifndef D_TestFailure_H #define D_TestFailure_H #include "SimpleString.h" #if CPPUTEST_USE_STD_CPP_LIB #include <stdexcept> #endif class UtestShell; class TestOutput; class TestFailure { public: TestFailure(UtestShell*, const char* fileName, size_t lineNumber, const SimpleString& theMessage); TestFailure(UtestShell*, const SimpleString& theMessage); TestFailure(UtestShell*, const char* fileName, size_t lineNumber); TestFailure(const TestFailure&); virtual ~TestFailure(); virtual SimpleString getFileName() const; virtual SimpleString getTestName() const; virtual SimpleString getTestNameOnly() const; virtual size_t getFailureLineNumber() const; virtual SimpleString getMessage() const; virtual SimpleString getTestFileName() const; virtual size_t getTestLineNumber() const; bool isOutsideTestFile() const; bool isInHelperFunction() const; protected: SimpleString createButWasString(const SimpleString& expected, const SimpleString& actual); SimpleString createDifferenceAtPosString(const SimpleString& actual, size_t offset, size_t reportedPosition); SimpleString createUserText(const SimpleString& text); SimpleString testName_; SimpleString testNameOnly_; SimpleString fileName_; size_t lineNumber_; SimpleString testFileName_; size_t testLineNumber_; SimpleString message_; TestFailure& operator=(const TestFailure&); }; class EqualsFailure: public TestFailure { public: EqualsFailure(UtestShell*, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text); EqualsFailure(UtestShell*, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); }; class DoublesEqualFailure: public TestFailure { public: DoublesEqualFailure(UtestShell*, const char* fileName, size_t lineNumber, double expected, double actual, double threshold, const SimpleString& text); }; class CheckEqualFailure : public TestFailure { public: CheckEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); }; class ComparisonFailure : public TestFailure { public: ComparisonFailure(UtestShell* test, const char *fileName, size_t lineNumber, const SimpleString& checkString, const SimpleString& comparisonString, const SimpleString& text); }; class ContainsFailure: public TestFailure { public: ContainsFailure(UtestShell*, const char* fileName, size_t lineNumber, const SimpleString& expected, const SimpleString& actual, const SimpleString& text); }; class CheckFailure : public TestFailure { public: CheckFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& checkString, const SimpleString& conditionString, const SimpleString& textString = ""); }; class FailFailure : public TestFailure { public: FailFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& message); }; class LongsEqualFailure : public TestFailure { public: LongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, long expected, long actual, const SimpleString& text); }; class UnsignedLongsEqualFailure : public TestFailure { public: UnsignedLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, unsigned long expected, unsigned long actual, const SimpleString& text); }; class LongLongsEqualFailure : public TestFailure { public: LongLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, cpputest_longlong expected, cpputest_longlong actual, const SimpleString& text); }; class UnsignedLongLongsEqualFailure : public TestFailure { public: UnsignedLongLongsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, cpputest_ulonglong expected, cpputest_ulonglong actual, const SimpleString& text); }; class SignedBytesEqualFailure : public TestFailure { public: SignedBytesEqualFailure (UtestShell* test, const char* fileName, size_t lineNumber, signed char expected, signed char actual, const SimpleString& text); }; class StringEqualFailure : public TestFailure { public: StringEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text); }; class StringEqualNoCaseFailure : public TestFailure { public: StringEqualNoCaseFailure(UtestShell* test, const char* fileName, size_t lineNumber, const char* expected, const char* actual, const SimpleString& text); }; class BinaryEqualFailure : public TestFailure { public: BinaryEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, const unsigned char* expected, const unsigned char* actual, size_t size, const SimpleString& text); }; class BitsEqualFailure : public TestFailure { public: BitsEqualFailure(UtestShell* test, const char* fileName, size_t lineNumber, unsigned long expected, unsigned long actual, unsigned long mask, size_t byteCount, const SimpleString& text); }; class FeatureUnsupportedFailure : public TestFailure { public: FeatureUnsupportedFailure(UtestShell* test, const char* fileName, size_t lineNumber, const SimpleString& featureName, const SimpleString& text); }; #if CPPUTEST_HAVE_EXCEPTIONS class UnexpectedExceptionFailure : public TestFailure { public: UnexpectedExceptionFailure(UtestShell* test); #if CPPUTEST_USE_STD_CPP_LIB UnexpectedExceptionFailure(UtestShell* test, const std::exception &e); #endif }; #endif #endif
null
99
cpp
cpputest
CommandLineTestRunner.h
include/CppUTest/CommandLineTestRunner.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_CommandLineTestRunner_H #define D_CommandLineTestRunner_H #include "TestHarness.h" #include "TestOutput.h" #include "CommandLineArguments.h" #include "TestFilter.h" class TestRegistry; #define DEF_PLUGIN_MEM_LEAK "MemoryLeakPlugin" #define DEF_PLUGIN_SET_POINTER "SetPointerPlugin" class CommandLineTestRunner { public: static int RunAllTests(int ac, const char *const *av); static int RunAllTests(int ac, char** av); CommandLineTestRunner(int ac, const char *const *av, TestRegistry* registry); virtual ~CommandLineTestRunner(); int runAllTestsMain(); protected: virtual TestOutput* createTeamCityOutput(); virtual TestOutput* createJUnitOutput(const SimpleString& packageName); virtual TestOutput* createConsoleOutput(); virtual TestOutput* createCompositeOutput(TestOutput* outputOne, TestOutput* outputTwo); TestOutput* output_; private: CommandLineArguments* arguments_; TestRegistry* registry_; bool parseArguments(TestPlugin*); int runAllTests(); void initializeTestRun(); }; #endif
null
100
cpp
cpputest
MemoryLeakDetectorMallocMacros.h
include/CppUTest/MemoryLeakDetectorMallocMacros.h
null
/* * This file can be used to get extra debugging information about memory leaks in your production code. * It defines a preprocessor macro for malloc. This will pass additional information to the * malloc and this will give the line/file information of the memory leaks in your code. * * You can use this by including this file to all your production code. When using gcc, you can use * the -include file to do this for you. * */ #include "CppUTestConfig.h" #if CPPUTEST_USE_MEM_LEAK_DETECTION /* This prevents the declaration from done twice and makes sure the file only #defines malloc, so it can be included anywhere */ #ifndef CPPUTEST_USE_MALLOC_MACROS #ifdef __cplusplus extern "C" { #endif extern void* cpputest_malloc_location(size_t size, const char* file, size_t line); extern void* cpputest_calloc_location(size_t count, size_t size, const char* file, size_t line); extern void* cpputest_realloc_location(void *, size_t, const char* file, size_t line); extern void cpputest_free_location(void* buffer, const char* file, size_t line); #ifdef __cplusplus } #endif extern void crash_on_allocation_number(unsigned number); #define malloc(a) cpputest_malloc_location(a, __FILE__, __LINE__) #define calloc(a, b) cpputest_calloc_location(a, b, __FILE__, __LINE__) #define realloc(a, b) cpputest_realloc_location(a, b, __FILE__, __LINE__) #define free(a) cpputest_free_location(a, __FILE__, __LINE__) #define CPPUTEST_USE_MALLOC_MACROS 1 #endif /* CPPUTEST_USE_MALLOC_MACROS */ /* This prevents strdup macros to get defined, unless it has been enabled by the user or generated config */ #ifdef CPPUTEST_HAVE_STRDUP /* This prevents the declaration from done twice and makes sure the file only #defines strdup, so it can be included anywhere */ #ifndef CPPUTEST_USE_STRDUP_MACROS #ifdef __cplusplus extern "C" { #endif extern char* cpputest_strdup_location(const char* str, const char* file, size_t line); extern char* cpputest_strndup_location(const char* str, size_t n, const char* file, size_t line); #ifdef __cplusplus } #endif #define strdup(str) cpputest_strdup_location(str, __FILE__, __LINE__) #define strndup(str, n) cpputest_strndup_location(str, n, __FILE__, __LINE__) #define CPPUTEST_USE_STRDUP_MACROS 1 #endif /* CPPUTEST_USE_STRDUP_MACROS */ #endif /* CPPUTEST_HAVE_STRDUP */ #endif /* CPPUTEST_USE_MEM_LEAK_DETECTION */
null