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
README.md exists but content is empty.
Downloads last month
39