ID
int64
0
2.65k
Language
stringclasses
1 value
Repository Name
stringclasses
21 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
10
111
File Path for Unit Test
stringlengths
16
116
Code
stringlengths
66
1.91M
Unit Test - (Ground Truth)
stringlengths
40
32.1k
248
cpp
cmake-cpputest
LedDriverTest.cpp
tests/LedDriver/LedDriverTest.cpp
null
/*** * Excerpted from "Test-Driven Development for Embedded C", * published by The Pragmatic Bookshelf. * Copyrights apply to this code. It may not be used to create training material, * courses, books, articles, and the like. Contact us if you are in doubt. * We make no guarantees that this code is fit for any purpose. * Visit http://www.pragmaticprogrammer.com/titles/jgade for more book information. ***/ /*- ------------------------------------------------------------------ -*/ /*- Copyright (c) James W. Grenning -- All Rights Reserved -*/ /*- For use by owners of Test-Driven Development for Embedded C, -*/ /*- and attendees of Renaissance Software Consulting, Co. training -*/ /*- classes. -*/ /*- -*/ /*- Available at http://pragprog.com/titles/jgade/ -*/ /*- ISBN 1-934356-62-X, ISBN13 978-1-934356-62-3 -*/ /*- -*/ /*- Authorized users may use this source code in your own -*/ /*- projects, however the source code may not be used to -*/ /*- create training material, courses, books, articles, and -*/ /*- the like. We make no guarantees that this source code is -*/ /*- fit for any purpose. -*/ /*- -*/ /*- www.renaissancesoftware.net [email protected] -*/ /*- ------------------------------------------------------------------ -*/ #include "CppUTest/TestHarness.h" extern "C" { #include "LedDriver.h" #include "RuntimeErrorStub.h" } TEST_GROUP(LedDriver) { uint16_t virtualLeds; void setup() { virtualLeds = 0; LedDriver_Create(&virtualLeds); } void teardown() { LedDriver_Destroy(); } }; TEST(LedDriver, LedsAreOffAfterCreate) { virtualLeds = 0xffff; LedDriver_Create(&virtualLeds); LONGS_EQUAL(0, virtualLeds); } TEST(LedDriver, TurnOnLedOne) { LedDriver_TurnOn(1); LONGS_EQUAL(1, virtualLeds); } TEST(LedDriver, TurnOffLedOne) { LedDriver_TurnOn(1); LedDriver_TurnOff(1); LONGS_EQUAL(0, virtualLeds); } TEST(LedDriver, TurnOnMultipleLeds) { LedDriver_TurnOn(9); LedDriver_TurnOn(8); LONGS_EQUAL(0x180, virtualLeds); } TEST(LedDriver, TurnOffAnyLed) { LedDriver_TurnAllOn(); LedDriver_TurnOff(8); LONGS_EQUAL(0xff7f, virtualLeds); } TEST(LedDriver, LedMemoryIsNotReadable) { virtualLeds = 0xffff; LedDriver_TurnOn(8); LONGS_EQUAL(0x80, virtualLeds); } TEST(LedDriver, UpperAndLowerBounds) { LedDriver_TurnOn(1); LedDriver_TurnOn(16); LONGS_EQUAL(0x8001, virtualLeds); } TEST(LedDriver, OutOfBoundsTurnOnDoesNoHarm) { LedDriver_TurnOn(-1); LedDriver_TurnOn(0); LedDriver_TurnOn(17); LedDriver_TurnOn(3141); LONGS_EQUAL(0, virtualLeds); } TEST(LedDriver, OutOfBoundsTurnOffDoesNoHarm) { LedDriver_TurnAllOn(); LedDriver_TurnOff(-1); LedDriver_TurnOff(0); LedDriver_TurnOff(17); LedDriver_TurnOff(3141); LONGS_EQUAL(0xffff, virtualLeds); } IGNORE_TEST(LedDriver, OutOfBoundsToDo) { // demo shows how to IGNORE a test } TEST(LedDriver, OutOfBoundsProducesRuntimeError) { LedDriver_TurnOn(-1); STRCMP_EQUAL("LED Driver: out-of-bounds LED", RuntimeErrorStub_GetLastError()); } TEST(LedDriver, IsOn) { CHECK_EQUAL(FALSE, LedDriver_IsOn(1)); LedDriver_TurnOn(1); CHECK_EQUAL(TRUE, LedDriver_IsOn(1)); } TEST(LedDriver, IsOff) { CHECK_EQUAL(TRUE, LedDriver_IsOff(12)); LedDriver_TurnOn(12); CHECK_EQUAL(FALSE, LedDriver_IsOff(12)); } TEST(LedDriver, OutOfBoundsLedsAreAlwaysOff) { CHECK_EQUAL(TRUE, LedDriver_IsOff(0)); CHECK_EQUAL(TRUE, LedDriver_IsOff(17)); CHECK_EQUAL(FALSE, LedDriver_IsOn(0)); CHECK_EQUAL(FALSE, LedDriver_IsOn(17)); } TEST(LedDriver, AllOn) { LedDriver_TurnAllOn(); LONGS_EQUAL(0xffff, virtualLeds); } TEST(LedDriver, AllOff) { LedDriver_TurnAllOn(); LedDriver_TurnAllOff(); LONGS_EQUAL(0, virtualLeds); }
null
249
cpp
firmware_testing
common.h
code/src/include/common.h
null
#ifndef _COMMON_H_ #define _COMMON_H_ #include <inttypes.h> uint8_t calculator(char op, uint8_t val1, uint8_t val2); /* I2C Hardware functions and slave registers */ #define I2C_SLAVE_ADDRESS 0x30 /* I2C slave address */ #define I2C_REG1 0x0A /* Register 1 offset */ #define I2C_REG2 0x0B /* Register 2 offset */ #define I2C_REG3 0x0C /* Register 3 offset */ #define I2C_START_DEV 0x01 /* Slave init value */ #define DEVICE_READY 0x10 /* Device ready */ uint8_t i2c_read(uint8_t address, uint8_t reg_addr); uint8_t i2c_write(uint8_t address, uint8_t reg_addr, uint8_t value); /* Other Examples */ uint8_t mem_leak_function(void); void ISR(void); void wait_for_ISR_func(void); #ifdef TEST_MAIN /** * These functions are only used in the CppUTest framework so that we * can to test them. */ void init_device(void); uint32_t test_main(void); #endif #endif
null
250
cpp
firmware_testing
main.cpp
code/tests/main.cpp
null
/** * This file is the main test file used by the CppUTest framework. */ #include "CppUTest/CommandLineTestRunner.h" int main(int ac, char** av) { return CommandLineTestRunner::RunAllTests(ac, av); }
null
251
cpp
firmware_testing
t_other.cpp
code/tests/t_other.cpp
null
/** * This file has all unit tests for all functions in src/other.c */ #include "CppUTest/TestHarness.h" #include <thread> extern "C" { #include <unistd.h> #include "common.h" } extern uint8_t brick_code; TEST_GROUP(t_other) { /* Stuff to do before each test */ void setup() { /* Restore original state */ brick_code = 1; } /* Stuff to do after each test */ void teardown(){} }; /** * Test function that is leaking memory. * Change memory leak definition CPPUTEST_USE_MEM_LEAK_DETECTION=N to * CPPUTEST_USE_MEM_LEAK_DETECTION=Y in the MakefileCppUTest.mk file. * Then Run: make test */ TEST(t_other, mem_leak_example) { uint8_t ret = mem_leak_function(); CHECK_EQUAL(1, ret); } /* Test example calling an ISR */ TEST(t_other, _ISR_) { /* Check init conditions */ CHECK_EQUAL(1, brick_code); ISR(); CHECK_EQUAL(0, brick_code); } /** * Thread that calls ISR function after some microseconds. */ void call_ISR(uint32_t usec) { usleep(usec); ISR(); } /** * This test example shows how to test specific function that depends * on a ISR to happen in order to continue it's execution. */ TEST(t_other, wait_for_ISR_func) { /* Call ISR after 10 usec */ std::thread first (call_ISR, 10); wait_for_ISR_func(); CHECK_EQUAL(0, brick_code); first.join(); }
null
252
cpp
firmware_testing
t_math.cpp
code/tests/t_math.cpp
null
/** * This file has all unit tests for all functions in src/math.c */ #include "CppUTest/TestHarness.h" extern "C" { #include "common.h" } TEST_GROUP(t_math) {}; /* Test covers addition case */ TEST(t_math, calc_plus) { uint8_t ret = calculator('+', 2, 8); CHECK_EQUAL(10, ret); } /* Test covers subtraction case */ TEST(t_math, calc_minus) { uint8_t ret = calculator('-', 5, 5); CHECK_EQUAL(0, ret); } /* Tests covers default case */ TEST(t_math, calc_default_mul) { uint8_t ret = calculator('*', 1, 5); CHECK_EQUAL(0, ret); } TEST(t_math, calc_default_div) { uint8_t ret = calculator('/', 1, 5); CHECK_EQUAL(0, ret); } /* Test covers integer overflow case for addition operations */ TEST(t_math, calc_ret_overflow_add) { uint8_t ret = calculator('+', 200, 56); CHECK_EQUAL(0, ret); ret = calculator('+', 200, 57); CHECK_EQUAL(1, ret); } /* Test covers integer overflow case for subtraction operations */ TEST(t_math, calc_ret_overflow_minus) { uint8_t ret = calculator('-', 0, 1); CHECK_EQUAL(255, ret); }
null
253
cpp
firmware_testing
t_main.cpp
code/tests/t_main.cpp
null
/** * This file has all unit tests for all functions in src/main.c */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" extern "C" { #include "common.h" } TEST_GROUP(t_main) { /* Stuff to do before each test */ void setup() { } /* Stuff to do after each test */ void teardown() { mock().checkExpectations(); /* Check mock expectations */ mock().clear(); /* Delete metadata */ } }; /* Test checks correct call of init_device */ TEST(t_main, init_device_call) { mock().expectOneCall("i2c_write").withParameter("address", I2C_SLAVE_ADDRESS) .withParameter("reg_addr", I2C_REG1) .withParameter("value", I2C_START_DEV) .andReturnValue(0); init_device(); } /** * Test reconfiguration case, when device does not respond to * first i2c_read call. */ TEST(t_main, check_reconfigure_behaviour) { /** * Expect two i2c_write calls with the same parameters: * - One is done at the beggining of main function by the init_device(); * - Another is done in the else condition also by init_device(); */ mock().expectNCalls(2, "i2c_write") .withParameter("address", I2C_SLAVE_ADDRESS) .withParameter("reg_addr", I2C_REG1) .withParameter("value", I2C_START_DEV) .andReturnValue(0); /* Expect one i2c_read call and return 0 */ mock().expectOneCall("i2c_read") .withParameter("address", I2C_SLAVE_ADDRESS) .withParameter("reg_addr", I2C_REG2) .andReturnValue(0); /* Will force firmware to enter else condition */ /* Run main firmware function */ uint32_t ret = test_main(); CHECK_EQUAL(0, ret); } /** * Test device behaviour when it's ready to be read by the firmware. */ TEST(t_main, check_device_ready) { /* Expect one i2w_write call. Ignore parameters */ mock().expectOneCall("i2c_write") .ignoreOtherParameters() .andReturnValue(0); /* Expect i2c_read call and return DEVICE_READYE */ mock().expectOneCall("i2c_read") .withParameter("address", I2C_SLAVE_ADDRESS) .withParameter("reg_addr", I2C_REG2) .andReturnValue(DEVICE_READY); /* Expect second i2c_read call with reg_addr of I2C_REG3 */ mock().expectOneCall("i2c_read") .withParameter("address", I2C_SLAVE_ADDRESS) .withParameter("reg_addr", I2C_REG3) .andReturnValue(0); /* Run main firmware function */ uint32_t ret = test_main(); CHECK_EQUAL(0, ret); }
null
254
cpp
firmware_testing
i2c_mock.cpp
code/tests/mocks/i2c_mock.cpp
null
/** * This file contains mock functions of src/hw/i2c.c file. Mocking allows us to * use these functions in the test framework to test firmware with hardware * dependencies and define which execution path we want to take. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" extern "C" { #include "common.h" } /** * I2c read mock function */ uint8_t i2c_read(uint8_t address, uint8_t reg_addr) { return (uint8_t) mock().actualCall("i2c_read") .withParameter("address", address) .withParameter("reg_addr", reg_addr) .returnUnsignedIntValueOrDefault(0); } /** * I2c read write function */ uint8_t i2c_write(uint8_t address, uint8_t reg_addr, uint8_t value) { return (uint8_t) mock().actualCall("i2c_write") .withParameter("address", address) .withParameter("reg_addr", reg_addr) .withParameter("value", value) .returnUnsignedIntValueOrDefault(0); }
null
255
cpp
blalor-cpputest
PrinterTest.cpp
examples/ApplicationLib/PrinterTest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "Printer.h" #include "MockPrinter.h" TEST_GROUP(Printer) { Printer* printer; MockPrinter* mockPrinter; void setup() { mockPrinter = new MockPrinter(); printer = mockPrinter; } void teardown() { delete printer; } }; TEST(Printer, PrintConstCharStar) { printer->Print("hello"); printer->Print("hello\n"); CHECK_EQUAL("hellohello\n", mockPrinter->getOutput()); } TEST(Printer, PrintLong) { printer->Print(1234); CHECK_EQUAL("1234", mockPrinter->getOutput()); } TEST(Printer, StreamOperators) { *printer << "n=" << 1234; CHECK_EQUAL("n=1234", mockPrinter->getOutput()); }
null
256
cpp
blalor-cpputest
EventDispatcherTest.cpp
examples/ApplicationLib/EventDispatcherTest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" #include "EventDispatcher.h" class ObserverMock : public EventObserver { public: virtual void notify(const Event& event, int timeOutInSeconds) { mock().actualCall("notify").onObject(this).withParameterOfType("Event", "event", (void*) &event).withParameter("timeOutInSeconds", timeOutInSeconds); } virtual void notifyRegistration(EventObserver* newObserver) { mock().actualCall("notifyRegistration").onObject(this).withParameter("newObserver", newObserver); } }; class EventComparator : public MockNamedValueComparator { public: virtual bool isEqual(void* object1, void* object2) { return ((Event*)object1)->type == ((Event*)object2)->type; } virtual SimpleString valueToString(void* object) { return StringFrom(((Event*)object)->type); } }; TEST_GROUP(EventDispatcher) { Event event; EventDispatcher* dispatcher; ObserverMock observer; ObserverMock observer2; EventComparator eventComparator; void setup() { dispatcher = new EventDispatcher; mock().installComparator("Event", eventComparator); } void teardown() { delete dispatcher; mock().removeAllComparators(); } }; TEST(EventDispatcher, EventWithoutRegistrationsResultsIntoNoCalls) { dispatcher->dispatchEvent(event, 10); } TEST(EventDispatcher, EventWithRegistrationForEventResultsIntoCallback) { mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10); event.type = IMPORTANT_EVENT; dispatcher->registerObserver(IMPORTANT_EVENT, &observer); dispatcher->dispatchEvent(event, 10); } TEST(EventDispatcher, DifferentEventWithRegistrationDoesNotResultIntoCallback) { event.type = LESS_IMPORTANT_EVENT; dispatcher->registerObserver(IMPORTANT_EVENT, &observer); dispatcher->dispatchEvent(event, 10); } TEST(EventDispatcher, RegisterTwoObserversResultIntoTwoCallsAndARegistrationNotification) { mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10); mock().expectOneCall("notify").onObject(&observer2).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10); mock().expectOneCall("notifyRegistration").onObject(&observer).withParameter("newObserver", &observer2); event.type = IMPORTANT_EVENT; dispatcher->registerObserver(IMPORTANT_EVENT, &observer); dispatcher->registerObserver(IMPORTANT_EVENT, &observer2); dispatcher->dispatchEvent(event, 10); }
null
257
cpp
blalor-cpputest
EventDispatcher.cpp
examples/ApplicationLib/EventDispatcher.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "EventDispatcher.h" EventDispatcher::EventDispatcher() { } void EventDispatcher::registerObserver(EventType type, EventObserver* observer) { for (list<pair<EventType, EventObserver*> >::iterator i = observerList_.begin(); i != observerList_.end(); i++) i->second->notifyRegistration(observer); observerList_.push_back(make_pair(type, observer)); } void EventDispatcher::dispatchEvent(const Event& event, int timeoutSeconds) { for (list<pair<EventType, EventObserver*> >::iterator i = observerList_.begin(); i != observerList_.end(); i++) { if (i->first == event.type) i->second->notify(event, timeoutSeconds); } }
null
258
cpp
blalor-cpputest
CircularBufferTest.cpp
examples/ApplicationLib/CircularBufferTest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "MockPrinter.h" #include "CircularBuffer.h" TEST_GROUP(CircularBuffer) { CircularBuffer* buffer; void setup() { buffer = new CircularBuffer(); } void teardown() { delete buffer; } void fillTheQueue(int seed, int howMany) { for (int i = 0; i < howMany; i++) buffer->Put(seed + i); } void removeFromQueue(int howMany) { for (int i = 0; i < howMany; i++) buffer->Get(); } }; TEST(CircularBuffer, EmptyAfterCreation) { CHECK(buffer->IsEmpty()); } TEST(CircularBuffer, NotEmpty) { buffer->Put(10046); CHECK(!buffer->IsEmpty()); } TEST(CircularBuffer, NotEmptyThenEmpty) { buffer->Put(4567); CHECK(!buffer->IsEmpty()); buffer->Get(); CHECK(buffer->IsEmpty()); } TEST(CircularBuffer, GetPutOneValue) { buffer->Put(4567); LONGS_EQUAL(4567, buffer->Get()); } TEST(CircularBuffer, GetPutAFew) { buffer->Put(1); buffer->Put(2); buffer->Put(3); LONGS_EQUAL(1, buffer->Get()); LONGS_EQUAL(2, buffer->Get()); LONGS_EQUAL(3, buffer->Get()); } TEST(CircularBuffer, Capacity) { CircularBuffer b(2); LONGS_EQUAL(2, b.Capacity()); } TEST(CircularBuffer, IsFull) { fillTheQueue(0, buffer->Capacity()); CHECK(buffer->IsFull()); } TEST(CircularBuffer, EmptyToFullToEmpty) { fillTheQueue(100, buffer->Capacity()); CHECK(buffer->IsFull()); removeFromQueue(buffer->Capacity()); CHECK(buffer->IsEmpty()); } TEST(CircularBuffer, WrapAround) { fillTheQueue(100, buffer->Capacity()); CHECK(buffer->IsFull()); LONGS_EQUAL(100, buffer->Get()); CHECK(!buffer->IsFull()); buffer->Put(1000); CHECK(buffer->IsFull()); removeFromQueue(buffer->Capacity() - 1); LONGS_EQUAL(1000, buffer->Get()); CHECK(buffer->IsEmpty()); } TEST(CircularBuffer, PutToFull) { int capacity = buffer->Capacity(); fillTheQueue(900, capacity); buffer->Put(9999); for (int i = 0; i < buffer->Capacity() - 1; i++) LONGS_EQUAL(i+900+1, buffer->Get()); LONGS_EQUAL(9999, buffer->Get()); CHECK(buffer->IsEmpty()); } //Sometime people ask what tests the tests. //Do you know the answer TEST(CircularBuffer, GetFromEmpty) { LONGS_EQUAL(-1, buffer->Get()); CHECK(buffer->IsEmpty()); } /* * the next tests demonstrate using a mock object for * capturing output * */ TEST(CircularBuffer, PrintEmpty) { MockPrinter mock; Printer* p = &mock; buffer->Print(p); CHECK_EQUAL("Circular buffer content:\n<>\n", mock.getOutput()); } TEST(CircularBuffer, PrintAfterOnePut) { MockPrinter mock; buffer->Put(1); buffer->Print(&mock); CHECK_EQUAL("Circular buffer content:\n<1>\n", mock.getOutput()); } TEST(CircularBuffer, PrintNotYetWrappedOrFull) { MockPrinter mock; buffer->Put(1); buffer->Put(2); buffer->Put(3); buffer->Print(&mock); CHECK_EQUAL("Circular buffer content:\n<1, 2, 3>\n", mock.getOutput()); } TEST(CircularBuffer, PrintNotYetWrappedAndIsFull) { MockPrinter mock; fillTheQueue(200, buffer->Capacity()); buffer->Print(&mock); const char* expected = "Circular buffer content:\n" "<200, 201, 202, 203, 204>\n"; CHECK_EQUAL(expected, mock.getOutput()); } TEST(CircularBuffer, PrintWrappedAndIsFullOldestToNewest) { MockPrinter mock; fillTheQueue(200, buffer->Capacity()); buffer->Get(); buffer->Put(999); buffer->Print(&mock); const char* expected = "Circular buffer content:\n" "<201, 202, 203, 204, 999>\n"; CHECK_EQUAL(expected, mock.getOutput()); } TEST(CircularBuffer, PrintWrappedAndFullOverwriteOldest) { MockPrinter mock; fillTheQueue(200, buffer->Capacity()); buffer->Put(9999); buffer->Print(&mock); const char* expected = "Circular buffer content:\n" "<201, 202, 203, 204, 9999>\n"; CHECK_EQUAL(expected, mock.getOutput()); } TEST(CircularBuffer, PrintBoundary) { MockPrinter mock; fillTheQueue(200, buffer->Capacity()); removeFromQueue(buffer->Capacity() - 2); buffer->Put(888); fillTheQueue(300, buffer->Capacity() - 1); buffer->Print(&mock); const char* expected = "Circular buffer content:\n" "<888, 300, 301, 302, 303>\n"; CHECK_EQUAL(expected, mock.getOutput()); } TEST(CircularBuffer, FillEmptyThenPrint) { MockPrinter mock; fillTheQueue(200, buffer->Capacity()); removeFromQueue(buffer->Capacity()); buffer->Print(&mock); const char* expected = "Circular buffer content:\n" "<>\n"; CHECK_EQUAL(expected, mock.getOutput()); }
null
259
cpp
blalor-cpputest
Printer.cpp
examples/ApplicationLib/Printer.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Printer.h" #include "CppUTest/TestHarness.h" #include "CppUTest/SimpleString.h" #include <stdio.h> Printer::Printer() { } Printer::~Printer() { } void Printer::Print(const char* s) { for (const char* p = s; *p; p++) putchar(*p); } void Printer::Print(long n) { Print(StringFrom(n).asCharString()); } Printer& operator<<(Printer& p, const char* s) { p.Print(s); return p; } Printer& operator<<(Printer& p, long int i) { p.Print(i); return p; }
null
260
cpp
blalor-cpputest
hello.h
examples/ApplicationLib/hello.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef HELLO_H_ #define HELLO_H_ extern void printHelloWorld(); extern int (*PrintFormated)(const char*, ...); #endif /*HELLO_H_*/
null
261
cpp
blalor-cpputest
EventDispatcher.h
examples/ApplicationLib/EventDispatcher.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef EVENTDISPATCHER__H #define EVENTDISPATCHER__H #include <list> using namespace std; enum EventType { IMPORTANT_EVENT, LESS_IMPORTANT_EVENT }; class Event { public: EventType type; }; class EventObserver { public: virtual void notify(const Event& event, int timeOutInSeconds)=0; virtual void notifyRegistration(EventObserver* newObserver)=0; }; class EventDispatcher { list<pair<EventType, EventObserver*> > observerList_; public: EventDispatcher(); void registerObserver(EventType type, EventObserver* observer); void dispatchEvent(const Event& event, int timeoutSeconds); }; #endif
null
262
cpp
blalor-cpputest
MockPrinter.h
examples/ApplicationLib/MockPrinter.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MockPrinter_H #define D_MockPrinter_H /////////////////////////////////////////////////////////////////////////////// // // MockPrinter.h // // MockPrinter is responsible for providing a test stub for Printer // /////////////////////////////////////////////////////////////////////////////// #include "Printer.h" #include "CppUTest/SimpleString.h" #include <stdlib.h> #include <string> class MockPrinter: public Printer { public: explicit MockPrinter() { } virtual ~MockPrinter() { } virtual void Print(const char* s) { savedOutput.append(s); } virtual void Print(long int value) { SimpleString buffer; buffer = StringFromFormat("%ld", value); savedOutput.append(buffer.asCharString()); } std::string getOutput() const { return savedOutput; } private: std::string savedOutput; MockPrinter(const MockPrinter&); MockPrinter& operator=(const MockPrinter&); }; #endif // D_MockPrinter_H
null
263
cpp
blalor-cpputest
MockDocumentationTest.cpp
examples/ApplicationLib/MockDocumentationTest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" extern "C" { #include "CppUTestExt/MockSupport_c.h" } TEST_GROUP(FirstTestGroup) { }; TEST(FirstTestGroup, FirsTest) { // FAIL("Fail me!"); } TEST(FirstTestGroup, SecondTest) { // STRCMP_EQUAL("hello", "world"); } TEST_GROUP(MockDocumentation) { }; void productionCode() { mock().actualCall("productionCode"); } TEST(MockDocumentation, SimpleScenario) { mock().expectOneCall("productionCode"); productionCode(); mock().checkExpectations(); } class ClassFromProductionCode { public: virtual void importantFunction(){} }; class ClassFromProductionCodeMock : public ClassFromProductionCode { public: virtual void importantFunction() { mock().actualCall("importantFunction").onObject(this); } }; TEST(MockDocumentation, SimpleScenarioObject) { ClassFromProductionCode* object = new ClassFromProductionCodeMock; /* create mock instead of real thing */ mock().expectOneCall("importantFunction").onObject(object); object->importantFunction(); mock().checkExpectations(); delete object; } void parameters_function(int p1, const char* p2) { void* object = (void*) 1; mock().actualCall("function").onObject(object).withParameter("p1", p1).withParameter("p2", p2); } TEST(MockDocumentation, parameters) { void* object = (void*) 1; mock().expectOneCall("function").onObject(object).withParameter("p1", 2).withParameter("p2", "hah"); parameters_function(2, "hah"); } class MyTypeComparator : public MockNamedValueComparator { public: virtual bool isEqual(void* object1, void* object2) { return object1 == object2; } virtual SimpleString valueToString(void* object) { return StringFrom(object); } }; TEST(MockDocumentation, ObjectParameters) { void* object = (void*) 1; MyTypeComparator comparator; mock().installComparator("myType", comparator); mock().expectOneCall("function").withParameterOfType("myType", "parameterName", object); mock().clear(); mock().removeAllComparators(); } TEST(MockDocumentation, returnValue) { mock().expectOneCall("function").andReturnValue(10); int value = mock().actualCall("function").returnValue().getIntValue(); value = mock().returnValue().getIntValue(); } TEST(MockDocumentation, setData) { ClassFromProductionCode object; mock().setData("importantValue", 10); mock().setDataObject("importantObject", "ClassFromProductionCode", &object); ClassFromProductionCode * pobject; int value = mock().getData("importantValue").getIntValue(); pobject = (ClassFromProductionCode*) mock().getData("importantObject").getObjectPointer(); LONGS_EQUAL(10, value); POINTERS_EQUAL(pobject, &object); } void doSomethingThatWouldOtherwiseBlowUpTheMockingFramework() { } TEST(MockDocumentation, otherMockSupport) { mock().crashOnFailure(); // mock().actualCall("unex"); mock().expectOneCall("foo"); mock().ignoreOtherCalls(); mock().disable(); doSomethingThatWouldOtherwiseBlowUpTheMockingFramework(); mock().enable(); mock().clear(); } TEST(MockDocumentation, scope) { mock("xmlparser").expectOneCall("open"); mock("filesystem").ignoreOtherCalls(); mock("xmlparser").actualCall("open"); } static int equalMethod(void* object1, void* object2) { return object1 == object2; } static char* toStringMethod(void*) { return (char*) "string"; } TEST(MockDocumentation, CInterface) { void* object = (void*) 0x1; mock_c()->expectOneCall("foo")->withIntParameters("integer", 10)->andReturnDoubleValue(1.11); mock_c()->actualCall("foo")->withIntParameters("integer", 10)->returnValue().value.doubleValue; mock_c()->installComparator("type", equalMethod, toStringMethod); mock_scope_c("scope")->expectOneCall("bar")->withParameterOfType("type", "name", object); mock_scope_c("scope")->actualCall("bar")->withParameterOfType("type", "name", object); mock_c()->removeAllComparators(); mock_c()->setIntData("important", 10); mock_c()->checkExpectations(); mock_c()->clear(); } TEST_GROUP(FooTestGroup) { void setup() { // Init stuff } void teardown() { // Uninit stuff } }; TEST(FooTestGroup, Foo) { // Test FOO } TEST(FooTestGroup, MoreFoo) { // Test more FOO } TEST_GROUP(BarTestGroup) { void setup() { // Init Bar } }; TEST(BarTestGroup, Bar) { // Test Bar }
null
264
cpp
blalor-cpputest
CircularBuffer.cpp
examples/ApplicationLib/CircularBuffer.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CircularBuffer.h" #include "Printer.h" CircularBuffer::CircularBuffer(int _capacity) : index(0), outdex(0), capacity(_capacity), empty(true), full(false) { buffer = new int[this->capacity]; } CircularBuffer::~CircularBuffer() { delete[] buffer; } bool CircularBuffer::IsEmpty() { return empty; } bool CircularBuffer::IsFull() { return full; } void CircularBuffer::Put(int i) { empty = false; buffer[index] = i; index = Next(index); if (full) outdex = Next(outdex); else if (index == outdex) full = true; } int CircularBuffer::Get() { int result = -1; full = false; if (!empty) { result = buffer[outdex]; outdex = Next(outdex); if (outdex == index) empty = true; } return result; } int CircularBuffer::Capacity() { return capacity; } int CircularBuffer::Next(int i) { if (++i >= capacity) i = 0; return i; } void CircularBuffer::Print(Printer* p) { p->Print("Circular buffer content:\n<"); int printIndex = outdex; int count = index - outdex; if (!empty && (index <= outdex)) count = capacity - (outdex - index); for (int i = 0; i < count; i++) { p->Print(buffer[printIndex]); printIndex = Next(printIndex); if (i + 1 != count) p->Print(", "); } p->Print(">\n"); }
null
265
cpp
blalor-cpputest
HelloTest.cpp
examples/ApplicationLib/HelloTest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ extern "C" { #include "hello.h" } #include <stdio.h> #include <stdarg.h> #include "CppUTest/TestHarness.h" static SimpleString* buffer; TEST_GROUP(HelloWorld) { static int output_method(const char* output, ...) { va_list arguments; va_start(arguments, output); *buffer = VStringFromFormat(output, arguments); va_end(arguments); return 1; } void setup() { buffer = new SimpleString(); UT_PTR_SET(PrintFormated, &output_method); } void teardown() { delete buffer; } }; TEST(HelloWorld, PrintOk) { printHelloWorld(); STRCMP_EQUAL("Hello World!\n", buffer->asCharString()); }
null
266
cpp
blalor-cpputest
ExamplesNewOverrides.h
examples/ApplicationLib/ExamplesNewOverrides.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <list> #include "CppUTest/MemoryLeakDetectorNewMacros.h"
null
267
cpp
blalor-cpputest
Printer.h
examples/ApplicationLib/Printer.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_Printer_H #define D_Printer_H /////////////////////////////////////////////////////////////////////////////// // // Printer is responsible for ... // /////////////////////////////////////////////////////////////////////////////// class Printer { public: explicit Printer(); virtual ~Printer(); virtual void Print(const char*); virtual void Print(long int); private: Printer(const Printer&); Printer& operator=(const Printer&); }; Printer& operator<<(Printer&, const char*); Printer& operator<<(Printer&, long int); #endif // D_Printer_H
null
268
cpp
blalor-cpputest
AllTests.h
examples/ApplicationLib/AllTests.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ IMPORT_TEST_GROUP( Printer); IMPORT_TEST_GROUP( CircularBuffer); IMPORT_TEST_GROUP( HelloWorld); IMPORT_TEST_GROUP( EventDispatcher); IMPORT_TEST_GROUP( MockDocumentation);
null
269
cpp
blalor-cpputest
CircularBuffer.h
examples/ApplicationLib/CircularBuffer.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_CircularBuffer_H #define D_CircularBuffer_H /////////////////////////////////////////////////////////////////////////////// // // CircularBuffer.h // // CircularBuffer is responsible for ... // /////////////////////////////////////////////////////////////////////////////// class Printer; class CircularBuffer { public: explicit CircularBuffer(int capacity = CAPACITY); virtual ~CircularBuffer(); void Put(int); int Get(); bool IsEmpty(); bool IsFull(); int Capacity(); int Next(int i); void Print(Printer*); private: int index; int outdex; int* buffer; int capacity; enum { CAPACITY = 5 }; bool empty; bool full; CircularBuffer(const CircularBuffer&); CircularBuffer& operator=(const CircularBuffer&); }; #endif // D_CircularBuffer_H
null
270
cpp
blalor-cpputest
AllTests.cpp
examples/AllTests/AllTests.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/TestPlugin.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h" class MyDummyComparator : public MockNamedValueComparator { public: virtual bool isEqual(void* object1, void* object2) { return object1 == object2; } virtual SimpleString valueToString(void* object) { return StringFrom(object); } }; int main(int ac, char** av) { MyDummyComparator dummyComparator; MockSupportPlugin mockPlugin; mockPlugin.installComparator("MyDummyType", dummyComparator); TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin); return CommandLineTestRunner::RunAllTests(ac, av); } #include "ApplicationLib/AllTests.h"
null
271
cpp
blalor-cpputest
StarterMemoryLeakWarning.cpp
src/Platforms/StarterKit/StarterMemoryLeakWarning.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/MemoryLeakWarning.h" #include <stdlib.h> #include <stdio.h> /* Static since we REALLY can have only one of these! */ static int allocatedBlocks = 0; static int allocatedArrays = 0; static int firstInitialBlocks = 0; static int firstInitialArrays = 0; static bool reporterRegistered = false; class MemoryLeakWarningData { public: MemoryLeakWarningData(); int initialBlocksUsed; int initialArraysUsed; int blockUsageCheckPoint; int arrayUsageCheckPoint; int expectCount; char message[100]; }; void MemoryLeakWarning::CreateData() { _impl = (MemoryLeakWarningData*) malloc(sizeof(MemoryLeakWarningData)); _impl->initialBlocksUsed = 0; _impl->initialArraysUsed = 0; _impl->blockUsageCheckPoint = 0; _impl->arrayUsageCheckPoint = 0; _impl->expectCount = 0; _impl->message_[0] = '\0'; } void MemoryLeakWarning::DestroyData() { free(_impl); } extern "C" { void reportMemoryBallance(); } void reportMemoryBallance() { int blockBalance = allocatedBlocks - firstInitialBlocks; int arrayBalance = allocatedArrays - firstInitialArrays; if (blockBalance == 0 && arrayBalance == 0) ; else if (blockBalance + arrayBalance == 0) printf("No leaks but some arrays were deleted without []\n"); else { if (blockBalance > 0) printf("Memory leak! %d blocks not deleted\n", blockBalance); if (arrayBalance > 0) printf("Memory leak! %d arrays not deleted\n", arrayBalance); if (blockBalance < 0) printf("More blocks deleted than newed! %d extra deletes\n", blockBalance); if (arrayBalance < 0) printf("More arrays deleted than newed! %d extra deletes\n", arrayBalance); printf("NOTE - some memory leaks appear to be allocated statics that are not released\n" " - by the standard library\n" " - Use the -r switch on your unit tests to repeat the test sequence\n" " - If no leaks are reported on the second pass, it is likely a static\n" " - that is not released\n"); } } MemoryLeakWarning* MemoryLeakWarning::_latest = NULL; MemoryLeakWarning::MemoryLeakWarning() { _latest = this; CreateData(); } MemoryLeakWarning::~MemoryLeakWarning() { DestroyData(); } MemoryLeakWarning* MemoryLeakWarning::GetLatest() { return _latest; } void MemoryLeakWarning::SetLatest(MemoryLeakWarning* latest) { _latest = latest; } void MemoryLeakWarning::Enable() { _impl->initialBlocksUsed = allocatedBlocks; _impl->initialArraysUsed = allocatedArrays; if (!reporterRegistered) { firstInitialBlocks = allocatedBlocks; firstInitialArrays = allocatedArrays; reporterRegistered = true; } } const char* MemoryLeakWarning::FinalReport(int toBeDeletedLeaks) { if (_impl->initialBlocksUsed != (allocatedBlocks-toBeDeletedLeaks) || _impl->initialArraysUsed != allocatedArrays ) { printf("initial blocks=%d, allocated blocks=%d\ninitial arrays=%d, allocated arrays=%d\n", _impl->initialBlocksUsed, allocatedBlocks, _impl->initialArraysUsed, allocatedArrays); return "Memory new/delete imbalance after running tests\n"; } else return ""; } void MemoryLeakWarning::CheckPointUsage() { _impl->blockUsageCheckPoint = allocatedBlocks; _impl->arrayUsageCheckPoint = allocatedArrays; } bool MemoryLeakWarning::UsageIsNotBalanced() { int arrayBalance = allocatedArrays - _impl->arrayUsageCheckPoint; int blockBalance = allocatedBlocks - _impl->blockUsageCheckPoint; if (_impl->expectCount != 0 && blockBalance + arrayBalance == _impl->expectCount) return false; if (blockBalance == 0 && arrayBalance == 0) return false; else if (blockBalance + arrayBalance == 0) sprintf(_impl->message_, "No leaks but some arrays were deleted without []\n"); else { int nchars = 0; if (_impl->blockUsageCheckPoint != allocatedBlocks) nchars = sprintf(_impl->message_, "this test leaks %d blocks", allocatedBlocks - _impl->blockUsageCheckPoint); if (_impl->arrayUsageCheckPoint != allocatedArrays) sprintf(_impl->message_ + nchars, "this test leaks %d arrays", allocatedArrays - _impl->arrayUsageCheckPoint); } return true; } const char* MemoryLeakWarning::Message() { return _impl->message_; } void MemoryLeakWarning::ExpectLeaks(int n) { _impl->expectCount = n; } /* Global overloaded operators */ void* operator new(size_t size) { allocatedBlocks++; return malloc(size); } void operator delete(void* mem) { allocatedBlocks--; free(mem); } void* operator new[](size_t size) { allocatedArrays++; return malloc(size); } void operator delete[](void* mem) { allocatedArrays--; free(mem); } void* operator new(size_t size, const char* file, int line) { allocatedBlocks++; return malloc(size); }
null
272
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/StarterKit/UtestPlatform.cpp
null
#include "CppUTest/TestHarness.h" #include "CppUTest/TestResult.h" #include <time.h> #include <sys/time.h> void Utest::executePlatformSpecificTestBody() { testBody(); } ///////////// Time in millis static long TimeInMillisImplementation() { struct timeval tv; struct timezone tz; ::gettimeofday(&tv, &tz); return (tv.tv_sec * 1000) + (long)(tv.tv_usec * 0.001); } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static SimpleString TimeStringImplementation() { time_t tm = time(NULL); return ctime(&tm); } static SimpleString (*timeStringFp) () = TimeStringImplementation; SimpleString GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(SimpleString (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } ///////////// Run one test with exit on first error, using setjmp/longjmp #include <setjmp.h> static jmp_buf test_exit_jmp_buf; void TestRegistry::platformSpecificRunOneTest(Utest* test, TestResult& result) { if (0 == setjmp(test_exit_jmp_buf)) runOneTest(test, result) ; } void PlatformSpecificExitCurrentTestImpl() { longjmp(test_exit_jmp_buf, 1); } void FakePlatformSpecificExitCurrentTest() { } void (*PlatformSpecificExitCurrentTest)() = PlatformSpecificExitCurrentTestImpl;
null
273
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/GccNoStdC/UtestPlatform.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #undef malloc #undef free #undef calloc #undef realloc #include "CppUTest/TestRegistry.h" #include "CppUTest/PlatformSpecificFunctions.h" bool Utest::executePlatformSpecificSetup() { /* To be implemented */ setup(); return false; } void Utest::executePlatformSpecificTestBody() { /* To be implemented */ testBody(); } void Utest::executePlatformSpecificTeardown() { /* To be implemented */ teardown(); } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { /* To be implemented */ runOneTest(plugin, result); } void Utest::executePlatformSpecificExitCurrentTest() { /* To be implemented */ } long GetPlatformSpecificTimeInMillis() { /* To be implemented */ return 0; } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { (void) platformSpecific; } ///////////// Time in String const char* GetPlatformSpecificTimeString() { /* To be implemented */ return NULL; } void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) { /* To be implemented */ (void) platformMethod; } int PlatformSpecificAtoI(const char*str) { /* To be implemented */ (void) str; return 0; } size_t PlatformSpecificStrLen(const char* str) { /* To be implemented */ (void) str; return 0; } char* PlatformSpecificStrCat(char* s1, const char* s2) { /* To be implemented */ (void) s1; (void) s2; return NULL; } char* PlatformSpecificStrCpy(char* s1, const char* s2) { /* To be implemented */ (void) s1; (void) s2; return NULL; } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { /* To be implemented */ (void) s1; (void) s2; (void) size; return NULL; } int PlatformSpecificStrCmp(const char* s1, const char* s2) { /* To be implemented */ (void) s1; (void) s2; return 0; } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { /* To be implemented */ (void) s1; (void) s2; (void) size; return 0; } char* PlatformSpecificStrStr(const char* s1, const char* s2) { /* To be implemented */ (void) s1; (void) s2; return NULL; } int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args) { /* To be implemented */ (void) size; (void) args; (void) format; (void) args; (void) str; return 0; } char PlatformSpecificToLower(char c) { /* To be implemented */ (void) c; return 0; } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { /* To be implemented */ (void) filename; (void) flag; return NULL; } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { /* To be implemented */ (void) str; (void) file; } void PlatformSpecificFClose(PlatformSpecificFile file) { /* To be implemented */ (void) file; } void PlatformSpecificFlush() { /* To be implemented */ } int PlatformSpecificPutchar(int c) { /* To be implemented */ (void) c; return 0; } void* PlatformSpecificMalloc(size_t size) { /* To be implemented */ (void) size; return NULL; } void* PlatformSpecificRealloc (void* memory, size_t size) { /* To be implemented */ (void) memory; (void) size; return NULL; } void PlatformSpecificFree(void* memory) { /* To be implemented */ (void) memory; } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { /* To be implemented */ (void) size; (void) s1; (void) s2; return NULL; } void* PlatformSpecificMemset(void* mem, int c, size_t size) { /* To be implemented */ (void) mem; (void) c; (void) size; return NULL; } double PlatformSpecificFabs(double d) { /* To be implemented */ (void) d; return 0.0; } int PlatformSpecificIsNan(double d) { /* To be implemented */ (void) d; return 0; } void* malloc(size_t) { return NULL; } void free(void *) { }
null
274
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/VisualCpp/UtestPlatform.cpp
null
#include "Platform.h" #include <stdlib.h> #include "CppUTest/TestHarness.h" #undef malloc #undef free #undef calloc #undef realloc #include "CppUTest/TestRegistry.h" #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #include <string.h> #include <math.h> #include <float.h> #include "CppUTest/PlatformSpecificFunctions.h" #include <windows.h> #include <mmsystem.h> #if 0 //from GCC static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; bool Utest::executePlatformSpecificSetup() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; setup(); jmp_buf_index--; return true; } return false; } void Utest::executePlatformSpecificTestBody() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; testBody(); jmp_buf_index--; } } void Utest::executePlatformSpecificTeardown() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; teardown(); jmp_buf_index--; } } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin_, TestResult& result_) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; runOneTest(plugin_, result_); jmp_buf_index--; } } void Utest::executePlatformSpecificExitCurrentTest() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } #endif ///////////// Time in millis static long TimeInMillisImplementation() { return timeGetTime()/1000; } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static const char* TimeStringImplementation() { return "Windows time needs work"; } static const char* (*timeStringFp) () = TimeStringImplementation; const char* GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } ////// taken from gcc int PlatformSpecificAtoI(const char*str) { return atoi(str); } size_t PlatformSpecificStrLen(const char* str) { return strlen(str); } char* PlatformSpecificStrCat(char* s1, const char* s2) { return strcat(s1, s2); } char* PlatformSpecificStrCpy(char* s1, const char* s2) { return strcpy(s1, s2); } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { return strncpy(s1, s2, size); } int PlatformSpecificStrCmp(const char* s1, const char* s2) { return strcmp(s1, s2); } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { return strncmp(s1, s2, size); } char* PlatformSpecificStrStr(const char* s1, const char* s2) { return (char*) strstr(s1, s2); } int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args) { char* buf = 0; int sizeGuess = size; int result = _vsnprintf( str, size, format, args); str[size-1] = 0; while (result == -1) { if (buf != 0) free(buf); sizeGuess += 10; buf = (char*)malloc(sizeGuess); result = _vsnprintf( buf, sizeGuess, format, args); } if (buf != 0) free(buf); return result; } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { return fopen(filename, flag); } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { fputs(str, (FILE*)file); } void PlatformSpecificFClose(PlatformSpecificFile file) { fclose((FILE*)file); } void PlatformSpecificFlush() { fflush(stdout); } int PlatformSpecificPutchar(int c) { return putchar(c); } void* PlatformSpecificMalloc(size_t size) { return malloc(size); } void* PlatformSpecificRealloc (void* memory, size_t size) { return realloc(memory, size); } void PlatformSpecificFree(void* memory) { free(memory); } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { return memcpy(s1, s2, size); } void* PlatformSpecificMemset(void* mem, int c, size_t size) { return memset(mem, c, size); } double PlatformSpecificFabs(double d) { return fabs(d); } int PlatformSpecificIsNan(double d) { return _isnan(d); } /////// clean up the rest #if 0 void TestRegistry::platformSpecificRunOneTest(Utest* test, TestResult& result_) { try { runOneTest(test, result_) ; } catch (int) { //exiting test early } } void Utest::executePlatformSpecificTestBody() { testBody(); } void PlatformSpecificExitCurrentTestImpl() { throw(1); } #endif int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, void* args) { return _vsnprintf( str, size, format, (va_list) args); } char PlatformSpecificToLower(char c) { return tolower(c); } //platform specific test running stuff #if 1 #include <setjmp.h> static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; bool Utest::executePlatformSpecificSetup() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; setup(); jmp_buf_index--; return true; } return false; } void Utest::executePlatformSpecificTestBody() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; testBody(); jmp_buf_index--; } } void Utest::executePlatformSpecificTeardown() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; teardown(); jmp_buf_index--; } } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; runOneTest(plugin, result); jmp_buf_index--; } } void Utest::executePlatformSpecificExitCurrentTest() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } /* void PlatformSpecificExitCurrentTestImpl() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } */ #endif //static jmp_buf test_exit_jmp_buf[10]; //static int jmp_buf_index = 0; #if 0 bool Utest::executePlatformSpecificSetup() { try { setup(); } catch (int) { return false; } return true; } void Utest::executePlatformSpecificTestBody() { try { testBody(); } catch (int) { } } void Utest::executePlatformSpecificTeardown() { try { teardown(); } catch (int) { } } void PlatformSpecificExitCurrentTestImpl() { throw(1); } void (*PlatformSpecificExitCurrentTest)() = PlatformSpecificExitCurrentTestImpl; void FakePlatformSpecificExitCurrentTest() { } #endif
null
275
cpp
blalor-cpputest
SymbianMemoryLeakWarning.cpp
src/Platforms/Symbian/SymbianMemoryLeakWarning.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde and Timo Puronen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "MemoryLeakWarning.h" #include <e32base.h> MemoryLeakWarning* MemoryLeakWarning::_latest = NULL; // naming convention due to CppUTest generic class name class MemoryLeakWarningData : public CBase { public: TInt iInitialAllocCells; TInt iExpectedLeaks; TInt iInitialThreadHandleCount; TInt iInitialProcessHandleCount; }; MemoryLeakWarning::MemoryLeakWarning() { _latest = this; CreateData(); } MemoryLeakWarning::~MemoryLeakWarning() { DestroyData(); } void MemoryLeakWarning::Enable() { } const char* MemoryLeakWarning::FinalReport(int toBeDeletedLeaks) { TInt cellDifference(User::CountAllocCells() - _impl->iInitialAllocCells); if( cellDifference != toBeDeletedLeaks ) { return "Heap imbalance after test\n"; } TInt processHandles; TInt threadHandles; RThread().HandleCount(processHandles, threadHandles); if(_impl->iInitialProcessHandleCount != processHandles || _impl->iInitialThreadHandleCount != threadHandles) { return "Handle count imbalance after test\n"; } return ""; } void MemoryLeakWarning::CheckPointUsage() { _impl->iInitialAllocCells = User::CountAllocCells(); RThread().HandleCount(_impl->iInitialProcessHandleCount, _impl->iInitialThreadHandleCount); } bool MemoryLeakWarning::UsageIsNotBalanced() { TInt allocatedCells(User::CountAllocCells()); if(_impl->iExpectedLeaks != 0) { TInt difference(Abs(_impl->iInitialAllocCells - allocatedCells)); return difference != _impl->iExpectedLeaks; } return allocatedCells != _impl->iInitialAllocCells; } const char* MemoryLeakWarning::Message() { return ""; } void MemoryLeakWarning::ExpectLeaks(int n) { _impl->iExpectedLeaks = n; } // this method leaves (no naming convention followed due to CppUTest framework void MemoryLeakWarning::CreateData() { _impl = new(ELeave) MemoryLeakWarningData(); } void MemoryLeakWarning::DestroyData() { delete _impl; _impl = NULL; } MemoryLeakWarning* MemoryLeakWarning::GetLatest() { return _latest; } void MemoryLeakWarning::SetLatest(MemoryLeakWarning* latest) { _latest = latest; }
null
276
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/Symbian/UtestPlatform.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde and Timo Puronen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include <e32def.h> #include <e32std.h> #include <sys/time.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <stdlib.h> #include "CppUTest/PlatformSpecificFunctions.h" void Utest::executePlatformSpecificTestBody() { TInt err(KErrNone); TRAP(err, testBody()); if(err != KErrNone) { Utest::getCurrent()->fail("Leave in test method", "", 0); } } void Utest::executePlatformSpecificExitCurrentTest() { User::Leave(KErrNone); } bool Utest::executePlatformSpecificSetup() { setup(); return true; } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { runOneTest(plugin, result); } void Utest::executePlatformSpecificTeardown() { teardown(); } static long TimeInMillisImplementation() { struct timeval tv; struct timezone tz; ::gettimeofday(&tv, &tz); return (tv.tv_sec * 1000) + (long)(tv.tv_usec * 0.001); } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static SimpleString TimeStringImplementation() { time_t tm = time(NULL); return ctime(&tm); } static SimpleString (*timeStringFp) () = TimeStringImplementation; SimpleString GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(SimpleString (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } int PlatformSpecificVSNprintf(char* str, unsigned int size, const char* format, va_list args) { return vsnprintf(str, size, format, args); } char PlatformSpecificToLower(char c) { return tolower(c); } void PlatformSpecificFlush() { fflush(stdout); } int PlatformSpecificPutchar(int c) { return putchar(c); } char* PlatformSpecificStrCpy(char* s1, const char* s2) { return strcpy(s1, s2); } size_t PlatformSpecificStrLen(const char* s) { return strlen(s); } char* PlatformSpecificStrStr(const char* s1, const char* s2) { return strstr(s1, s2); } int PlatformSpecificStrCmp(const char* s1, const char* s2) { return strcmp(s1, s2); } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { return strncpy(s1, s2, size); } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { return strncmp(s1, s2, size); } char* PlatformSpecificStrCat(char* s1, const char* s2) { return strcat(s1, s2); } double PlatformSpecificFabs(double d) { return fabs(d); } void* PlatformSpecificMalloc(size_t size) { return malloc(size); } void* PlatformSpecificRealloc (void* memory, size_t size) { return realloc(memory, size); } void PlatformSpecificFree(void* memory) { free(memory); } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { return memcpy(s1, s2, size); } void* PlatformSpecificMemset(void* mem, int c, size_t size) { return memset(mem, c, size); } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { return fopen(filename, flag); } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { fputs(str, (FILE*)file); } void PlatformSpecificFClose(PlatformSpecificFile file) { fclose((FILE*)file); } int PlatformSpecificAtoI(const char*str) { return atoi(str); }
null
277
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/Gcc/UtestPlatform.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include "CppUTest/TestHarness.h" #undef malloc #undef free #undef calloc #undef realloc #include "CppUTest/TestRegistry.h" #include <sys/time.h> #include <time.h> #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #include <string.h> #include <math.h> #include <ctype.h> #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; bool Utest::executePlatformSpecificSetup() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; setup(); jmp_buf_index--; return true; } return false; } void Utest::executePlatformSpecificTestBody() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; testBody(); jmp_buf_index--; } } void Utest::executePlatformSpecificTeardown() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; teardown(); jmp_buf_index--; } } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; runOneTest(plugin, result); jmp_buf_index--; } } void Utest::executePlatformSpecificExitCurrentTest() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } ///////////// Time in millis static long TimeInMillisImplementation() { struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001); } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static const char* TimeStringImplementation() { time_t tm = time(NULL); return ctime(&tm); } static const char* (*timeStringFp) () = TimeStringImplementation; const char* GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } int PlatformSpecificAtoI(const char*str) { return atoi(str); } size_t PlatformSpecificStrLen(const char* str) { return strlen(str); } char* PlatformSpecificStrCat(char* s1, const char* s2) { return strcat(s1, s2); } char* PlatformSpecificStrCpy(char* s1, const char* s2) { return strcpy(s1, s2); } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { return strncpy(s1, s2, size); } int PlatformSpecificStrCmp(const char* s1, const char* s2) { return strcmp(s1, s2); } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { return strncmp(s1, s2, size); } char* PlatformSpecificStrStr(const char* s1, const char* s2) { return (char*) strstr(s1, s2); } int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args) { return vsnprintf( str, size, format, args); } char PlatformSpecificToLower(char c) { return (char) tolower((char) c); } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { return fopen(filename, flag); } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { fputs(str, (FILE*)file); } void PlatformSpecificFClose(PlatformSpecificFile file) { fclose((FILE*)file); } void PlatformSpecificFlush() { fflush(stdout); } int PlatformSpecificPutchar(int c) { return putchar(c); } void* PlatformSpecificMalloc(size_t size) { return malloc(size); } void* PlatformSpecificRealloc (void* memory, size_t size) { return realloc(memory, size); } void PlatformSpecificFree(void* memory) { free(memory); } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { return memcpy(s1, s2, size); } void* PlatformSpecificMemset(void* mem, int c, size_t size) { return memset(mem, c, size); } double PlatformSpecificFabs(double d) { return fabs(d); } int PlatformSpecificIsNan(double d) { return isnan((float)d); }
null
278
cpp
blalor-cpputest
UtestPlatform.cpp
src/Platforms/Iar/UtestPlatform.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <time.h> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <setjmp.h> #include <string.h> #include <math.h> #include "CppUTest/TestHarness.h" #undef malloc #undef calloc #undef realloc #undef free #include "CppUTest/TestRegistry.h" #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; bool Utest::executePlatformSpecificSetup() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; setup(); jmp_buf_index--; return true; } return false; } void Utest::executePlatformSpecificTestBody() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; testBody(); jmp_buf_index--; } } void Utest::executePlatformSpecificTeardown() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; teardown(); jmp_buf_index--; } } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; runOneTest(plugin, result); jmp_buf_index--; } } void Utest::executePlatformSpecificExitCurrentTest() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } ///////////// Time in millis static long TimeInMillisImplementation() { clock_t t = clock(); t = t * 10; return 1; } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static const char* TimeStringImplementation() { time_t tm = time(NULL); return ctime(&tm); } static const char* (*timeStringFp) () = TimeStringImplementation; const char* GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } int PlatformSpecificAtoI(const char*str) { return atoi(str); } size_t PlatformSpecificStrLen(const char* str) { return strlen(str); } char* PlatformSpecificStrCat(char* s1, const char* s2) { return strcat(s1, s2); } char* PlatformSpecificStrCpy(char* s1, const char* s2) { return strcpy(s1, s2); } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { return strncpy(s1, s2, size); } int PlatformSpecificStrCmp(const char* s1, const char* s2) { return strcmp(s1, s2); } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { return strncmp(s1, s2, size); } char* PlatformSpecificStrStr(const char* s1, const char* s2) { return strstr((char*)s1, (char*)s2); } int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args) { return vsnprintf( str, size, format, args); } char PlatformSpecificToLower(char c) { return tolower(c); } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { return 0; } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { } void PlatformSpecificFClose(PlatformSpecificFile file) { } void PlatformSpecificFlush() { } int PlatformSpecificPutchar(int c) { return putchar(c); } void* PlatformSpecificMalloc(size_t size) { return malloc(size); } void* PlatformSpecificRealloc (void* memory, size_t size) { return realloc(memory, size); } void PlatformSpecificFree(void* memory) { free(memory); } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { return memcpy(s1, s2, size); } void* PlatformSpecificMemset(void* mem, int c, size_t size) { return memset(mem, c, size); } double PlatformSpecificFabs(double d) { return fabs(d); } int PlatformSpecificIsNan(double d) { return isnan(d); }
null
279
cpp
blalor-cpputest
MemoryReportFormatter.cpp
src/CppUTestExt/MemoryReportFormatter.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MemoryReportAllocator.h" #include "CppUTestExt/MemoryReportFormatter.h" NormalMemoryReportFormatter::NormalMemoryReportFormatter() { } NormalMemoryReportFormatter::~NormalMemoryReportFormatter() { } void NormalMemoryReportFormatter::report_test_start(TestResult* result, Utest& test) { result->print(StringFromFormat("TEST(%s, %s)\n", test.getGroup().asCharString(), test.getName().asCharString()).asCharString()); } void NormalMemoryReportFormatter::report_test_end(TestResult* result, Utest& test) { result->print(StringFromFormat("ENDTEST(%s, %s)\n", test.getGroup().asCharString(), test.getName().asCharString()).asCharString()); } void NormalMemoryReportFormatter::report_alloc_memory(TestResult* result, MemoryLeakAllocator* allocator, size_t size, char* memory, const char* file, int line) { result->print(StringFromFormat("\tAllocation using %s of size: %d pointer: %p at %s:%d\n", allocator->alloc_name(), size, memory, file, line).asCharString()); } void NormalMemoryReportFormatter::report_free_memory(TestResult* result, MemoryLeakAllocator* allocator, char* memory, const char* file, int line) { result->print(StringFromFormat("\tDeallocation using %s of pointer: %p at %s:%d\n", allocator->free_name(), memory, file, line).asCharString()); } void NormalMemoryReportFormatter::report_testgroup_start(TestResult* result, Utest& test) { const size_t line_size = 80; SimpleString groupName = StringFromFormat("TEST GROUP(%s)", test.getGroup().asCharString()); size_t beginPos = (line_size/2) - (groupName.size()/2); SimpleString line("-", beginPos); line += groupName; line += SimpleString("-", line_size - line.size()); line += "\n"; result->print(line.asCharString()); }
null
280
cpp
blalor-cpputest
MockExpectedFunctionCall.cpp
src/CppUTestExt/MockExpectedFunctionCall.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockExpectedFunctionCall.h" SimpleString StringFrom(const MockNamedValue& parameter) { return parameter.toString(); } MockExpectedFunctionCall::MockExpectedFunctionCall() : ignoreOtherParameters_(false), parametersWereIgnored_(false), callOrder_(0), expectedCallOrder_(NO_EXPECTED_CALL_ORDER), outOfOrder_(true), returnValue_(""), objectPtr_(NULL), wasPassedToObject_(true) { parameters_ = new MockNamedValueList(); } MockExpectedFunctionCall::~MockExpectedFunctionCall() { parameters_->clear(); delete parameters_; } MockFunctionCall& MockExpectedFunctionCall::withName(const SimpleString& name) { setName(name); callOrder_ = NOT_CALLED_YET; return *this; } MockFunctionCall& MockExpectedFunctionCall::withParameter(const SimpleString& name, int value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withParameter(const SimpleString& name, double value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withParameter(const SimpleString& name, const char* value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withParameter(const SimpleString& name, void* value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withParameterOfType(const SimpleString& type, const SimpleString& name, void* value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setObjectPointer(type, value); newParameter->setComparator(getComparatorForType(type)); return *this; } SimpleString MockExpectedFunctionCall::getParameterType(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return (p) ? p->getType() : ""; } bool MockExpectedFunctionCall::hasParameterWithName(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return p != NULL; } MockNamedValue MockExpectedFunctionCall::getParameter(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return (p) ? *p : MockNamedValue(""); } bool MockExpectedFunctionCall::areParametersFulfilled() { for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) if (! item(p)->isFulfilled()) return false; return true; } bool MockExpectedFunctionCall::areIgnoredParametersFulfilled() { if (ignoreOtherParameters_) return parametersWereIgnored_; return true; } MockFunctionCall& MockExpectedFunctionCall::ignoreOtherParameters() { ignoreOtherParameters_ = true; return *this; } bool MockExpectedFunctionCall::isFulfilled() { return isFulfilledWithoutIgnoredParameters() && areIgnoredParametersFulfilled(); } bool MockExpectedFunctionCall::isFulfilledWithoutIgnoredParameters() { return callOrder_ != NOT_CALLED_YET && areParametersFulfilled() && wasPassedToObject_; } void MockExpectedFunctionCall::callWasMade(int callOrder) { callOrder_ = callOrder; if (expectedCallOrder_ == NO_EXPECTED_CALL_ORDER) outOfOrder_ = false; else if (callOrder_ == expectedCallOrder_) outOfOrder_ = false; else outOfOrder_ = true; } void MockExpectedFunctionCall::parametersWereIgnored() { parametersWereIgnored_ = true; } void MockExpectedFunctionCall::wasPassedToObject() { wasPassedToObject_ = true; } void MockExpectedFunctionCall::resetExpectation() { callOrder_ = NOT_CALLED_YET; wasPassedToObject_ = (objectPtr_ == NULL); for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) item(p)->setFulfilled(false); } void MockExpectedFunctionCall::parameterWasPassed(const SimpleString& name) { for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) { if (p->getName() == name) item(p)->setFulfilled(true); } } SimpleString MockExpectedFunctionCall::getParameterValueString(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return (p) ? StringFrom(*p) : "failed"; } bool MockExpectedFunctionCall::hasParameter(const MockNamedValue& parameter) { MockNamedValue * p = parameters_->getValueByName(parameter.getName()); return (p) ? p->equals(parameter) : ignoreOtherParameters_; } SimpleString MockExpectedFunctionCall::callToString() { SimpleString str; if (objectPtr_) str = StringFromFormat("(object address: %p)::", objectPtr_); str += getName(); str += " -> "; if (expectedCallOrder_ != NO_EXPECTED_CALL_ORDER) { str += StringFromFormat("expected call order: <%d> -> ", expectedCallOrder_); } if (parameters_->begin() == NULL) { str += (ignoreOtherParameters_) ? "all parameters ignored" : "no parameters"; return str; } for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) { str += StringFromFormat("%s %s: <%s>", p->getType().asCharString(), p->getName().asCharString(), getParameterValueString(p->getName()).asCharString()); if (p->next()) str += ", "; } if (ignoreOtherParameters_) str += ", other parameters are ignored"; return str; } SimpleString MockExpectedFunctionCall::missingParametersToString() { SimpleString str; for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) { if (! item(p)->isFulfilled()) { if (str != "") str += ", "; str += StringFromFormat("%s %s", p->getType().asCharString(), p->getName().asCharString()); } } return str; } bool MockExpectedFunctionCall::relatesTo(const SimpleString& functionName) { return functionName == getName(); } bool MockExpectedFunctionCall::relatesToObject(void*objectPtr) const { return objectPtr_ == objectPtr; } MockExpectedFunctionCall::MockExpectedFunctionParameter* MockExpectedFunctionCall::item(MockNamedValueListNode* node) { return (MockExpectedFunctionParameter*) node->item(); } MockExpectedFunctionCall::MockExpectedFunctionParameter::MockExpectedFunctionParameter(const SimpleString& name) : MockNamedValue(name), fulfilled_(false) { } void MockExpectedFunctionCall::MockExpectedFunctionParameter::setFulfilled(bool b) { fulfilled_ = b; } bool MockExpectedFunctionCall::MockExpectedFunctionParameter::isFulfilled() const { return fulfilled_; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(int value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(const char* value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(double value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(void* value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::onObject(void* objectPtr) { wasPassedToObject_ = false; objectPtr_ = objectPtr; return *this; } bool MockExpectedFunctionCall::hasReturnValue() { return ! returnValue_.getName().isEmpty(); } MockNamedValue MockExpectedFunctionCall::returnValue() { return returnValue_; } int MockExpectedFunctionCall::getCallOrder() const { return callOrder_; } MockFunctionCall& MockExpectedFunctionCall::withCallOrder(int callOrder) { expectedCallOrder_ = callOrder; return *this; } bool MockExpectedFunctionCall::isOutOfOrder() const { return outOfOrder_; }
null
281
cpp
blalor-cpputest
MemoryReporterPlugin.cpp
src/CppUTestExt/MemoryReporterPlugin.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MemoryReporterPlugin.h" #include "CppUTestExt/MemoryReportFormatter.h" #include "CppUTestExt/CodeMemoryReportFormatter.h" MemoryReporterPlugin::MemoryReporterPlugin() : TestPlugin("MemoryReporterPlugin"), formatter_(NULL) { } MemoryReporterPlugin::~MemoryReporterPlugin() { removeGlobalMemoryReportAllocators(); destroyMemoryFormatter(formatter_); } bool MemoryReporterPlugin::parseArguments(int /* ac */, const char** av, int index) { SimpleString argument (av[index]); if (argument.contains("-pmemoryreport=")) { argument.replace("-pmemoryreport=", ""); destroyMemoryFormatter(formatter_); formatter_ = createMemoryFormatter(argument); return true; } return false; } MemoryReportFormatter* MemoryReporterPlugin::createMemoryFormatter(const SimpleString& type) { if (type == "normal") { return new NormalMemoryReportFormatter; } else if (type == "code") { return new CodeMemoryReportFormatter(StandardMallocAllocator::defaultAllocator()); } return NULL; } void MemoryReporterPlugin::destroyMemoryFormatter(MemoryReportFormatter* formatter) { delete formatter; } void MemoryReporterPlugin::setGlobalMemoryReportAllocators() { mallocAllocator.setRealAllocator(MemoryLeakAllocator::getCurrentMallocAllocator()); MemoryLeakAllocator::setCurrentMallocAllocator(&mallocAllocator); newAllocator.setRealAllocator(MemoryLeakAllocator::getCurrentNewAllocator()); MemoryLeakAllocator::setCurrentNewAllocator(&newAllocator); newArrayAllocator.setRealAllocator(MemoryLeakAllocator::getCurrentNewArrayAllocator()); MemoryLeakAllocator::setCurrentNewArrayAllocator(&newArrayAllocator); } void MemoryReporterPlugin::removeGlobalMemoryReportAllocators() { if (MemoryLeakAllocator::getCurrentNewAllocator() == &newAllocator) MemoryLeakAllocator::setCurrentNewAllocator(newAllocator.getRealAllocator()); if (MemoryLeakAllocator::getCurrentNewArrayAllocator() == &newArrayAllocator) MemoryLeakAllocator::setCurrentNewArrayAllocator(newArrayAllocator.getRealAllocator()); if (MemoryLeakAllocator::getCurrentMallocAllocator() == &mallocAllocator) MemoryLeakAllocator::setCurrentMallocAllocator(mallocAllocator.getRealAllocator()); } void MemoryReporterPlugin::initializeAllocator(MemoryReportAllocator* allocator, TestResult & result) { allocator->setFormatter(formatter_); allocator->setTestResult((&result)); } void MemoryReporterPlugin::preTestAction(Utest& test, TestResult& result) { if (formatter_ == NULL) return; initializeAllocator(&mallocAllocator, result); initializeAllocator(&newAllocator, result); initializeAllocator(&newArrayAllocator, result); setGlobalMemoryReportAllocators(); if (test.getGroup() != currentTestGroup_) { formatter_->report_testgroup_start(&result, test); currentTestGroup_ = test.getGroup(); } formatter_->report_test_start(&result, test); } void MemoryReporterPlugin::postTestAction(Utest& test, TestResult& result) { if (formatter_ == NULL) return; removeGlobalMemoryReportAllocators(); formatter_->report_test_end(&result, test); if (test.getNext()->getGroup() != currentTestGroup_) formatter_->report_testgroup_end(&result, test); }
null
282
cpp
blalor-cpputest
MockFailure.cpp
src/CppUTestExt/MockFailure.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockFailure.h" #include "CppUTestExt/MockExpectedFunctionCall.h" #include "CppUTestExt/MockExpectedFunctionsList.h" void MockFailureReporter::failTest(const MockFailure& failure) { getTestToFail()->getTestResult()->addFailure(failure); if (crashOnFailure_) UT_CRASH(); getTestToFail()->exitCurrentTest(); } Utest* MockFailureReporter::getTestToFail() { return Utest::getCurrent(); } MockFailure::MockFailure(Utest* test) : TestFailure(test, "Test failed with MockFailure without an error! Something went seriously wrong.") { } void MockFailure::addExpectationsAndCallHistory(const MockExpectedFunctionsList& expectations) { message_ += "\tEXPECTED calls that did NOT happen:\n"; message_ += expectations.unfulfilledFunctionsToString("\t\t"); message_ += "\n\tACTUAL calls that did happen (in call order):\n"; message_ += expectations.fulfilledFunctionsToString("\t\t"); } void MockFailure::addExpectationsAndCallHistoryRelatedTo(const SimpleString& name, const MockExpectedFunctionsList& expectations) { MockExpectedFunctionsList expectationsForFunction; expectationsForFunction.addExpectationsRelatedTo(name, expectations); message_ += "\tEXPECTED calls that DID NOT happen related to function: "; message_ += name; message_ += "\n"; message_ += expectationsForFunction.unfulfilledFunctionsToString("\t\t"); message_ += "\n\tACTUAL calls that DID happen related to function: "; message_ += name; message_ += "\n"; message_ += expectationsForFunction.fulfilledFunctionsToString("\t\t"); } MockExpectedCallsDidntHappenFailure::MockExpectedCallsDidntHappenFailure(Utest* test, const MockExpectedFunctionsList& expectations) : MockFailure(test) { message_ = "Mock Failure: Expected call did not happen.\n"; addExpectationsAndCallHistory(expectations); } MockUnexpectedCallHappenedFailure::MockUnexpectedCallHappenedFailure(Utest* test, const SimpleString& name, const MockExpectedFunctionsList& expectations) : MockFailure(test) { int amountOfExpectations = expectations.amountOfExpectationsFor(name); if (amountOfExpectations) message_ = StringFromFormat("Mock Failure: Unexpected additional (%dth) call to function: ", amountOfExpectations+1); else message_ = "Mock Failure: Unexpected call to function: "; message_ += name; message_ += "\n"; addExpectationsAndCallHistory(expectations); } MockCallOrderFailure::MockCallOrderFailure(Utest* test, const MockExpectedFunctionsList& expectations) : MockFailure(test) { message_ = "Mock Failure: Out of order calls"; message_ += "\n"; addExpectationsAndCallHistory(expectations); } MockUnexpectedParameterFailure::MockUnexpectedParameterFailure(Utest* test, const SimpleString& functionName, const MockNamedValue& parameter, const MockExpectedFunctionsList& expectations) : MockFailure(test) { MockExpectedFunctionsList expectationsForFunctionWithParameterName; expectationsForFunctionWithParameterName.addExpectationsRelatedTo(functionName, expectations); expectationsForFunctionWithParameterName.onlyKeepExpectationsWithParameterName(parameter.getName()); if (expectationsForFunctionWithParameterName.isEmpty()) { message_ = "Mock Failure: Unexpected parameter name to function \""; message_ += functionName; message_ += "\": "; message_ += parameter.getName(); } else { message_ = "Mock Failure: Unexpected parameter value to parameter \""; message_ += parameter.getName(); message_ += "\" to function \""; message_ += functionName; message_ += "\": <"; message_ += StringFrom(parameter); message_ += ">"; } message_ += "\n"; addExpectationsAndCallHistoryRelatedTo(functionName, expectations); message_ += "\n\tACTUAL unexpected parameter passed to function: "; message_ += functionName; message_ += "\n"; message_ += "\t\t"; message_ += parameter.getType(); message_ += " "; message_ += parameter.getName(); message_ += ": <"; message_ += StringFrom(parameter); message_ += ">"; } MockExpectedParameterDidntHappenFailure::MockExpectedParameterDidntHappenFailure(Utest* test, const SimpleString& functionName, const MockExpectedFunctionsList& expectations) : MockFailure(test) { MockExpectedFunctionsList expectationsForFunction; expectationsForFunction.addExpectationsRelatedTo(functionName, expectations); message_ = "Mock Failure: Expected parameter for function \""; message_ += functionName; message_ += "\" did not happen.\n"; addExpectationsAndCallHistoryRelatedTo(functionName, expectations); message_ += "\n\tMISSING parameters that didn't happen:\n"; message_ += "\t\t"; message_ += expectationsForFunction.missingParametersToString(); } MockNoWayToCompareCustomTypeFailure::MockNoWayToCompareCustomTypeFailure(Utest* test, const SimpleString& typeName) : MockFailure(test) { message_ = StringFromFormat("MockFailure: No way to compare type <%s>. Please install a ParameterTypeComparator.", typeName.asCharString()); } MockUnexpectedObjectFailure::MockUnexpectedObjectFailure(Utest* test, const SimpleString& functionName, void* actual, const MockExpectedFunctionsList& expectations) : MockFailure(test) { message_ = StringFromFormat ("MockFailure: Function called on a unexpected object: %s\n" "\tActual object for call has address: <%p>\n", functionName.asCharString(),actual); addExpectationsAndCallHistoryRelatedTo(functionName, expectations); } MockExpectedObjectDidntHappenFailure::MockExpectedObjectDidntHappenFailure(Utest* test, const SimpleString& functionName, const MockExpectedFunctionsList& expectations) : MockFailure(test) { message_ = StringFromFormat("Mock Failure: Expected call on object for function \"%s\" but it did not happen.\n", functionName.asCharString()); addExpectationsAndCallHistoryRelatedTo(functionName, expectations); }
null
283
cpp
blalor-cpputest
MockFunctionCall.cpp
src/CppUTestExt/MockFunctionCall.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockFunctionCall.h" #include "CppUTestExt/MockNamedValue.h" MockFunctionCall::MockFunctionCall() : comparatorRepository_(NULL) { } MockFunctionCall::~MockFunctionCall() { } void MockFunctionCall::setComparatorRepository(MockNamedValueComparatorRepository* repository) { comparatorRepository_ = repository; } void MockFunctionCall::setName(const SimpleString& name) { functionName_ = name; } SimpleString MockFunctionCall::getName() const { return functionName_; } MockNamedValueComparator* MockFunctionCall::getComparatorForType(const SimpleString& type) const { if (comparatorRepository_) return comparatorRepository_->getComparatorForType(type); return NULL; } struct MockFunctionCallCompositeNode { MockFunctionCallCompositeNode(MockFunctionCall& functionCall, MockFunctionCallCompositeNode* next) : next_(next), call_(functionCall){} MockFunctionCallCompositeNode* next_; MockFunctionCall& call_; }; MockFunctionCallComposite::MockFunctionCallComposite() : head_(NULL) { } MockFunctionCallComposite::~MockFunctionCallComposite() { } void MockFunctionCallComposite::add(MockFunctionCall& call) { head_ = new MockFunctionCallCompositeNode(call, head_); } void MockFunctionCallComposite::clear() { while (head_) { MockFunctionCallCompositeNode* next = head_->next_; delete head_; head_ = next; } } MockFunctionCall& MockFunctionCallComposite::withName(const SimpleString& name) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withName(name); return *this; } MockFunctionCall& MockFunctionCallComposite::withCallOrder(int) { FAIL("withCallOrder not supported for CompositeCalls"); return *this; } MockFunctionCall& MockFunctionCallComposite::withParameter(const SimpleString& name, int value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withParameter(name, value); return *this; } MockFunctionCall& MockFunctionCallComposite::withParameter(const SimpleString& name, double value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withParameter(name, value); return *this; } MockFunctionCall& MockFunctionCallComposite::withParameter(const SimpleString& name, const char* value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withParameter(name, value); return *this; } MockFunctionCall& MockFunctionCallComposite::withParameter(const SimpleString& name, void* value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withParameter(name, value); return *this; } MockFunctionCall& MockFunctionCallComposite::withParameterOfType(const SimpleString& typeName, const SimpleString& name, void* value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.withParameterOfType(typeName, name, value); return *this; } MockFunctionCall& MockFunctionCallComposite::ignoreOtherParameters() { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.ignoreOtherParameters(); return *this; } MockFunctionCall& MockFunctionCallComposite::andReturnValue(int value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.andReturnValue(value); return *this; } MockFunctionCall& MockFunctionCallComposite::MockFunctionCallComposite::andReturnValue(double value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.andReturnValue(value); return *this; } MockFunctionCall& MockFunctionCallComposite::andReturnValue(const char* value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.andReturnValue(value); return *this; } MockFunctionCall& MockFunctionCallComposite::andReturnValue(void* value) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.andReturnValue(value); return *this; } bool MockFunctionCallComposite::hasReturnValue() { return head_->call_.hasReturnValue(); } MockNamedValue MockFunctionCallComposite::returnValue() { return head_->call_.returnValue(); } MockFunctionCall& MockFunctionCallComposite::onObject(void* object) { for (MockFunctionCallCompositeNode* node = head_; node != NULL; node = node->next_) node->call_.onObject(object); return *this; } MockFunctionCallTrace::MockFunctionCallTrace() { } MockFunctionCallTrace::~MockFunctionCallTrace() { } MockFunctionCall& MockFunctionCallTrace::withName(const SimpleString& name) { traceBuffer_ += "\nFunction name: "; traceBuffer_ += name; return *this; } MockFunctionCall& MockFunctionCallTrace::withCallOrder(int callOrder) { traceBuffer_ += "\nwithCallOrder: "; traceBuffer_ += StringFrom(callOrder); return *this; } MockFunctionCall& MockFunctionCallTrace::withParameter(const SimpleString& name, int value) { traceBuffer_ += " "; traceBuffer_ += name; traceBuffer_ += ":"; traceBuffer_ += StringFrom(value); return *this; } MockFunctionCall& MockFunctionCallTrace::withParameter(const SimpleString& name, double value) { traceBuffer_ += " "; traceBuffer_ += name; traceBuffer_ += ":"; traceBuffer_ += StringFrom(value); return *this; } MockFunctionCall& MockFunctionCallTrace::withParameter(const SimpleString& name, const char* value) { traceBuffer_ += " "; traceBuffer_ += name; traceBuffer_ += ":"; traceBuffer_ += StringFrom(value); return *this; } MockFunctionCall& MockFunctionCallTrace::withParameter(const SimpleString& name, void* value) { traceBuffer_ += " "; traceBuffer_ += name; traceBuffer_ += ":"; traceBuffer_ += StringFrom(value); return *this; } MockFunctionCall& MockFunctionCallTrace::withParameterOfType(const SimpleString& typeName, const SimpleString& name, void* value) { traceBuffer_ += " "; traceBuffer_ += typeName; traceBuffer_ += " "; traceBuffer_ += name; traceBuffer_ += ":"; traceBuffer_ += StringFrom(value); return *this; } MockFunctionCall& MockFunctionCallTrace::ignoreOtherParameters() { return *this; } MockFunctionCall& MockFunctionCallTrace::andReturnValue(int) { return *this; } MockFunctionCall& MockFunctionCallTrace::andReturnValue(double) { return *this; } MockFunctionCall& MockFunctionCallTrace::andReturnValue(const char*) { return *this; } MockFunctionCall& MockFunctionCallTrace::andReturnValue(void*) { return *this; } bool MockFunctionCallTrace::hasReturnValue() { return false; } MockNamedValue MockFunctionCallTrace::returnValue() { return MockNamedValue(""); } MockFunctionCall& MockFunctionCallTrace::onObject(void* objectPtr) { traceBuffer_ += StringFrom(objectPtr); return *this; } void MockFunctionCallTrace::clear() { traceBuffer_ = ""; } const char* MockFunctionCallTrace::getTraceOutput() { return traceBuffer_.asCharString(); } MockFunctionCallTrace& MockFunctionCallTrace::instance() { static MockFunctionCallTrace call; return call; }
null
284
cpp
blalor-cpputest
MockSupport_c.cpp
src/CppUTestExt/MockSupport_c.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTestExt/MockSupport.h" extern "C" { #include "CppUTestExt/MockSupport_c.h" } #include <string.h> static MockSupport* currentMockSupport = NULL; static MockFunctionCall* currentCall = NULL; class MockCFunctionComparatorNode : public MockNamedValueComparator { public: MockCFunctionComparatorNode(MockCFunctionComparatorNode* next, MockTypeEqualFunction_c equal, MockTypeValueToStringFunction_c toString) : next_(next), equal_(equal), toString_(toString) {} virtual ~MockCFunctionComparatorNode() {}; virtual bool isEqual(void* object1, void* object2) { return (bool) equal_(object1, object2); } virtual SimpleString valueToString(void* object) { return SimpleString(toString_(object)); } MockCFunctionComparatorNode* next_; MockTypeEqualFunction_c equal_; MockTypeValueToStringFunction_c toString_; }; static MockCFunctionComparatorNode* comparatorList_ = NULL; extern "C" { MockFunctionCall_c* expectOneCall_c(const char* name); MockFunctionCall_c* actualCall_c(const char* name); void setIntData_c(const char* name, int value); void setDoubleData_c(const char* name, double value); void setStringData_c(const char* name, const char* value); void setPointerData_c(const char* name, void* value); void setDataObject_c(const char* name, const char* type, void* value); MockValue_c getData_c(const char* name); void checkExpectations_c(); int expectedCallsLeft_c(); void clear_c(); MockFunctionCall_c* withIntParameters_c(const char* name, int value); MockFunctionCall_c* withDoubleParameters_c(const char* name, double value); MockFunctionCall_c* withStringParameters_c(const char* name, const char* value); MockFunctionCall_c* withPointerParameters_c(const char* name, void* value); MockFunctionCall_c* withParameterOfType_c(const char* type, const char* name, void* value); MockFunctionCall_c* andReturnIntValue_c(int value); MockFunctionCall_c* andReturnDoubleValue_c(double value); MockFunctionCall_c* andReturnStringValue_c(const char* value); MockFunctionCall_c* andReturnPointerValue_c(void* value); MockValue_c returnValue_c(); void installComparator_c (const char* typeName, MockTypeEqualFunction_c isEqual, MockTypeValueToStringFunction_c valueToString) { comparatorList_ = new MockCFunctionComparatorNode(comparatorList_, isEqual, valueToString); currentMockSupport->installComparator(typeName, *comparatorList_); } void removeAllComparators_c() { while (comparatorList_) { MockCFunctionComparatorNode *next = comparatorList_->next_; delete comparatorList_; comparatorList_ = next; } currentMockSupport->removeAllComparators(); } static MockFunctionCall_c gFunctionCall = { withIntParameters_c, withDoubleParameters_c, withStringParameters_c, withPointerParameters_c, withParameterOfType_c, andReturnIntValue_c, andReturnDoubleValue_c, andReturnStringValue_c, andReturnPointerValue_c, returnValue_c }; static MockSupport_c gMockSupport = { expectOneCall_c, actualCall_c, returnValue_c, setIntData_c, setDoubleData_c, setStringData_c, setPointerData_c, setDataObject_c, getData_c, checkExpectations_c, expectedCallsLeft_c, clear_c, installComparator_c, removeAllComparators_c }; MockFunctionCall_c* withIntParameters_c(const char* name, int value) { currentCall = &currentCall->withParameter(name, value); return &gFunctionCall; } MockFunctionCall_c* withDoubleParameters_c(const char* name, double value) { currentCall = &currentCall->withParameter(name, value); return &gFunctionCall; } MockFunctionCall_c* withStringParameters_c(const char* name, const char* value) { currentCall = &currentCall->withParameter(name, value); return &gFunctionCall; } MockFunctionCall_c* withPointerParameters_c(const char* name, void* value) { currentCall = &currentCall->withParameter(name, value); return &gFunctionCall; } MockFunctionCall_c* withParameterOfType_c(const char* type, const char* name, void* value) { currentCall = &currentCall->withParameterOfType(type, name, value); return &gFunctionCall; } MockFunctionCall_c* andReturnIntValue_c(int value) { currentCall = &currentCall->andReturnValue(value); return &gFunctionCall; } MockFunctionCall_c* andReturnDoubleValue_c(double value) { currentCall = &currentCall->andReturnValue(value); return &gFunctionCall; } MockFunctionCall_c* andReturnStringValue_c(const char* value) { currentCall = &currentCall->andReturnValue(value); return &gFunctionCall; } MockFunctionCall_c* andReturnPointerValue_c(void* value) { currentCall = &currentCall->andReturnValue(value); return &gFunctionCall; } static MockValue_c getMockValueCFromNamedValue(const MockNamedValue& namedValue) { MockValue_c returnValue; if (strcmp(namedValue.getType().asCharString(), "int") == 0) { returnValue.type = MOCKVALUETYPE_INTEGER; returnValue.value.intValue = namedValue.getIntValue(); } else if (strcmp(namedValue.getType().asCharString(), "double") == 0) { returnValue.type = MOCKVALUETYPE_DOUBLE; returnValue.value.doubleValue = namedValue.getDoubleValue(); } else if (strcmp(namedValue.getType().asCharString(), "char*") == 0) { returnValue.type = MOCKVALUETYPE_STRING; returnValue.value.stringValue = namedValue.getStringValue(); } else if (strcmp(namedValue.getType().asCharString(), "void*") == 0) { returnValue.type = MOCKVALUETYPE_POINTER; returnValue.value.pointerValue = namedValue.getPointerValue(); } else { returnValue.type = MOCKVALUETYPE_OBJECT; returnValue.value.objectValue = namedValue.getObjectPointer(); } return returnValue; } MockValue_c returnValue_c() { return getMockValueCFromNamedValue(currentCall->returnValue()); } MockFunctionCall_c* expectOneCall_c(const char* name) { currentCall = &currentMockSupport->expectOneCall(name); return &gFunctionCall; } MockFunctionCall_c* actualCall_c(const char* name) { currentCall = &currentMockSupport->actualCall(name); return &gFunctionCall; } void setIntData_c(const char* name, int value) { return currentMockSupport->setData(name, value); } void setDoubleData_c(const char* name, double value) { return currentMockSupport->setData(name, value); } void setStringData_c(const char* name, const char* value) { return currentMockSupport->setData(name, value); } void setPointerData_c(const char* name, void* value) { return currentMockSupport->setData(name, value); } void setDataObject_c(const char* name, const char* type, void* value) { return currentMockSupport->setDataObject(name, type, value); } MockValue_c getData_c(const char* name) { return getMockValueCFromNamedValue(currentMockSupport->getData(name)); } void checkExpectations_c() { currentMockSupport->checkExpectations(); } int expectedCallsLeft_c() { return currentMockSupport->expectedCallsLeft(); } void clear_c() { currentMockSupport->clear(); } MockSupport_c* mock_c() { currentMockSupport = &mock(); return &gMockSupport; } MockSupport_c* mock_scope_c(const char* scope) { currentMockSupport = &mock(scope); return &gMockSupport; } }
null
285
cpp
blalor-cpputest
MockNamedValue.cpp
src/CppUTestExt/MockNamedValue.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockNamedValue.h" #include "CppUTest/PlatformSpecificFunctions.h" MockNamedValue::MockNamedValue(const SimpleString& name) : name_(name), type_("int"), comparator_(NULL) { value_.intValue_ = 0; } MockNamedValue::~MockNamedValue() { } void MockNamedValue::setValue(int value) { type_ = "int"; value_.intValue_ = value; } void MockNamedValue::setValue(double value) { type_ = "double"; value_.doubleValue_ = value; } void MockNamedValue::setValue(void* value) { type_ = "void*"; value_.pointerValue_ = value; } void MockNamedValue::setValue(const char* value) { type_ = "char*"; value_.stringValue_ = value; } void MockNamedValue::setObjectPointer(const SimpleString& type, void* objectPtr) { type_ = type; value_.objectPointerValue_ = objectPtr; } void MockNamedValue::setName(const char* name) { name_ = name; } SimpleString MockNamedValue::getName() const { return name_; } SimpleString MockNamedValue::getType() const { return type_; } int MockNamedValue::getIntValue() const { STRCMP_EQUAL("int", type_.asCharString()); return value_.intValue_; } double MockNamedValue::getDoubleValue() const { STRCMP_EQUAL("double", type_.asCharString()); return value_.doubleValue_; } const char* MockNamedValue::getStringValue() const { STRCMP_EQUAL("char*", type_.asCharString()); return value_.stringValue_; } void* MockNamedValue::getPointerValue() const { STRCMP_EQUAL("void*", type_.asCharString()); return value_.pointerValue_; } void* MockNamedValue::getObjectPointer() const { return value_.objectPointerValue_; } void MockNamedValue::setComparator(MockNamedValueComparator* comparator) { comparator_ = comparator; } bool MockNamedValue::equals(const MockNamedValue& p) const { if (type_ != p.type_) return false; if (type_ == "int") return value_.intValue_ == p.value_.intValue_; else if (type_ == "char*") return SimpleString(value_.stringValue_) == SimpleString(p.value_.stringValue_); else if (type_ == "void*") return value_.pointerValue_ == p.value_.pointerValue_; else if (type_ == "double") return (doubles_equal(value_.doubleValue_, p.value_.doubleValue_, 0.005)); if (comparator_) return comparator_->isEqual(value_.objectPointerValue_, p.value_.objectPointerValue_); return false; } SimpleString MockNamedValue::toString() const { if (type_ == "int") return StringFrom(value_.intValue_); else if (type_ == "char*") return value_.stringValue_; else if (type_ == "void*") return StringFrom(value_.pointerValue_); else if (type_ == "double") return StringFrom(value_.doubleValue_); if (comparator_) return comparator_->valueToString(value_.objectPointerValue_); return StringFromFormat("No comparator found for type: \"%s\"", type_.asCharString()); } void MockNamedValueListNode::setNext(MockNamedValueListNode* node) { next_ = node; } MockNamedValueListNode* MockNamedValueListNode::next() { return next_; } MockNamedValue* MockNamedValueListNode::item() { return data_; } void MockNamedValueListNode::destroy() { delete data_; } MockNamedValueListNode::MockNamedValueListNode(MockNamedValue* newValue) : data_(newValue), next_(NULL) { } SimpleString MockNamedValueListNode::getName() const { return data_->getName(); } SimpleString MockNamedValueListNode::getType() const { return data_->getType(); } MockNamedValueList::MockNamedValueList() : head_(NULL) { } void MockNamedValueList::clear() { while (head_) { MockNamedValueListNode* n = head_->next(); head_->destroy(); delete head_; head_ = n; } } void MockNamedValueList::add(MockNamedValue* newValue) { MockNamedValueListNode* newNode = new MockNamedValueListNode(newValue); if (head_ == NULL) head_ = newNode; else { MockNamedValueListNode* lastNode = head_; while (lastNode->next()) lastNode = lastNode->next(); lastNode->setNext(newNode); } } MockNamedValue* MockNamedValueList::getValueByName(const SimpleString& name) { for (MockNamedValueListNode * p = head_; p; p = p->next()) if (p->getName() == name) return p->item(); return NULL; } MockNamedValueListNode* MockNamedValueList::begin() { return head_; } struct MockNamedValueComparatorRepositoryNode { MockNamedValueComparatorRepositoryNode(const SimpleString& name, MockNamedValueComparator& comparator, MockNamedValueComparatorRepositoryNode* next) : name_(name), comparator_(comparator), next_(next) {}; SimpleString name_; MockNamedValueComparator& comparator_; MockNamedValueComparatorRepositoryNode* next_; }; MockNamedValueComparatorRepository::MockNamedValueComparatorRepository() : head_(NULL) { } MockNamedValueComparatorRepository::~MockNamedValueComparatorRepository() { clear(); } void MockNamedValueComparatorRepository::clear() { while (head_) { MockNamedValueComparatorRepositoryNode* next = head_->next_; delete head_; head_ = next; } } void MockNamedValueComparatorRepository::installComparator(const SimpleString& name, MockNamedValueComparator& comparator) { head_ = new MockNamedValueComparatorRepositoryNode(name, comparator, head_); } MockNamedValueComparator* MockNamedValueComparatorRepository::getComparatorForType(const SimpleString& name) { for (MockNamedValueComparatorRepositoryNode* p = head_; p; p = p->next_) if (p->name_ == name) return &p->comparator_; return NULL;; } void MockNamedValueComparatorRepository::installComparators(const MockNamedValueComparatorRepository& repository) { for (MockNamedValueComparatorRepositoryNode* p = repository.head_; p; p = p->next_) installComparator(p->name_, p->comparator_); }
null
286
cpp
blalor-cpputest
MockSupport.cpp
src/CppUTestExt/MockSupport.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" #include "CppUTestExt/MockActualFunctionCall.h" #include "CppUTestExt/MockExpectedFunctionCall.h" #include "CppUTestExt/MockFailure.h" #define MOCK_SUPPORT_SCOPE_PREFIX "!!!$$$MockingSupportScope$$$!!!" static MockSupport global_mock; int MockSupport::callOrder_ = 0; int MockSupport::expectedCallOrder_ = 0; MockSupport& mock(const SimpleString& mockName) { if (mockName != "") return *global_mock.getMockSupportScope(mockName); return global_mock; } MockSupport::MockSupport() : strictOrdering_(false), reporter_(&defaultReporter_), ignoreOtherCalls_(false), enabled_(true), lastActualFunctionCall_(NULL), tracing_(false) { } MockSupport::~MockSupport() { } void MockSupport::crashOnFailure() { reporter_->crashOnFailure(); } void MockSupport::setMockFailureReporter(MockFailureReporter* reporter) { reporter_ = (reporter != NULL) ? reporter : &defaultReporter_; if (lastActualFunctionCall_) lastActualFunctionCall_->setMockFailureReporter(reporter_); for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->setMockFailureReporter(reporter_); } void MockSupport::installComparator(const SimpleString& typeName, MockNamedValueComparator& comparator) { comparatorRepository_.installComparator(typeName, comparator); for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->installComparator(typeName, comparator); } void MockSupport::installComparators(const MockNamedValueComparatorRepository& repository) { comparatorRepository_.installComparators(repository); for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->installComparators(repository); } void MockSupport::removeAllComparators() { comparatorRepository_.clear(); for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->removeAllComparators(); } void MockSupport::clear() { delete lastActualFunctionCall_; lastActualFunctionCall_ = NULL; tracing_ = false; MockFunctionCallTrace::instance().clear(); expectations_.deleteAllExpectationsAndClearList(); compositeCalls_.clear(); ignoreOtherCalls_ = false; enabled_ = true; callOrder_ = 0; expectedCallOrder_ = 0; strictOrdering_ = false; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) { MockSupport* support = getMockSupport(p); if (support) { support->clear(); delete support; } } data_.clear(); } void MockSupport::strictOrder() { strictOrdering_ = true; } MockFunctionCall& MockSupport::expectOneCall(const SimpleString& functionName) { if (!enabled_) return MockIgnoredCall::instance(); MockExpectedFunctionCall* call = new MockExpectedFunctionCall; call->setComparatorRepository(&comparatorRepository_); call->withName(functionName); if (strictOrdering_) call->withCallOrder(++expectedCallOrder_); expectations_.addExpectedCall(call); return *call; } MockFunctionCall& MockSupport::expectNCalls(int amount, const SimpleString& functionName) { compositeCalls_.clear(); for (int i = 0; i < amount; i++) compositeCalls_.add(expectOneCall(functionName)); return compositeCalls_; } MockActualFunctionCall* MockSupport::createActualFunctionCall() { lastActualFunctionCall_ = new MockActualFunctionCall(++callOrder_, reporter_, expectations_); return lastActualFunctionCall_; } MockFunctionCall& MockSupport::actualCall(const SimpleString& functionName) { if (lastActualFunctionCall_) { lastActualFunctionCall_->checkExpectations(); delete lastActualFunctionCall_; lastActualFunctionCall_ = NULL; } if (!enabled_) return MockIgnoredCall::instance(); if (tracing_) return MockFunctionCallTrace::instance().withName(functionName); if (!expectations_.hasExpectationWithName(functionName) && ignoreOtherCalls_) { return MockIgnoredCall::instance(); } MockActualFunctionCall* call = createActualFunctionCall(); call->setComparatorRepository(&comparatorRepository_); call->withName(functionName); return *call; } void MockSupport::ignoreOtherCalls() { ignoreOtherCalls_ = true; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->ignoreOtherCalls(); } void MockSupport::disable() { enabled_ = false; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->disable(); } void MockSupport::enable() { enabled_ = true; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->enable(); } void MockSupport::tracing(bool enabled) { tracing_ = enabled; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) getMockSupport(p)->tracing(enabled); } const char* MockSupport::getTraceOutput() { return MockFunctionCallTrace::instance().getTraceOutput(); } bool MockSupport::expectedCallsLeft() { int callsLeft = expectations_.hasUnfullfilledExpectations(); for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p)) callsLeft += getMockSupport(p)->expectedCallsLeft(); return callsLeft; } bool MockSupport::wasLastCallFulfilled() { if (lastActualFunctionCall_ && !lastActualFunctionCall_->isFulfilled()) return false; for (MockNamedValueListNode* p = data_.begin(); p; p = p->next()) if (getMockSupport(p) && !getMockSupport(p)->wasLastCallFulfilled()) return false; return true; } void MockSupport::failTestWithUnexpectedCalls() { MockExpectedFunctionsList expectationsList; expectationsList.addExpectations(expectations_); for(MockNamedValueListNode *p = data_.begin();p;p = p->next()) if(getMockSupport(p)) expectationsList.addExpectations(getMockSupport(p)->expectations_); MockExpectedCallsDidntHappenFailure failure(reporter_->getTestToFail(), expectationsList); clear(); reporter_->failTest(failure); } void MockSupport::failTestWithOutOfOrderCalls() { MockExpectedFunctionsList expectationsList; expectationsList.addExpectations(expectations_); for(MockNamedValueListNode *p = data_.begin();p;p = p->next()) if(getMockSupport(p)) expectationsList.addExpectations(getMockSupport(p)->expectations_); MockCallOrderFailure failure(reporter_->getTestToFail(), expectationsList); clear(); reporter_->failTest(failure); } void MockSupport::checkExpectationsOfLastCall() { if(lastActualFunctionCall_) lastActualFunctionCall_->checkExpectations(); for(MockNamedValueListNode *p = data_.begin();p;p = p->next()) if(getMockSupport(p) && getMockSupport(p)->lastActualFunctionCall_) getMockSupport(p)->lastActualFunctionCall_->checkExpectations(); } void MockSupport::checkExpectations() { checkExpectationsOfLastCall(); if (wasLastCallFulfilled() && expectedCallsLeft()) failTestWithUnexpectedCalls(); if (expectations_.hasCallsOutOfOrder()) failTestWithOutOfOrderCalls(); } bool MockSupport::hasData(const SimpleString& name) { return data_.getValueByName(name) != NULL; } MockNamedValue* MockSupport::retrieveDataFromStore(const SimpleString& name) { MockNamedValue* newData = data_.getValueByName(name); if (newData == NULL) { newData = new MockNamedValue(name); data_.add(newData); } return newData; } void MockSupport::setData(const SimpleString& name, int value) { MockNamedValue* newData = retrieveDataFromStore(name); newData->setValue(value); } void MockSupport::setData(const SimpleString& name, const char* value) { MockNamedValue* newData = retrieveDataFromStore(name); newData->setValue(value); } void MockSupport::setData(const SimpleString& name, double value) { MockNamedValue* newData = retrieveDataFromStore(name); newData->setValue(value); } void MockSupport::setData(const SimpleString& name, void* value) { MockNamedValue* newData = retrieveDataFromStore(name); newData->setValue(value); } void MockSupport::setDataObject(const SimpleString& name, const SimpleString& type, void* value) { MockNamedValue* newData = retrieveDataFromStore(name); newData->setObjectPointer(type, value); } MockNamedValue MockSupport::getData(const SimpleString& name) { MockNamedValue* value = data_.getValueByName(name); if (value == NULL) return MockNamedValue(""); return *value; } MockSupport* MockSupport::getMockSupportScope(const SimpleString& name) { SimpleString mockingSupportName = MOCK_SUPPORT_SCOPE_PREFIX; mockingSupportName += name; if (hasData(mockingSupportName)) { STRCMP_EQUAL("MockSupport", getData(mockingSupportName).getType().asCharString()); return (MockSupport*) getData(mockingSupportName).getObjectPointer(); } MockSupport *newMock = new MockSupport; newMock->setMockFailureReporter(reporter_); if (ignoreOtherCalls_) newMock->ignoreOtherCalls(); if (!enabled_) newMock->disable(); newMock->tracing(tracing_); newMock->installComparators(comparatorRepository_); setDataObject(mockingSupportName, "MockSupport", newMock); return newMock; } MockSupport* MockSupport::getMockSupport(MockNamedValueListNode* node) { if (node->getType() == "MockSupport" && node->getName().contains(MOCK_SUPPORT_SCOPE_PREFIX)) return (MockSupport*) node->item()->getObjectPointer(); return NULL; } MockNamedValue MockSupport::returnValue() { if (lastActualFunctionCall_) return lastActualFunctionCall_->returnValue(); return MockNamedValue(""); } int MockSupport::intReturnValue() { return returnValue().getIntValue(); } const char* MockSupport::stringReturnValue() { return returnValue().getStringValue(); } double MockSupport::doubleReturnValue() { return returnValue().getDoubleValue(); } void* MockSupport::pointerReturnValue() { return returnValue().getPointerValue(); } bool MockSupport::hasReturnValue() { if (lastActualFunctionCall_) return lastActualFunctionCall_->hasReturnValue(); return false; }
null
287
cpp
blalor-cpputest
MockSupportPlugin.cpp
src/CppUTestExt/MockSupportPlugin.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" #include "CppUTestExt/MockSupportPlugin.h" class MockSupportPluginReporter : public MockFailureReporter { Utest& test_; TestResult& result_; public: MockSupportPluginReporter(Utest& test, TestResult& result) : test_(test), result_(result) { } virtual void failTest(const MockFailure& failure) { result_.addFailure(failure); } virtual Utest* getTestToFail() { return &test_; } }; MockSupportPlugin::MockSupportPlugin(const SimpleString& name) : TestPlugin(name) { } MockSupportPlugin::~MockSupportPlugin() { repository_.clear(); } void MockSupportPlugin::preTestAction(Utest&, TestResult&) { mock().installComparators(repository_); } void MockSupportPlugin::postTestAction(Utest& test, TestResult& result) { MockSupportPluginReporter reporter(test, result); mock().setMockFailureReporter(&reporter); mock().checkExpectations(); mock().clear(); mock().setMockFailureReporter(NULL); mock().removeAllComparators(); } void MockSupportPlugin::installComparator(const SimpleString& name, MockNamedValueComparator& comparator) { repository_.installComparator(name, comparator); }
null
288
cpp
blalor-cpputest
OrderedTest.cpp
src/CppUTestExt/OrderedTest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/OrderedTest.h" OrderedTest* OrderedTest::_orderedTestsHead = 0; OrderedTest::OrderedTest() : _nextOrderedTest(0) { } OrderedTest::~OrderedTest() { } int OrderedTest::getLevel() { return _level; } void OrderedTest::setLevel(int level) { _level = level; } void OrderedTest::setOrderedTestHead(OrderedTest* test) { _orderedTestsHead = test; } OrderedTest* OrderedTest::getOrderedTestHead() { return _orderedTestsHead; } bool OrderedTest::firstOrderedTest() { return (getOrderedTestHead() == 0); } OrderedTest* OrderedTest::addOrderedTest(OrderedTest* test) { Utest::addTest(test); _nextOrderedTest = test; return this; } void OrderedTest::addOrderedTestToHead(OrderedTest* test) { TestRegistry *reg = TestRegistry::getCurrentRegistry(); if (reg->getFirstTest()->isNull() || getOrderedTestHead() == reg->getFirstTest()) reg->addTest(test); else reg->getTestWithNext(getOrderedTestHead())->addTest(test); test->_nextOrderedTest = getOrderedTestHead(); setOrderedTestHead(test); } OrderedTest* OrderedTest::getNextOrderedTest() { return _nextOrderedTest; } OrderedTestInstaller::OrderedTestInstaller(OrderedTest* test, const char* groupName, const char* testName, const char* fileName, int lineNumber, int level) { test->setTestName(testName); test->setGroupName(groupName); test->setFileName(fileName); test->setLineNumber(lineNumber); test->setLevel(level); if (OrderedTest::firstOrderedTest()) OrderedTest::addOrderedTestToHead(test); else addOrderedTestInOrder(test); } void OrderedTestInstaller::addOrderedTestInOrder(OrderedTest* test) { if (test->getLevel() < OrderedTest::getOrderedTestHead()->getLevel()) OrderedTest::addOrderedTestToHead( test); else addOrderedTestInOrderNotAtHeadPosition(test); } void OrderedTestInstaller::addOrderedTestInOrderNotAtHeadPosition( OrderedTest* test) { OrderedTest* current = OrderedTest::getOrderedTestHead(); while (current->getNextOrderedTest()) { if (current->getNextOrderedTest()->getLevel() > test->getLevel()) { test->addOrderedTest(current->getNextOrderedTest()); current->addOrderedTest(test); return; } current = current->getNextOrderedTest(); } test->addOrderedTest(current->getNextOrderedTest()); current->addOrderedTest(test); } OrderedTestInstaller::~OrderedTestInstaller() { }
null
289
cpp
blalor-cpputest
MemoryReportAllocator.cpp
src/CppUTestExt/MemoryReportAllocator.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MemoryReportAllocator.h" #include "CppUTestExt/MemoryReportFormatter.h" MemoryReportAllocator::MemoryReportAllocator() : result_(NULL), realAllocator_(NULL), formatter_(NULL) { } MemoryReportAllocator::~MemoryReportAllocator() { } const char* MemoryReportAllocator::name() { return realAllocator_->name(); } const char* MemoryReportAllocator::alloc_name() { return realAllocator_->alloc_name(); } const char* MemoryReportAllocator::free_name() { return realAllocator_->free_name(); } void MemoryReportAllocator::setRealAllocator(MemoryLeakAllocator* allocator) { realAllocator_ = allocator; } bool MemoryReportAllocator::allocateMemoryLeakNodeSeparately() { return realAllocator_->allocateMemoryLeakNodeSeparately(); } MemoryLeakAllocator* MemoryReportAllocator::getRealAllocator() { return realAllocator_; } void MemoryReportAllocator::setTestResult(TestResult* result) { result_ = result; } void MemoryReportAllocator::setFormatter(MemoryReportFormatter* formatter) { formatter_ = formatter; } char* MemoryReportAllocator::alloc_memory(size_t size, const char* file, int line) { char* memory = realAllocator_->alloc_memory(size, file, line); if (result_ && formatter_) formatter_->report_alloc_memory(result_, this, size, memory, file, line); return memory; } void MemoryReportAllocator::free_memory(char* memory, const char* file, int line) { realAllocator_->free_memory(memory, file, line); if (result_ && formatter_) formatter_->report_free_memory(result_, this, memory, file, line); }
null
290
cpp
blalor-cpputest
MockExpectedFunctionsList.cpp
src/CppUTestExt/MockExpectedFunctionsList.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockExpectedFunctionsList.h" #include "CppUTestExt/MockExpectedFunctionCall.h" MockExpectedFunctionsList::MockExpectedFunctionsList() : head_(NULL) { } MockExpectedFunctionsList::~MockExpectedFunctionsList() { while (head_) { MockExpectedFunctionsListNode* next = head_->next_; delete head_; head_ = next; } } bool MockExpectedFunctionsList::hasCallsOutOfOrder() const { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (p->expectedCall_->isOutOfOrder()) return true; return false; } int MockExpectedFunctionsList::size() const { int count = 0; for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) count++; return count; } bool MockExpectedFunctionsList::isEmpty() const { return size() == 0; } int MockExpectedFunctionsList::amountOfExpectationsFor(const SimpleString& name) const { int count = 0; for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (p->expectedCall_->relatesTo(name)) count++; return count; } int MockExpectedFunctionsList::amountOfUnfulfilledExpectations() const { int count = 0; for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->isFulfilled()) count++; return count; } bool MockExpectedFunctionsList::hasFulfilledExpectations() const { return (size() - amountOfUnfulfilledExpectations()) != 0; } bool MockExpectedFunctionsList::hasUnfullfilledExpectations() const { return amountOfUnfulfilledExpectations() != 0; } bool MockExpectedFunctionsList::hasExpectationWithName(const SimpleString& name) const { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (p->expectedCall_->relatesTo(name)) return true; return false; } void MockExpectedFunctionsList::addExpectedCall(MockExpectedFunctionCall* call) { MockExpectedFunctionsListNode* newCall = new MockExpectedFunctionsListNode(call); if (head_ == NULL) head_ = newCall; else { MockExpectedFunctionsListNode* lastCall = head_; while (lastCall->next_) lastCall = lastCall->next_; lastCall->next_ = newCall; } } void MockExpectedFunctionsList::addUnfilfilledExpectations(const MockExpectedFunctionsList& list) { for (MockExpectedFunctionsListNode* p = list.head_; p; p = p->next_) if (! p->expectedCall_->isFulfilled()) addExpectedCall(p->expectedCall_); } void MockExpectedFunctionsList::addExpectationsRelatedTo(const SimpleString& name, const MockExpectedFunctionsList& list) { for (MockExpectedFunctionsListNode* p = list.head_; p; p = p->next_) if (p->expectedCall_->relatesTo(name)) addExpectedCall(p->expectedCall_); } void MockExpectedFunctionsList::addExpectations(const MockExpectedFunctionsList& list) { for (MockExpectedFunctionsListNode* p = list.head_; p; p = p->next_) addExpectedCall(p->expectedCall_); } void MockExpectedFunctionsList::onlyKeepExpectationsRelatedTo(const SimpleString& name) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->relatesTo(name)) p->expectedCall_ = NULL; pruneEmptyNodeFromList(); } void MockExpectedFunctionsList::onlyKeepUnfulfilledExpectations() { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (p->expectedCall_->isFulfilled()) p->expectedCall_ = NULL; pruneEmptyNodeFromList(); } void MockExpectedFunctionsList::onlyKeepUnfulfilledExpectationsRelatedTo(const SimpleString& name) { onlyKeepUnfulfilledExpectations(); onlyKeepExpectationsRelatedTo(name); } void MockExpectedFunctionsList::onlyKeepExpectationsWithParameterName(const SimpleString& name) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->hasParameterWithName(name)) p->expectedCall_ = NULL; pruneEmptyNodeFromList(); } void MockExpectedFunctionsList::onlyKeepExpectationsWithParameter(const MockNamedValue& parameter) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->hasParameter(parameter)) p->expectedCall_ = NULL; pruneEmptyNodeFromList(); } void MockExpectedFunctionsList::onlyKeepExpectationsOnObject(void* objectPtr) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->relatesToObject(objectPtr)) p->expectedCall_ = NULL; pruneEmptyNodeFromList(); } void MockExpectedFunctionsList::onlyKeepUnfulfilledExpectationsWithParameter(const MockNamedValue& parameter) { onlyKeepUnfulfilledExpectations(); onlyKeepExpectationsWithParameter(parameter); } void MockExpectedFunctionsList::onlyKeepUnfulfilledExpectationsOnObject(void* objectPtr) { onlyKeepUnfulfilledExpectations(); onlyKeepExpectationsOnObject(objectPtr); } MockExpectedFunctionCall* MockExpectedFunctionsList::removeOneFulfilledExpectation() { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) { if (p->expectedCall_->isFulfilled()) { MockExpectedFunctionCall* fulfilledCall = p->expectedCall_; p->expectedCall_ = NULL; pruneEmptyNodeFromList(); return fulfilledCall; } } return NULL; } MockExpectedFunctionCall* MockExpectedFunctionsList::removeOneFulfilledExpectationWithIgnoredParameters() { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) { if (p->expectedCall_->isFulfilledWithoutIgnoredParameters()) { MockExpectedFunctionCall* fulfilledCall = p->expectedCall_; p->expectedCall_->parametersWereIgnored(); p->expectedCall_ = NULL; pruneEmptyNodeFromList(); return fulfilledCall; } } return NULL; } void MockExpectedFunctionsList::pruneEmptyNodeFromList() { MockExpectedFunctionsListNode* current = head_; MockExpectedFunctionsListNode* previous = NULL; MockExpectedFunctionsListNode* toBeDeleted = NULL; while (current) { if (current->expectedCall_ == NULL) { toBeDeleted = current; if (previous == NULL) head_ = current = current->next_; else current = previous->next_ = current->next_; delete toBeDeleted; } else { previous = current; current = current->next_; } } } void MockExpectedFunctionsList::deleteAllExpectationsAndClearList() { while (head_) { MockExpectedFunctionsListNode* next = head_->next_; delete head_->expectedCall_; delete head_; head_ = next; } } void MockExpectedFunctionsList::resetExpectations() { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) p->expectedCall_->resetExpectation(); } void MockExpectedFunctionsList::callWasMade(int callOrder) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) p->expectedCall_->callWasMade(callOrder); } void MockExpectedFunctionsList::wasPassedToObject() { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) p->expectedCall_->wasPassedToObject(); } void MockExpectedFunctionsList::parameterWasPassed(const SimpleString& parameterName) { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) p->expectedCall_->parameterWasPassed(parameterName); } MockExpectedFunctionsList::MockExpectedFunctionsListNode* MockExpectedFunctionsList::findNodeWithCallOrderOf(int callOrder) const { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (p->expectedCall_->getCallOrder() == callOrder && p->expectedCall_->isFulfilled()) return p; return NULL; } SimpleString stringOrNoneTextWhenEmpty(const SimpleString& inputString, const SimpleString& linePrefix) { SimpleString str = inputString; if (str == "") { str += linePrefix; str += "<none>"; } return str; } SimpleString appendStringOnANewLine(const SimpleString& inputString, const SimpleString& linePrefix, const SimpleString& stringToAppend) { SimpleString str = inputString; if (str != "") str += "\n"; str += linePrefix; str += stringToAppend; return str; } SimpleString MockExpectedFunctionsList::unfulfilledFunctionsToString(const SimpleString& linePrefix) const { SimpleString str; for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (!p->expectedCall_->isFulfilled()) str = appendStringOnANewLine(str, linePrefix, p->expectedCall_->callToString()); return stringOrNoneTextWhenEmpty(str, linePrefix); } SimpleString MockExpectedFunctionsList::fulfilledFunctionsToString(const SimpleString& linePrefix) const { SimpleString str; MockExpectedFunctionsListNode* nextNodeInOrder = head_; for (int callOrder = 1; (nextNodeInOrder = findNodeWithCallOrderOf(callOrder)); callOrder++) if (nextNodeInOrder) str = appendStringOnANewLine(str, linePrefix, nextNodeInOrder->expectedCall_->callToString()); return stringOrNoneTextWhenEmpty(str, linePrefix); } SimpleString MockExpectedFunctionsList::missingParametersToString() const { SimpleString str; for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->isFulfilled()) str = appendStringOnANewLine(str, "", p->expectedCall_->missingParametersToString()); return stringOrNoneTextWhenEmpty(str, ""); } bool MockExpectedFunctionsList::hasUnfulfilledExpectationsBecauseOfMissingParameters() const { for (MockExpectedFunctionsListNode* p = head_; p; p = p->next_) if (! p->expectedCall_->areParametersFulfilled()) return true; return false; }
null
291
cpp
blalor-cpputest
CodeMemoryReportFormatter.cpp
src/CppUTestExt/CodeMemoryReportFormatter.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/CodeMemoryReportFormatter.h" #include "CppUTestExt/MemoryReportAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" #define MAX_VARIABLE_NAME_LINE_PART 10 #define MAX_VARIABLE_NAME_FILE_PART 53 #define MAX_VARIABLE_NAME_SEPERATOR_PART 1 #define MAX_VARIABLE_NAME_LENGTH MAX_VARIABLE_NAME_FILE_PART + MAX_VARIABLE_NAME_SEPERATOR_PART + MAX_VARIABLE_NAME_LINE_PART struct CodeReportingAllocationNode { char variableName_[MAX_VARIABLE_NAME_LENGTH + 1]; void* memory_; CodeReportingAllocationNode* next_; }; CodeMemoryReportFormatter::CodeMemoryReportFormatter(MemoryLeakAllocator* internalAllocator) : codeReportingList_(NULL), internalAllocator_(internalAllocator) { } CodeMemoryReportFormatter::~CodeMemoryReportFormatter() { clearReporting(); } void CodeMemoryReportFormatter::clearReporting() { while (codeReportingList_) { CodeReportingAllocationNode* oldNode = codeReportingList_; codeReportingList_ = codeReportingList_->next_; internalAllocator_->free_memory((char*) oldNode, __FILE__, __LINE__); } } void CodeMemoryReportFormatter::addNodeToList(const char* variableName, void* memory, CodeReportingAllocationNode* next) { CodeReportingAllocationNode* newNode = (CodeReportingAllocationNode*) internalAllocator_->alloc_memory(sizeof(CodeReportingAllocationNode), __FILE__, __LINE__); newNode->memory_ = memory; newNode->next_ = next; PlatformSpecificStrNCpy(newNode->variableName_, variableName, MAX_VARIABLE_NAME_LENGTH); codeReportingList_ = newNode; } CodeReportingAllocationNode* CodeMemoryReportFormatter::findNode(void* memory) { CodeReportingAllocationNode* current = codeReportingList_; while (current && current->memory_ != memory) { current = current->next_; } return current; } static SimpleString extractFileNameFromPath(const char* file) { const char* fileNameOnly = file + PlatformSpecificStrLen(file); while (fileNameOnly != file && *fileNameOnly != '/') fileNameOnly--; if (*fileNameOnly == '/') fileNameOnly++; return fileNameOnly; } SimpleString CodeMemoryReportFormatter::createVariableNameFromFileLineInfo(const char *file, int line) { SimpleString fileNameOnly = extractFileNameFromPath(file); fileNameOnly.replace(".", "_"); for (int i = 1; i < 100000; i++) { SimpleString variableName = StringFromFormat("%s_%d_%d", fileNameOnly.asCharString(), line, i); if (!variableExists(variableName)) return variableName; } return ""; } bool CodeMemoryReportFormatter::isNewAllocator(MemoryLeakAllocator* allocator) { return PlatformSpecificStrCmp(allocator->alloc_name(), StandardNewAllocator::defaultAllocator()->alloc_name()) == 0 || PlatformSpecificStrCmp(allocator->alloc_name(), StandardNewArrayAllocator::defaultAllocator()->alloc_name()) == 0; } bool CodeMemoryReportFormatter::variableExists(const SimpleString& variableName) { CodeReportingAllocationNode* current = codeReportingList_; while (current) { if (variableName == current->variableName_) return true; current = current->next_; } return false; } SimpleString CodeMemoryReportFormatter::getAllocationString(MemoryLeakAllocator* allocator, const SimpleString& variableName, size_t size) { if (isNewAllocator(allocator)) return StringFromFormat("char* %s = new char[%d]; /* using %s */", variableName.asCharString(), size, allocator->alloc_name()); else return StringFromFormat("void* %s = malloc(%d);", variableName.asCharString(), size); } SimpleString CodeMemoryReportFormatter::getDeallocationString(MemoryLeakAllocator* allocator, const SimpleString& variableName, const char* file, int line) { if (isNewAllocator(allocator)) return StringFromFormat("delete [] %s; /* using %s at %s:%d */", variableName.asCharString(), allocator->free_name(), file, line); else return StringFromFormat("free(%s); /* at %s:%d */", variableName.asCharString(), file, line); } void CodeMemoryReportFormatter::report_test_start(TestResult* result, Utest& test) { clearReporting(); result->print(StringFromFormat("*/\nTEST(%s_memoryReport, %s)\n{ /* at %s:%d */\n", test.getGroup().asCharString(), test.getName().asCharString(), test.getFile().asCharString(), test.getLineNumber()).asCharString()); } void CodeMemoryReportFormatter::report_test_end(TestResult* result, Utest&) { result->print("}/*"); } void CodeMemoryReportFormatter::report_testgroup_start(TestResult* result, Utest& test) { result->print(StringFromFormat("*/TEST_GROUP(%s_memoryReport)\n{\n};\n/*", test.getGroup().asCharString()).asCharString()); } void CodeMemoryReportFormatter::report_alloc_memory(TestResult* result, MemoryLeakAllocator* allocator, size_t size, char* memory, const char* file, int line) { SimpleString variableName = createVariableNameFromFileLineInfo(file, line); result->print(StringFromFormat("\t%s\n", getAllocationString(allocator, variableName, size).asCharString()).asCharString()); addNodeToList(variableName.asCharString(), memory, codeReportingList_); } void CodeMemoryReportFormatter::report_free_memory(TestResult* result, MemoryLeakAllocator* allocator, char* memory, const char* file, int line) { SimpleString variableName; CodeReportingAllocationNode* node = findNode(memory); if (memory == NULL) variableName = "NULL"; else variableName = node->variableName_; result->print(StringFromFormat("\t%s\n", getDeallocationString(allocator, variableName, file, line).asCharString()).asCharString()); }
null
292
cpp
blalor-cpputest
MockActualFunctionCall.cpp
src/CppUTestExt/MockActualFunctionCall.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockActualFunctionCall.h" #include "CppUTestExt/MockExpectedFunctionsList.h" #include "CppUTestExt/MockExpectedFunctionCall.h" #include "CppUTestExt/MockFailure.h" MockActualFunctionCall::MockActualFunctionCall(int callOrder, MockFailureReporter* reporter, const MockExpectedFunctionsList& allExpectations) : callOrder_(callOrder), reporter_(reporter), state_(CALL_SUCCEED), _fulfilledExpectation(NULL), allExpectations_(allExpectations) { unfulfilledExpectations_.addUnfilfilledExpectations(allExpectations); } MockActualFunctionCall::~MockActualFunctionCall() { } void MockActualFunctionCall::setMockFailureReporter(MockFailureReporter* reporter) { reporter_ = reporter; } Utest* MockActualFunctionCall::getTest() const { return reporter_->getTestToFail(); } void MockActualFunctionCall::failTest(const MockFailure& failure) { setState(CALL_FAILED); reporter_->failTest(failure); } void MockActualFunctionCall::finnalizeCallWhenFulfilled() { if (unfulfilledExpectations_.hasFulfilledExpectations()) { _fulfilledExpectation = unfulfilledExpectations_.removeOneFulfilledExpectation(); callHasSucceeded(); } } void MockActualFunctionCall::callHasSucceeded() { setState(CALL_SUCCEED); unfulfilledExpectations_.resetExpectations(); } MockFunctionCall& MockActualFunctionCall::withName(const SimpleString& name) { setName(name); setState(CALL_IN_PROGESS); unfulfilledExpectations_.onlyKeepUnfulfilledExpectationsRelatedTo(name); if (unfulfilledExpectations_.isEmpty()) { MockUnexpectedCallHappenedFailure failure(getTest(), name, allExpectations_); failTest(failure); return *this; } unfulfilledExpectations_.callWasMade(callOrder_); finnalizeCallWhenFulfilled(); return *this; } MockFunctionCall& MockActualFunctionCall::withCallOrder(int) { return *this; } void MockActualFunctionCall::checkActualParameter(const MockNamedValue& actualParameter) { unfulfilledExpectations_.onlyKeepUnfulfilledExpectationsWithParameter(actualParameter); if (unfulfilledExpectations_.isEmpty()) { MockUnexpectedParameterFailure failure(getTest(), getName(), actualParameter, allExpectations_); failTest(failure); return; } unfulfilledExpectations_.parameterWasPassed(actualParameter.getName()); finnalizeCallWhenFulfilled(); } MockFunctionCall& MockActualFunctionCall::withParameter(const SimpleString& name, int value) { MockNamedValue actualParameter(name); actualParameter.setValue(value); checkActualParameter(actualParameter); return *this; } MockFunctionCall& MockActualFunctionCall::withParameter(const SimpleString& name, double value) { MockNamedValue actualParameter(name); actualParameter.setValue(value); checkActualParameter(actualParameter); return *this; } MockFunctionCall& MockActualFunctionCall::withParameter(const SimpleString& name, const char* value) { MockNamedValue actualParameter(name); actualParameter.setValue(value); checkActualParameter(actualParameter); return *this; } MockFunctionCall& MockActualFunctionCall::withParameter(const SimpleString& name, void* value) { MockNamedValue actualParameter(name); actualParameter.setValue(value); checkActualParameter(actualParameter); return *this; } MockFunctionCall& MockActualFunctionCall::withParameterOfType(const SimpleString& type, const SimpleString& name, void* value) { if (getComparatorForType(type) == NULL) { MockNoWayToCompareCustomTypeFailure failure(getTest(), type); failTest(failure); return *this; } MockNamedValue actualParameter(name); actualParameter.setObjectPointer(type, value); actualParameter.setComparator(getComparatorForType(type)); checkActualParameter(actualParameter); return *this; } bool MockActualFunctionCall::isFulfilled() const { return state_ == CALL_SUCCEED; } bool MockActualFunctionCall::hasFailed() const { return state_ == CALL_FAILED; } void MockActualFunctionCall::checkExpectations() { if (state_ != CALL_IN_PROGESS) return; if (! unfulfilledExpectations_.hasUnfullfilledExpectations()) FAIL("Actual call is in progress. Checking expectations. But no unfulfilled expectations. Cannot happen.") _fulfilledExpectation = unfulfilledExpectations_.removeOneFulfilledExpectationWithIgnoredParameters(); if (_fulfilledExpectation) { callHasSucceeded(); return; } if (unfulfilledExpectations_.hasUnfulfilledExpectationsBecauseOfMissingParameters()) { MockExpectedParameterDidntHappenFailure failure(getTest(), getName(), allExpectations_); failTest(failure); } else { MockExpectedObjectDidntHappenFailure failure(getTest(), getName(), allExpectations_); failTest(failure); } } const char* MockActualFunctionCall::stringFromState(ActualCallState state) { switch (state) { case CALL_IN_PROGESS: return "In progress"; case CALL_FAILED: return "Failed"; case CALL_SUCCEED: return "Succeed"; default: ; } return "No valid state info"; } void MockActualFunctionCall::checkStateConsistency(ActualCallState oldState, ActualCallState newState) { if (oldState == newState) FAIL(StringFromFormat("State change to the same state: %s.", stringFromState(newState)).asCharString()); if (oldState == CALL_FAILED) FAIL("State was already failed. Cannot change state again."); } void MockActualFunctionCall::setState(ActualCallState state) { checkStateConsistency(state_, state); state_ = state; } MockFunctionCall& MockActualFunctionCall::andReturnValue(int) { FAIL("andReturnValue cannot be called on an ActualFunctionCall. Use returnValue instead to get the value."); return *this; } MockFunctionCall& MockActualFunctionCall::andReturnValue(const char*) { FAIL("andReturnValue cannot be called on an ActualFunctionCall. Use returnValue instead to get the value."); return *this; } MockFunctionCall& MockActualFunctionCall::andReturnValue(double) { FAIL("andReturnValue cannot be called on an ActualFunctionCall. Use returnValue instead to get the value."); return *this; } MockFunctionCall& MockActualFunctionCall::andReturnValue(void*) { FAIL("andReturnValue cannot be called on an ActualFunctionCall. Use returnValue instead to get the value."); return *this; } MockNamedValue MockActualFunctionCall::returnValue() { checkExpectations(); if (_fulfilledExpectation) return _fulfilledExpectation->returnValue(); return MockNamedValue("no return value"); } bool MockActualFunctionCall::hasReturnValue() { return ! returnValue().getName().isEmpty(); } MockFunctionCall& MockActualFunctionCall::onObject(void* objectPtr) { unfulfilledExpectations_.onlyKeepUnfulfilledExpectationsOnObject(objectPtr); if (unfulfilledExpectations_.isEmpty()) { MockUnexpectedObjectFailure failure(getTest(), getName(), objectPtr, allExpectations_); failTest(failure); return *this; } unfulfilledExpectations_.wasPassedToObject(); finnalizeCallWhenFulfilled(); return *this; }
null
293
cpp
blalor-cpputest
CommandLineTestRunner.cpp
src/CppUTest/CommandLineTestRunner.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/TestOutput.h" #include "CppUTest/JUnitTestOutput.h" #include "CppUTest/TestRegistry.h" CommandLineTestRunner::CommandLineTestRunner(int ac, const char** av, TestOutput* output) : output_(output), jUnitOutput_(new JUnitTestOutput) { arguments_ = new CommandLineArguments(ac, av); } CommandLineTestRunner::~CommandLineTestRunner() { delete arguments_; delete jUnitOutput_; } int CommandLineTestRunner::RunAllTests(int ac, char** av) { return RunAllTests(ac, const_cast<const char**> (av)); } int CommandLineTestRunner::RunAllTests(int ac, const char** av) { int result = 0; ConsoleTestOutput output; MemoryLeakWarningPlugin memLeakWarn(DEF_PLUGIN_MEM_LEAK); TestRegistry::getCurrentRegistry()->installPlugin(&memLeakWarn); { CommandLineTestRunner runner(ac, av, &output); result = runner.runAllTestsMain(); } if (result == 0) { output << memLeakWarn.FinalReport(0); } return result; } int CommandLineTestRunner::runAllTestsMain() { int testResult = 0; SetPointerPlugin pPlugin(DEF_PLUGIN_SET_POINTER); TestRegistry::getCurrentRegistry()->installPlugin(&pPlugin); if (!parseArguments(TestRegistry::getCurrentRegistry()->getFirstPlugin())) return 1; testResult = runAllTests(); TestRegistry::getCurrentRegistry()->cleanup(); return testResult; } void CommandLineTestRunner::initializeTestRun() { TestRegistry::getCurrentRegistry()->groupFilter(arguments_->getGroupFilter()); TestRegistry::getCurrentRegistry()->nameFilter(arguments_->getNameFilter()); if (arguments_->isVerbose()) output_->verbose(); } int CommandLineTestRunner::runAllTests() { initializeTestRun(); int loopCount = 0; int failureCount = 0; int repeat_ = arguments_->getRepeatCount(); while (loopCount++ < repeat_) { output_->printTestRun(loopCount, repeat_); TestResult tr(*output_); TestRegistry::getCurrentRegistry()->runAllTests(tr); failureCount += tr.getFailureCount(); } return failureCount; } bool CommandLineTestRunner::parseArguments(TestPlugin* plugin) { if (arguments_->parse(plugin)) { if (arguments_->isJUnitOutput()) { output_ = jUnitOutput_; } return true; } else { output_->print(arguments_->usage()); return false; } } bool CommandLineTestRunner::isVerbose() { return arguments_->isVerbose(); } int CommandLineTestRunner::getRepeatCount() { return arguments_->getRepeatCount(); } SimpleString CommandLineTestRunner::getGroupFilter() { return arguments_->getGroupFilter(); } SimpleString CommandLineTestRunner::getNameFilter() { return arguments_->getNameFilter(); }
null
294
cpp
blalor-cpputest
JUnitTestOutput.cpp
src/CppUTest/JUnitTestOutput.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/JUnitTestOutput.h" #include "CppUTest/TestResult.h" #include "CppUTest/TestFailure.h" #include "CppUTest/PlatformSpecificFunctions.h" struct JUnitTestCaseResultNode { JUnitTestCaseResultNode() : execTime_(0), failure_(0), next_(0) { } ; SimpleString name_; long execTime_; TestFailure* failure_; JUnitTestCaseResultNode* next_; }; struct JUnitTestGroupResult { JUnitTestGroupResult() : testCount_(0), failureCount_(0), groupExecTime_(0), head_(0), tail_(0) { } ; int testCount_; int failureCount_; long startTime_; long groupExecTime_; SimpleString group_; JUnitTestCaseResultNode* head_; JUnitTestCaseResultNode* tail_; }; struct JUnitTestOutputImpl { JUnitTestGroupResult results_; PlatformSpecificFile file_; }; JUnitTestOutput::JUnitTestOutput() : impl_(new JUnitTestOutputImpl) { } JUnitTestOutput::~JUnitTestOutput() { resetTestGroupResult(); delete impl_; } void JUnitTestOutput::resetTestGroupResult() { impl_->results_.testCount_ = 0; impl_->results_.failureCount_ = 0; impl_->results_.group_ = ""; JUnitTestCaseResultNode* cur = impl_->results_.head_; while (cur) { JUnitTestCaseResultNode* tmp = cur->next_; ; if (cur->failure_) delete cur->failure_; delete cur; cur = tmp; } impl_->results_.head_ = 0; impl_->results_.tail_ = 0; } void JUnitTestOutput::printTestsStarted() { } void JUnitTestOutput::printCurrentGroupStarted(const Utest& /*test*/) { } void JUnitTestOutput::printCurrentTestEnded(const TestResult& result) { impl_->results_.tail_->execTime_ = result.getCurrentTestTotalExecutionTime(); } void JUnitTestOutput::printTestsEnded(const TestResult& /*result*/) { } void JUnitTestOutput::printCurrentGroupEnded(const TestResult& result) { impl_->results_.groupExecTime_ = result.getCurrentGroupTotalExecutionTime(); writeTestGroupToFile(); resetTestGroupResult(); } void JUnitTestOutput::printCurrentTestStarted(const Utest& test) { impl_->results_.testCount_++; impl_->results_.group_ = test.getGroup(); impl_->results_.startTime_ = GetPlatformSpecificTimeInMillis(); if (impl_->results_.tail_ == 0) { impl_->results_.head_ = impl_->results_.tail_ = new JUnitTestCaseResultNode; } else { impl_->results_.tail_->next_ = new JUnitTestCaseResultNode; impl_->results_.tail_ = impl_->results_.tail_->next_; } impl_->results_.tail_->name_ = test.getName(); } static SimpleString createFileName(const SimpleString& group) { SimpleString fileName = "cpputest_"; fileName += group; fileName += ".xml"; return fileName; } void JUnitTestOutput::writeXmlHeader() { writeToFile("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); } void JUnitTestOutput::writeTestSuiteSummery() { SimpleString buf = StringFromFormat( "<testsuite errors=\"0\" failures=\"%d\" hostname=\"localhost\" name=\"%s\" tests=\"%d\" time=\"%d.%03d\" timestamp=\"%s\">\n", impl_->results_.failureCount_, impl_->results_.group_.asCharString(), impl_->results_.testCount_, (int) (impl_->results_.groupExecTime_ / 1000), (int) (impl_->results_.groupExecTime_ % 1000), GetPlatformSpecificTimeString()); writeToFile(buf.asCharString()); } void JUnitTestOutput::writeProperties() { writeToFile("<properties>\n"); writeToFile("</properties>\n"); } void JUnitTestOutput::writeTestCases() { JUnitTestCaseResultNode* cur = impl_->results_.head_; while (cur) { SimpleString buf = StringFromFormat( "<testcase classname=\"%s\" name=\"%s\" time=\"%d.%03d\">\n", impl_->results_.group_.asCharString(), cur->name_.asCharString(), (int) (cur->execTime_ / 1000), (int)(cur->execTime_ % 1000)); writeToFile(buf.asCharString()); if (cur->failure_) { writeFailure(cur); } writeToFile("</testcase>\n"); cur = cur->next_; } } void JUnitTestOutput::writeFailure(JUnitTestCaseResultNode* node) { SimpleString message = node->failure_->getMessage().asCharString(); message.replace('"', '\''); message.replace('<', '['); message.replace('>', ']'); message.replace("\n", "{newline}"); SimpleString buf = StringFromFormat( "<failure message=\"%s:%d: %s\" type=\"AssertionFailedError\">\n", node->failure_->getFileName().asCharString(), node->failure_->getFailureLineNumber(), message.asCharString()); writeToFile(buf.asCharString()); writeToFile("</failure>\n"); } void JUnitTestOutput::writeFileEnding() { writeToFile("<system-out></system-out>\n"); writeToFile("<system-err></system-err>\n"); writeToFile("</testsuite>"); } void JUnitTestOutput::writeTestGroupToFile() { openFileForWrite(createFileName(impl_->results_.group_)); writeXmlHeader(); writeTestSuiteSummery(); writeProperties(); writeTestCases(); writeFileEnding(); closeFile(); } void JUnitTestOutput::verbose() { } void JUnitTestOutput::printBuffer(const char*) { } void JUnitTestOutput::print(const char*) { } void JUnitTestOutput::print(long) { } void JUnitTestOutput::print(const TestFailure& failure) { if (impl_->results_.tail_->failure_ == 0) { impl_->results_.failureCount_++; impl_->results_.tail_->failure_ = new TestFailure(failure); } } void JUnitTestOutput::printTestRun(int /*number*/, int /*total*/) { } void JUnitTestOutput::flush() { } void JUnitTestOutput::openFileForWrite(const SimpleString& fileName) { impl_->file_ = PlatformSpecificFOpen(fileName.asCharString(), "w"); } void JUnitTestOutput::writeToFile(const SimpleString& buffer) { PlatformSpecificFPuts(buffer.asCharString(), impl_->file_); } void JUnitTestOutput::closeFile() { PlatformSpecificFClose(impl_->file_); }
null
295
cpp
blalor-cpputest
TestOutput.cpp
src/CppUTest/TestOutput.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestOutput.h" #include "CppUTest/PlatformSpecificFunctions.h" TestOutput::TestOutput() : dotCount_(0), verbose_(false), progressIndication_(".") { } TestOutput::~TestOutput() { } void TestOutput::verbose() { verbose_ = true; } void TestOutput::print(const char* str) { printBuffer(str); } void TestOutput::print(long n) { print(StringFrom(n).asCharString()); } void TestOutput::printDouble(double d) { print(StringFrom(d, 3).asCharString()); } void TestOutput::printHex(long n) { print(HexStringFrom(n).asCharString()); } TestOutput& operator<<(TestOutput& p, const char* s) { p.print(s); return p; } TestOutput& operator<<(TestOutput& p, long int i) { p.print(i); return p; } void TestOutput::printCurrentTestStarted(const Utest& test) { if (verbose_) print(test.getFormattedName().asCharString()); } void TestOutput::printCurrentTestEnded(const TestResult& res) { if (verbose_) { print(" - "); print(res.getCurrentTestTotalExecutionTime()); print(" ms\n"); } else { printProgressIndicator(); } } void TestOutput::printProgressIndicator() { print(progressIndication_); if (++dotCount_ % 50 == 0) print("\n"); } void TestOutput::setProgressIndicator(const char* indicator) { progressIndication_ = indicator; } void TestOutput::printTestsStarted() { } void TestOutput::printCurrentGroupStarted(const Utest& /*test*/) { } void TestOutput::printCurrentGroupEnded(const TestResult& /*res*/) { } void TestOutput::flush() { } void TestOutput::printTestsEnded(const TestResult& result) { if (result.getFailureCount() > 0) { print("\nErrors ("); print(result.getFailureCount()); print(" failures, "); } else { print("\nOK ("); } print(result.getTestCount()); print(" tests, "); print(result.getRunCount()); print(" ran, "); print(result.getCheckCount()); print(" checks, "); print(result.getIgnoredCount()); print(" ignored, "); print(result.getFilteredOutCount()); print(" filtered out, "); print(result.getTotalExecutionTime()); print(" ms)\n\n"); } void TestOutput::printTestRun(int number, int total) { if (total > 1) { print("Test run "); print(number); print(" of "); print(total); print("\n"); } } void TestOutput::print(const TestFailure& failure) { if (failure.isOutsideTestFile() || failure.isInHelperFunction()) printFileAndLineForTestAndFailure(failure); else printFileAndLineForFailure(failure); printFailureMessage(failure.getMessage()); } void TestOutput::printFileAndLineForTestAndFailure(const TestFailure& failure) { printEclipseErrorInFileOnLine(failure.getTestFileName(), failure.getTestLineNumber()); printFailureInTest(failure.getTestName()); printEclipseErrorInFileOnLine(failure.getFileName(), failure.getFailureLineNumber()); } void TestOutput::printFileAndLineForFailure(const TestFailure& failure) { printEclipseErrorInFileOnLine(failure.getFileName(), failure.getFailureLineNumber()); printFailureInTest(failure.getTestName()); } void TestOutput::printFailureInTest(SimpleString testName) { print(" Failure in "); print(testName.asCharString()); } void TestOutput::printFailureMessage(SimpleString reason) { print("\n"); print("\t"); print(reason.asCharString()); print("\n\n"); } void TestOutput::printEclipseErrorInFileOnLine(SimpleString file, int lineNumber) { print("\n"); print(file.asCharString()); print(":"); print(lineNumber); print(":"); print(" error:"); } void ConsoleTestOutput::printBuffer(const char* s) { while (*s) { if ('\n' == *s) PlatformSpecificPutchar('\r'); PlatformSpecificPutchar(*s); s++; } flush(); } void ConsoleTestOutput::flush() { PlatformSpecificFlush(); }
null
296
cpp
blalor-cpputest
MemoryLeakDetector.cpp
src/CppUTest/MemoryLeakDetector.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/MemoryLeakDetector.h" #include "CppUTest/MemoryLeakAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" #define UNKNOWN ((char*)("<unknown>")) SimpleStringBuffer::SimpleStringBuffer() : positions_filled_(0), write_limit_(SIMPLE_STRING_BUFFER_LEN-1) { } void SimpleStringBuffer::clear() { positions_filled_ = 0; buffer_[0] = '\0'; } void SimpleStringBuffer::add(const char* format, ...) { int count = 0; int positions_left = write_limit_ - positions_filled_; if (positions_left <= 0) return; va_list arguments; va_start(arguments, format); count = PlatformSpecificVSNprintf(buffer_ + positions_filled_, positions_left+1, format, arguments); if (count > 0) positions_filled_ += count; if (positions_filled_ > write_limit_) positions_filled_ = write_limit_; va_end(arguments); } char* SimpleStringBuffer::toString() { return buffer_; } void SimpleStringBuffer::setWriteLimit(int write_limit) { write_limit_ = write_limit; if (write_limit_ > SIMPLE_STRING_BUFFER_LEN-1) write_limit_ = SIMPLE_STRING_BUFFER_LEN-1; } void SimpleStringBuffer::resetWriteLimit() { write_limit_ = SIMPLE_STRING_BUFFER_LEN-1; } bool SimpleStringBuffer::reachedItsCapacity() { return positions_filled_ >= write_limit_; } //////////////////////// void MemoryLeakDetectorNode::init(char* memory, size_t size, MemoryLeakAllocator* allocator, MemLeakPeriod period, const char* file, int line) { memory_ = memory; size_ = size; allocator_ = allocator; period_ = period; file_ = file; line_ = line; } /////////////////////// bool MemoryLeakDetectorList::isInPeriod(MemoryLeakDetectorNode* node, MemLeakPeriod period) { return period == mem_leak_period_all || node->period_ == period || (node->period_ != mem_leak_period_disabled && period == mem_leak_period_enabled); } void MemoryLeakDetectorList::clearAllAccounting(MemLeakPeriod period) { MemoryLeakDetectorNode* cur = head_; MemoryLeakDetectorNode* prev = 0; while (cur) { if (isInPeriod(cur, period)) { if (prev) { prev->next_ = cur->next_; cur = prev; } else { head_ = cur->next_; cur = head_; continue; } } prev = cur; cur = cur->next_; } } void MemoryLeakDetectorList::addNewNode(MemoryLeakDetectorNode* node) { node->next_ = head_; head_ = node; } MemoryLeakDetectorNode* MemoryLeakDetectorList::removeNode(char* memory) { MemoryLeakDetectorNode* cur = head_; MemoryLeakDetectorNode* prev = 0; while (cur) { if (cur->memory_ == memory) { if (prev) { prev->next_ = cur->next_; return cur; } else { head_ = cur->next_; return cur; } } prev = cur; cur = cur->next_; } return 0; } MemoryLeakDetectorNode* MemoryLeakDetectorList::retrieveNode(char* memory) { MemoryLeakDetectorNode* cur = head_; while (cur) { if (cur->memory_ == memory) return cur; cur = cur->next_; } return NULL; } MemoryLeakDetectorNode* MemoryLeakDetectorList::getLeakFrom(MemoryLeakDetectorNode* node, MemLeakPeriod period) { for (MemoryLeakDetectorNode* cur = node; cur; cur = cur->next_) if (isInPeriod(cur, period)) return cur; return 0; } MemoryLeakDetectorNode* MemoryLeakDetectorList::getFirstLeak(MemLeakPeriod period) { return getLeakFrom(head_, period); } MemoryLeakDetectorNode* MemoryLeakDetectorList::getNextLeak(MemoryLeakDetectorNode* node, MemLeakPeriod period) { return getLeakFrom(node->next_, period); } int MemoryLeakDetectorList::getTotalLeaks(MemLeakPeriod period) { int total_leaks = 0; for (MemoryLeakDetectorNode* node = head_; node; node = node->next_) { if (isInPeriod(node, period)) total_leaks++; } return total_leaks; } bool MemoryLeakDetectorList::hasLeaks(MemLeakPeriod period) { for (MemoryLeakDetectorNode* node = head_; node; node = node->next_) if (isInPeriod(node, period)) return true; return false; } ///////////////////////////////////////////////////////////// unsigned long MemoryLeakDetectorTable::hash(char* memory) { return ((unsigned long) memory) % hash_prime; } void MemoryLeakDetectorTable::clearAllAccounting(MemLeakPeriod period) { for (int i = 0; i < hash_prime; i++) table_[i].clearAllAccounting(period); } void MemoryLeakDetectorTable::addNewNode(MemoryLeakDetectorNode* node) { table_[hash(node->memory_)].addNewNode(node); } MemoryLeakDetectorNode* MemoryLeakDetectorTable::removeNode(char* memory) { return table_[hash(memory)].removeNode(memory); } MemoryLeakDetectorNode* MemoryLeakDetectorTable::retrieveNode(char* memory) { return table_[hash(memory)].retrieveNode(memory); } bool MemoryLeakDetectorTable::hasLeaks(MemLeakPeriod period) { for (int i = 0; i < hash_prime; i++) if (table_[i].hasLeaks(period)) return true; return false; } int MemoryLeakDetectorTable::getTotalLeaks(MemLeakPeriod period) { int total_leaks = 0; for (int i = 0; i < hash_prime; i++) total_leaks += table_[i].getTotalLeaks(period); return total_leaks; } MemoryLeakDetectorNode* MemoryLeakDetectorTable::getFirstLeak(MemLeakPeriod period) { for (int i = 0; i < hash_prime; i++) { MemoryLeakDetectorNode* node = table_[i].getFirstLeak(period); if (node) return node; } return 0; } MemoryLeakDetectorNode* MemoryLeakDetectorTable::getNextLeak(MemoryLeakDetectorNode* leak, MemLeakPeriod period) { int i = hash(leak->memory_); MemoryLeakDetectorNode* node = table_[i].getNextLeak(leak, period); if (node) return node; for (++i; i < hash_prime; i++) { node = table_[i].getFirstLeak(period); if (node) return node; } return 0; } ///////////////////////////////////////////////////////////// MemoryLeakDetector::MemoryLeakDetector() { } void MemoryLeakDetector::init(MemoryLeakFailure* reporter) { doAllocationTypeChecking_ = true; current_period_ = mem_leak_period_disabled; reporter_ = reporter; output_buffer_ = SimpleStringBuffer(); memoryTable_ = MemoryLeakDetectorTable(); } void MemoryLeakDetector::clearAllAccounting(MemLeakPeriod period) { memoryTable_.clearAllAccounting(period); } void MemoryLeakDetector::startChecking() { output_buffer_.clear(); current_period_ = mem_leak_period_checking; } void MemoryLeakDetector::stopChecking() { current_period_ = mem_leak_period_enabled; } void MemoryLeakDetector::enable() { current_period_ = mem_leak_period_enabled; } void MemoryLeakDetector::disable() { current_period_ = mem_leak_period_disabled; } void MemoryLeakDetector::disableAllocationTypeChecking() { doAllocationTypeChecking_ = false; } void MemoryLeakDetector::enableAllocationTypeChecking() { doAllocationTypeChecking_ = true; } void MemoryLeakDetector::reportFailure(const char* message, const char* allocFile, int allocLine, size_t allocSize, MemoryLeakAllocator* allocAllocator, const char* freeFile, int freeLine, MemoryLeakAllocator* freeAllocator) { output_buffer_.add(message); output_buffer_.add(MEM_LEAK_ALLOC_LOCATION, allocFile, allocLine, allocSize, allocAllocator->alloc_name()); output_buffer_.add(MEM_LEAK_DEALLOC_LOCATION, freeFile, freeLine, freeAllocator->free_name()); reporter_->fail(output_buffer_.toString()); } size_t calculateIntAlignedSize(size_t size) { return (sizeof(int) - (size % sizeof(int))) + size; } size_t MemoryLeakDetector::sizeOfMemoryWithCorruptionInfo(size_t size) { return calculateIntAlignedSize(size + memory_corruption_buffer_size); } MemoryLeakDetectorNode* MemoryLeakDetector::getNodeFromMemoryPointer(char* memory, size_t memory_size) { return (MemoryLeakDetectorNode*) (memory + sizeOfMemoryWithCorruptionInfo(memory_size)); } void MemoryLeakDetector::storeLeakInformation(MemoryLeakDetectorNode *& node, char *new_memory, size_t size, MemoryLeakAllocator *allocator, const char *file, int line) { node->init(new_memory, size, allocator, current_period_, file, line); addMemoryCorruptionInformation(node->memory_ + node->size_); memoryTable_.addNewNode(node); } char* MemoryLeakDetector::reallocateMemoryAndLeakInformation(MemoryLeakAllocator* allocator, char* memory, size_t size, const char* file, int line) { char* new_memory = (char*) (PlatformSpecificRealloc(memory, sizeOfMemoryWithCorruptionInfo(size))); if (new_memory == NULL) return NULL; MemoryLeakDetectorNode *node = (MemoryLeakDetectorNode*) (allocator->allocMemoryLeakNode(sizeof(MemoryLeakDetectorNode))); storeLeakInformation(node, new_memory, size, allocator, file, line); return node->memory_; } void MemoryLeakDetector::invalidateMemory(char* memory) { MemoryLeakDetectorNode* node = memoryTable_.retrieveNode(memory); if (node) PlatformSpecificMemset(memory, 0xCD, node->size_); } void MemoryLeakDetector::addMemoryCorruptionInformation(char* memory) { memory[0] = 'B'; memory[1] = 'A'; memory[2] = 'S'; } bool MemoryLeakDetector::validMemoryCorruptionInformation(char* memory) { return memory[0] == 'B' && memory[1] == 'A' && memory[2] == 'S'; } bool MemoryLeakDetector::matchingAllocation(MemoryLeakAllocator *alloc_allocator, MemoryLeakAllocator *free_allocator) { if (alloc_allocator == free_allocator) return true; if (!doAllocationTypeChecking_) return true; return free_allocator->isOfEqualType(alloc_allocator); } void MemoryLeakDetector::checkForCorruption(MemoryLeakDetectorNode* node, const char* file, int line, MemoryLeakAllocator* allocator) { if (!matchingAllocation(node->allocator_, allocator)) reportFailure(MEM_LEAK_ALLOC_DEALLOC_MISMATCH, node->file_, node->line_, node->size_, node->allocator_, file, line, allocator); else if (!validMemoryCorruptionInformation(node->memory_ + node->size_)) reportFailure(MEM_LEAK_MEMORY_CORRUPTION, node->file_, node->line_, node->size_, node->allocator_, file, line, allocator); else if (allocator->allocateMemoryLeakNodeSeparately()) allocator->freeMemoryLeakNode((char*) node); } char* MemoryLeakDetector::allocMemory(MemoryLeakAllocator* allocator, size_t size) { return allocMemory(allocator, size, UNKNOWN, 0); } char* MemoryLeakDetector::allocMemory(MemoryLeakAllocator* allocator, size_t size, const char* file, int line) { /* With malloc, it is harder to guarantee that the allocator free is called. * This is because operator new is overloaded via linker symbols, but malloc just via #defines. * If the same allocation is used and the wrong free is called, it will deallocate the memory leak information * without the memory leak detector ever noticing it! * So, for malloc, we'll allocate the memory separately so we can detect this and give a proper error. */ char* memory; MemoryLeakDetectorNode* node; if (allocator->allocateMemoryLeakNodeSeparately()) { memory = allocator->alloc_memory(sizeOfMemoryWithCorruptionInfo(size), file, line); if (memory == NULL) return NULL; node = (MemoryLeakDetectorNode*) allocator->allocMemoryLeakNode(sizeof(MemoryLeakDetectorNode)); } else { memory = allocator->alloc_memory(sizeOfMemoryWithCorruptionInfo(size) + sizeof(MemoryLeakDetectorNode), file, line); if (memory == NULL) return NULL; node = getNodeFromMemoryPointer(memory, size); } storeLeakInformation(node, memory, size, allocator, file, line); return node->memory_; } void MemoryLeakDetector::removeMemoryLeakInformationWithoutCheckingOrDeallocating(void* memory) { memoryTable_.removeNode((char*) memory); } void MemoryLeakDetector::deallocMemory(MemoryLeakAllocator* allocator, void* memory, const char* file, int line) { if (memory == 0) return; MemoryLeakDetectorNode* node = memoryTable_.removeNode((char*) memory); if (node == NULL) { reportFailure(MEM_LEAK_DEALLOC_NON_ALLOCATED, "<unknown>", 0, 0, NullUnknownAllocator::defaultAllocator(), file, line, allocator); return; } checkForCorruption(node, file, line, allocator); allocator->free_memory((char*) memory, file, line); } void MemoryLeakDetector::deallocMemory(MemoryLeakAllocator* allocator, void* memory) { deallocMemory(allocator, (char*) memory, UNKNOWN, 0); } char* MemoryLeakDetector::reallocMemory(MemoryLeakAllocator* allocator, char* memory, size_t size, const char* file, int line) { if (memory) { MemoryLeakDetectorNode* node = memoryTable_.removeNode(memory); if (node == NULL) { reportFailure(MEM_LEAK_DEALLOC_NON_ALLOCATED, "<unknown>", 0, 0, NullUnknownAllocator::defaultAllocator(), file, line, allocator); return NULL; } checkForCorruption(node, file, line, allocator); } return reallocateMemoryAndLeakInformation(allocator, memory, size, file, line); } void MemoryLeakDetector::ConstructMemoryLeakReport(MemLeakPeriod period) { MemoryLeakDetectorNode* leak = memoryTable_.getFirstLeak(period); int total_leaks = 0; bool giveWarningOnUsingMalloc = false; output_buffer_.add(MEM_LEAK_HEADER); output_buffer_.setWriteLimit(SimpleStringBuffer::SIMPLE_STRING_BUFFER_LEN - MEM_LEAK_NORMAL_MALLOC_FOOTER_SIZE); while (leak) { output_buffer_.add(MEM_LEAK_LEAK, leak->size_, leak->file_, leak->line_, leak->allocator_->alloc_name(), leak->memory_); if (leak->allocator_->allocateMemoryLeakNodeSeparately()) giveWarningOnUsingMalloc = true; total_leaks++; leak = memoryTable_.getNextLeak(leak, period); } bool buffer_reached_its_capacity = output_buffer_.reachedItsCapacity(); output_buffer_.resetWriteLimit(); if (buffer_reached_its_capacity) output_buffer_.add(MEM_LEAK_TOO_MUCH); output_buffer_.add("%s %d\n", MEM_LEAK_FOOTER, total_leaks); if (giveWarningOnUsingMalloc) output_buffer_.add(MEM_LEAK_ADDITION_MALLOC_WARNING); } const char* MemoryLeakDetector::report(MemLeakPeriod period) { if (!memoryTable_.hasLeaks(period)) return MEM_LEAK_NONE; output_buffer_.clear(); ConstructMemoryLeakReport(period); return output_buffer_.toString(); } void MemoryLeakDetector::markCheckingPeriodLeaksAsNonCheckingPeriod() { MemoryLeakDetectorNode* leak = memoryTable_.getFirstLeak(mem_leak_period_checking); while (leak) { if (leak->period_ == mem_leak_period_checking) leak->period_ = mem_leak_period_enabled; leak = memoryTable_.getNextLeak(leak, mem_leak_period_checking); } } int MemoryLeakDetector::totalMemoryLeaks(MemLeakPeriod period) { return memoryTable_.getTotalLeaks(period); }
null
297
cpp
blalor-cpputest
TestPlugin.cpp
src/CppUTest/TestPlugin.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestPlugin.h" TestPlugin::TestPlugin(const SimpleString& name) : next_(NullTestPlugin::instance()), name_(name), enabled_(true) { } TestPlugin::TestPlugin(TestPlugin* next) : next_(next), name_("null") { } TestPlugin::~TestPlugin() { } TestPlugin* TestPlugin::addPlugin(TestPlugin* plugin) { next_ = plugin; return this; } void TestPlugin::runAllPreTestAction(Utest& test, TestResult& result) { if (enabled_) preTestAction(test, result); next_->runAllPreTestAction(test, result); } void TestPlugin::runAllPostTestAction(Utest& test, TestResult& result) { next_ ->runAllPostTestAction(test, result); if (enabled_) postTestAction(test, result); } bool TestPlugin::parseAllArguments(int ac, char** av, int index) { return parseAllArguments(ac, const_cast<const char**> (av), index); } bool TestPlugin::parseAllArguments(int ac, const char** av, int index) { if (parseArguments(ac, av, index)) return true; if (next_) return next_->parseAllArguments(ac, av, index); return false; } const SimpleString& TestPlugin::getName() { return name_; } TestPlugin* TestPlugin::getPluginByName(const SimpleString& name) { if (name == name_) return this; if (next_) return next_->getPluginByName(name); return (next_); } TestPlugin* TestPlugin::getNext() { return next_; } TestPlugin* TestPlugin::removePluginByName(const SimpleString& name) { TestPlugin* removed = 0; if (next_ && next_->getName() == name) { removed = next_; next_ = next_->next_; } return removed; } void TestPlugin::disable() { enabled_ = false; } void TestPlugin::enable() { enabled_ = true; } bool TestPlugin::isEnabled() { return enabled_; } struct cpputest_pair { void **orig; void *orig_value; }; //////// SetPlugin static int pointerTableIndex; static cpputest_pair setlist[SetPointerPlugin::MAX_SET]; SetPointerPlugin::SetPointerPlugin(const SimpleString& name) : TestPlugin(name) { pointerTableIndex = 0; } SetPointerPlugin::~SetPointerPlugin() { } void CppUTestStore(void**function, void*value) { if (pointerTableIndex >= SetPointerPlugin::MAX_SET) { FAIL("Maximum number of function pointers installed!"); } setlist[pointerTableIndex].orig_value = value; setlist[pointerTableIndex].orig = function; pointerTableIndex++; } void SetPointerPlugin::postTestAction(Utest& /*test*/, TestResult& /*result*/) { for (int i = pointerTableIndex - 1; i >= 0; i--) *((void**) setlist[i].orig) = setlist[i].orig_value; pointerTableIndex = 0; } //////// NullPlugin NullTestPlugin::NullTestPlugin() : TestPlugin(0) { } NullTestPlugin* NullTestPlugin::instance() { static NullTestPlugin _instance; return &_instance; } void NullTestPlugin::runAllPreTestAction(Utest&, TestResult&) { } void NullTestPlugin::runAllPostTestAction(Utest&, TestResult&) { }
null
298
cpp
blalor-cpputest
TestResult.cpp
src/CppUTest/TestResult.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestResult.h" #include "CppUTest/TestFailure.h" #include "CppUTest/TestOutput.h" #include "CppUTest/PlatformSpecificFunctions.h" TestResult::TestResult(TestOutput& p) : output_(p), testCount_(0), runCount_(0), checkCount_(0), failureCount_(0), filteredOutCount_(0), ignoredCount_(0), totalExecutionTime_(0), timeStarted_(0), currentTestTimeStarted_(0), currentTestTotalExecutionTime_(0), currentGroupTimeStarted_(0), currentGroupTotalExecutionTime_(0) { } void TestResult::setProgressIndicator(const char* indicator) { output_.setProgressIndicator(indicator); } TestResult::~TestResult() { } void TestResult::currentGroupStarted(Utest* test) { output_.printCurrentGroupStarted(*test); currentGroupTimeStarted_ = GetPlatformSpecificTimeInMillis(); } void TestResult::currentGroupEnded(Utest* /*test*/) { currentGroupTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentGroupTimeStarted_; output_.printCurrentGroupEnded(*this); } void TestResult::currentTestStarted(Utest* test) { output_.printCurrentTestStarted(*test); currentTestTimeStarted_ = GetPlatformSpecificTimeInMillis(); } void TestResult::print(const char* text) { output_.print(text); } void TestResult::currentTestEnded(Utest* /*test*/) { currentTestTotalExecutionTime_ = GetPlatformSpecificTimeInMillis() - currentTestTimeStarted_; output_.printCurrentTestEnded(*this); } void TestResult::addFailure(const TestFailure& failure) { output_.print(failure); failureCount_++; } void TestResult::countTest() { testCount_++; } void TestResult::countRun() { runCount_++; } void TestResult::countCheck() { checkCount_++; } void TestResult::countFilteredOut() { filteredOutCount_++; } void TestResult::countIgnored() { ignoredCount_++; } void TestResult::testsStarted() { timeStarted_ = GetPlatformSpecificTimeInMillis(); output_.printTestsStarted(); } void TestResult::testsEnded() { long timeEnded = GetPlatformSpecificTimeInMillis(); totalExecutionTime_ = timeEnded - timeStarted_; output_.printTestsEnded(*this); } long TestResult::getTotalExecutionTime() const { return totalExecutionTime_; } void TestResult::setTotalExecutionTime(long exTime) { totalExecutionTime_ = exTime; } long TestResult::getCurrentTestTotalExecutionTime() const { return currentTestTotalExecutionTime_; } long TestResult::getCurrentGroupTotalExecutionTime() const { return currentGroupTotalExecutionTime_; }
null
299
cpp
blalor-cpputest
SimpleString.cpp
src/CppUTest/SimpleString.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/SimpleString.h" #include "CppUTest/PlatformSpecificFunctions.h" #include "CppUTest/MemoryLeakAllocator.h" MemoryLeakAllocator* SimpleString::stringAllocator_ = NULL; MemoryLeakAllocator* SimpleString::getStringAllocator() { if (stringAllocator_ == NULL) return StandardNewArrayAllocator::defaultAllocator(); return stringAllocator_; } void SimpleString::setStringAllocator(MemoryLeakAllocator* allocator) { stringAllocator_ = allocator; } /* Avoid using the memory leak detector INSIDE SimpleString as its used inside the detector */ char* SimpleString::allocStringBuffer(size_t _size) { return getStringAllocator()->alloc_memory(_size, __FILE__, __LINE__); } void SimpleString::deallocStringBuffer(char* str) { getStringAllocator()->free_memory(str, __FILE__, __LINE__); } char* SimpleString::getEmptyString() const { char* empty = allocStringBuffer(1); empty[0] = '\0'; return empty; } SimpleString::SimpleString(const char *otherBuffer) { if (otherBuffer == 0) { buffer_ = getEmptyString(); } else { size_t len = PlatformSpecificStrLen(otherBuffer) + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrCpy(buffer_, otherBuffer); } } SimpleString::SimpleString(const char *other, size_t repeatCount) { size_t len = PlatformSpecificStrLen(other) * repeatCount + 1; buffer_ = allocStringBuffer(len); char* next = buffer_; for (size_t i = 0; i < repeatCount; i++) { PlatformSpecificStrCpy(next, other); next += PlatformSpecificStrLen(other); } *next = 0; } SimpleString::SimpleString(const SimpleString& other) { size_t len = other.size() + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrCpy(buffer_, other.buffer_); } SimpleString& SimpleString::operator=(const SimpleString& other) { if (this != &other) { deallocStringBuffer(buffer_); size_t len = other.size() + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrCpy(buffer_, other.buffer_); } return *this; } bool SimpleString::contains(const SimpleString& other) const { //strstr on some machines does not handle "" //the right way. "" should be found in any string if (PlatformSpecificStrLen(other.buffer_) == 0) return true; else if (PlatformSpecificStrLen(buffer_) == 0) return false; else return PlatformSpecificStrStr(buffer_, other.buffer_) != 0; } bool SimpleString::containsNoCase(const SimpleString& other) const { return toLower().contains(other.toLower()); } bool SimpleString::startsWith(const SimpleString& other) const { if (PlatformSpecificStrLen(other.buffer_) == 0) return true; else if (PlatformSpecificStrLen(buffer_) == 0) return false; else return PlatformSpecificStrStr(buffer_, other.buffer_) == buffer_; } bool SimpleString::endsWith(const SimpleString& other) const { size_t buffer_length = PlatformSpecificStrLen(buffer_); size_t other_buffer_length = PlatformSpecificStrLen(other.buffer_); if (other_buffer_length == 0) return true; if (buffer_length == 0) return false; if (buffer_length < other_buffer_length) return false; return PlatformSpecificStrCmp(buffer_ + buffer_length - other_buffer_length, other.buffer_) == 0; } size_t SimpleString::count(const SimpleString& substr) const { size_t num = 0; char* str = buffer_; while ((str = PlatformSpecificStrStr(str, substr.buffer_))) { num++; str++; } return num; } void SimpleString::split(const SimpleString& delimiter, SimpleStringCollection& col) const { size_t num = count(delimiter); size_t extraEndToken = (endsWith(delimiter)) ? 0 : 1; col.allocate(num + extraEndToken); char* str = buffer_; char* prev; for (size_t i = 0; i < num; ++i) { prev = str; str = PlatformSpecificStrStr(str, delimiter.buffer_) + 1; size_t len = str - prev; char* sub = allocStringBuffer(len + 1); PlatformSpecificStrNCpy(sub, prev, len); sub[len] = '\0'; col[i] = sub; deallocStringBuffer(sub); } if (extraEndToken) { col[num] = str; } } void SimpleString::replace(char to, char with) { size_t s = size(); for (size_t i = 0; i < s; i++) { if (buffer_[i] == to) buffer_[i] = with; } } void SimpleString::replace(const char* to, const char* with) { size_t c = count(to); size_t len = size(); size_t tolen = PlatformSpecificStrLen(to); size_t withlen = PlatformSpecificStrLen(with); size_t newsize = len + (withlen * c) - (tolen * c) + 1; if (newsize) { char* newbuf = allocStringBuffer(newsize); for (size_t i = 0, j = 0; i < len;) { if (PlatformSpecificStrNCmp(&buffer_[i], to, tolen) == 0) { PlatformSpecificStrNCpy(&newbuf[j], with, withlen); j += withlen; i += tolen; } else { newbuf[j] = buffer_[i]; j++; i++; } } deallocStringBuffer(buffer_); buffer_ = newbuf; buffer_[newsize - 1] = '\0'; } else { buffer_ = getEmptyString(); buffer_[0] = '\0'; } } SimpleString SimpleString::toLower() const { SimpleString str(*this); size_t str_size = str.size(); for (size_t i = 0; i < str_size; i++) str.buffer_[i] = PlatformSpecificToLower(str.buffer_[i]); return str; } const char *SimpleString::asCharString() const { return buffer_; } size_t SimpleString::size() const { return PlatformSpecificStrLen(buffer_); } bool SimpleString::isEmpty() const { return size() == 0; } SimpleString::~SimpleString() { deallocStringBuffer(buffer_); } bool operator==(const SimpleString& left, const SimpleString& right) { return 0 == PlatformSpecificStrCmp(left.asCharString(), right.asCharString()); } bool SimpleString::equalsNoCase(const SimpleString& str) const { return toLower() == str.toLower(); } bool operator!=(const SimpleString& left, const SimpleString& right) { return !(left == right); } SimpleString SimpleString::operator+(const SimpleString& rhs) { SimpleString t(buffer_); t += rhs.buffer_; return t; } SimpleString& SimpleString::operator+=(const SimpleString& rhs) { return operator+=(rhs.buffer_); } SimpleString& SimpleString::operator+=(const char* rhs) { size_t len = this->size() + PlatformSpecificStrLen(rhs) + 1; char* tbuffer = allocStringBuffer(len); PlatformSpecificStrCpy(tbuffer, this->buffer_); PlatformSpecificStrCat(tbuffer, rhs); deallocStringBuffer(buffer_); buffer_ = tbuffer; return *this; } void SimpleString::padStringsToSameLength(SimpleString& str1, SimpleString& str2, char padCharacter) { if (str1.size() > str2.size()) { padStringsToSameLength(str2, str1, padCharacter); return; } char pad[2]; pad[0] = padCharacter; pad[1] = 0; str1 = SimpleString(pad, str2.size() - str1.size()) + str1; } SimpleString SimpleString::subString(size_t beginPos, size_t amount) const { if (beginPos > size()-1) return ""; SimpleString newString = buffer_ + beginPos; if (newString.size() > amount) newString.buffer_[amount] = '\0'; return newString; } void SimpleString::copyToBuffer(char* bufferToCopy, size_t bufferSize) const { if (bufferToCopy == NULL || bufferSize == 0) return; size_t sizeToCopy = (bufferSize-1 < size()) ? bufferSize-1 : size(); PlatformSpecificStrNCpy(bufferToCopy, buffer_, sizeToCopy); bufferToCopy[sizeToCopy] = '\0'; } SimpleString StringFrom(bool value) { return SimpleString(StringFromFormat("%s", value ? "true" : "false")); } SimpleString StringFrom(const char *value) { return SimpleString(value); } SimpleString StringFromOrNull(const char * expected) { return (expected) ? StringFrom(expected) : "(null)"; } SimpleString StringFrom(int value) { return StringFromFormat("%d", value); } SimpleString StringFrom(long value) { return StringFromFormat("%ld", value); } SimpleString StringFrom(const void* value) { return SimpleString("0x") + HexStringFrom((long) value); } SimpleString HexStringFrom(long value) { return StringFromFormat("%lx", value); } SimpleString StringFrom(double value, int precision) { SimpleString format = StringFromFormat("%%.%df", precision); return StringFromFormat(format.asCharString(), value); } SimpleString StringFrom(char value) { return StringFromFormat("%c", value); } SimpleString StringFrom(const SimpleString& value) { return SimpleString(value); } SimpleString StringFromFormat(const char* format, ...) { SimpleString resultString; va_list arguments; va_start(arguments, format); resultString = VStringFromFormat(format, arguments); va_end(arguments); return resultString; } #if CPPUTEST_USE_STD_CPP_LIB #include <string> SimpleString StringFrom(const std::string& value) { return SimpleString(value.c_str()); } SimpleString StringFrom(uint32_t i) { return StringFromFormat("%10u (0x%08x)", i, i); } SimpleString StringFrom(uint16_t i) { return StringFromFormat("%5u (0x%04x)", i, i); } SimpleString StringFrom(uint8_t i) { return StringFromFormat("%3u (0x%02x)", i, i); } #endif //Kludge to get a va_copy in VC++ V6 #ifndef va_copy #define va_copy(copy, original) copy = original; #endif SimpleString VStringFromFormat(const char* format, va_list args) { va_list argsCopy; va_copy(argsCopy, args); enum { sizeOfdefaultBuffer = 100 }; char defaultBuffer[sizeOfdefaultBuffer]; SimpleString resultString; int size = PlatformSpecificVSNprintf(defaultBuffer, sizeOfdefaultBuffer, format, args); if (size < sizeOfdefaultBuffer) { resultString = SimpleString(defaultBuffer); } else { char* newBuffer = SimpleString::allocStringBuffer(size + 1); PlatformSpecificVSNprintf(newBuffer, size + 1, format, argsCopy); resultString = SimpleString(newBuffer); SimpleString::deallocStringBuffer(newBuffer); } return resultString; } SimpleStringCollection::SimpleStringCollection() { collection_ = 0; size_ = 0; } void SimpleStringCollection::allocate(size_t _size) { if (collection_) delete[] collection_; size_ = _size; collection_ = new SimpleString[size_]; } SimpleStringCollection::~SimpleStringCollection() { delete[] (collection_); } size_t SimpleStringCollection::size() const { return size_; } SimpleString& SimpleStringCollection::operator[](size_t index) { if (index >= size_) { empty_ = ""; return empty_; } return collection_[index]; }
null
300
cpp
blalor-cpputest
MemoryLeakWarningPlugin.cpp
src/CppUTest/MemoryLeakWarningPlugin.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/MemoryLeakWarningPlugin.h" #include "CppUTest/MemoryLeakDetector.h" #include "CppUTest/MemoryLeakAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" class MemoryLeakWarningReporter: public MemoryLeakFailure { public: virtual ~MemoryLeakWarningReporter() { } ; virtual void fail(char* fail_string) { FAIL(fail_string); } }; static MemoryLeakWarningReporter* globalReporter = 0; static MemoryLeakDetector* globalDetector = 0; void destroyDetector() { PlatformSpecificFree(globalDetector); globalReporter->~MemoryLeakWarningReporter(); PlatformSpecificFree(globalReporter); globalReporter = 0; globalDetector = 0; } MemoryLeakDetector* MemoryLeakWarningPlugin::getGlobalDetector() { if (globalDetector == 0) { /* Want to void using operator new here, however.. still need to init the vtable. * Now just memcpy a local stack variable in the malloced memory. Ought to work everywhere :)) */ MemoryLeakWarningReporter reporter; globalReporter = (MemoryLeakWarningReporter*) PlatformSpecificMalloc(sizeof(MemoryLeakWarningReporter)); PlatformSpecificMemCpy(globalReporter, &reporter, sizeof(MemoryLeakWarningReporter)); globalDetector = (MemoryLeakDetector*) PlatformSpecificMalloc(sizeof(MemoryLeakDetector)); if (globalDetector == 0) FAIL("operator new(size, bool) not enough memory"); globalDetector->init(globalReporter); } return globalDetector; } MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::firstPlugin_ = 0; MemoryLeakWarningPlugin* MemoryLeakWarningPlugin::getFirstPlugin() { return firstPlugin_; } MemoryLeakDetector* MemoryLeakWarningPlugin::getMemoryLeakDetector() { return memLeakDetector_; } void MemoryLeakWarningPlugin::ignoreAllLeaksInTest() { ignoreAllWarnings_ = true; } void MemoryLeakWarningPlugin::expectLeaksInTest(int n) { expectedLeaks_ = n; } MemoryLeakWarningPlugin::MemoryLeakWarningPlugin(const SimpleString& name, MemoryLeakDetector* localDetector) : TestPlugin(name), ignoreAllWarnings_(false), expectedLeaks_(0) { if (firstPlugin_ == 0) firstPlugin_ = this; if (localDetector) memLeakDetector_ = localDetector; else memLeakDetector_ = getGlobalDetector(); memLeakDetector_->enable(); } MemoryLeakWarningPlugin::~MemoryLeakWarningPlugin() { if (this == firstPlugin_) firstPlugin_ = 0; } void MemoryLeakWarningPlugin::preTestAction(Utest& /*test*/, TestResult& result) { memLeakDetector_->startChecking(); failureCount_ = result.getFailureCount(); } void MemoryLeakWarningPlugin::postTestAction(Utest& test, TestResult& result) { memLeakDetector_->stopChecking(); int leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_checking); if (!ignoreAllWarnings_ && expectedLeaks_ != leaks && failureCount_ == result.getFailureCount()) { TestFailure f(&test, memLeakDetector_->report(mem_leak_period_checking)); result.addFailure(f); } memLeakDetector_->markCheckingPeriodLeaksAsNonCheckingPeriod(); ignoreAllWarnings_ = false; expectedLeaks_ = 0; } const char* MemoryLeakWarningPlugin::FinalReport(int toBeDeletedLeaks) { int leaks = memLeakDetector_->totalMemoryLeaks(mem_leak_period_enabled); if (leaks != toBeDeletedLeaks) return memLeakDetector_->report(mem_leak_period_enabled); return ""; } #if CPPUTEST_USE_MEM_LEAK_DETECTION #undef new #if CPPUTEST_USE_STD_CPP_LIB #define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) if (memory == NULL) throw std::bad_alloc(); #define UT_THROW(except) throw (except) #define UT_THROW_EMPTY() throw () #else #define UT_THROW_BAD_ALLOC_WHEN_NULL(memory) #define UT_THROW(except) #define UT_THROW_EMPTY() #endif void* operator new(size_t size) UT_THROW(std::bad_alloc) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(MemoryLeakAllocator::getCurrentNewAllocator(), size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } void* operator new(size_t size, const char* file, int line) UT_THROW(std::bad_alloc) { void *memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(MemoryLeakAllocator::getCurrentNewAllocator(), size, (char*) file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } void operator delete(void* mem) UT_THROW_EMPTY() { MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(MemoryLeakAllocator::getCurrentNewAllocator(), (char*) mem); } void* operator new[](size_t size) UT_THROW(std::bad_alloc) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(MemoryLeakAllocator::getCurrentNewArrayAllocator(), size); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } void* operator new [](size_t size, const char* file, int line) UT_THROW(std::bad_alloc) { void* memory = MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(MemoryLeakAllocator::getCurrentNewArrayAllocator(), size, (char*) file, line); UT_THROW_BAD_ALLOC_WHEN_NULL(memory); return memory; } void operator delete[](void* mem) UT_THROW_EMPTY() { MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) mem); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(MemoryLeakAllocator::getCurrentNewArrayAllocator(), (char*) mem); } #endif
null
301
cpp
blalor-cpputest
TestFailure.cpp
src/CppUTest/TestFailure.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestFailure.h" #include "CppUTest/TestOutput.h" #include "CppUTest/PlatformSpecificFunctions.h" SimpleString removeAllPrintableCharactersFrom(const SimpleString& str) { size_t bufferSize = str.size()+1; char* buffer = (char*) PlatformSpecificMalloc(bufferSize); str.copyToBuffer(buffer, bufferSize); for (size_t i = 0; i < bufferSize-1; i++) if (buffer[i] != '\t' && buffer[i] != '\n') buffer[i] = ' '; SimpleString result(buffer); PlatformSpecificFree(buffer); return result; } SimpleString addMarkerToString(const SimpleString& str, int markerPos) { size_t bufferSize = str.size()+1; char* buffer = (char*) PlatformSpecificMalloc(bufferSize); str.copyToBuffer(buffer, bufferSize); buffer[markerPos] = '^'; SimpleString result(buffer); PlatformSpecificFree(buffer); return result; } TestFailure::TestFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& theMessage) : testName_(test->getFormattedName()), fileName_(fileName), lineNumber_(lineNumber), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_(theMessage) { } TestFailure::TestFailure(Utest* test, const SimpleString& theMessage) : testName_(test->getFormattedName()), fileName_(test->getFile()), lineNumber_(test->getLineNumber()), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_(theMessage) { } TestFailure::TestFailure(Utest* test, const char* fileName, int lineNum) : testName_(test->getFormattedName()), fileName_(fileName), lineNumber_(lineNum), testFileName_(test->getFile()), testLineNumber_(test->getLineNumber()), message_("no message") { } TestFailure::TestFailure(const TestFailure& f) : testName_(f.testName_), fileName_(f.fileName_), lineNumber_(f.lineNumber_), testFileName_(f.testFileName_), testLineNumber_(f.testLineNumber_), message_(f.message_) { } TestFailure::~TestFailure() { } SimpleString TestFailure::getFileName() const { return fileName_; } SimpleString TestFailure::getTestFileName() const { return testFileName_; } SimpleString TestFailure::getTestName() const { return testName_; } int TestFailure::getFailureLineNumber() const { return lineNumber_; } int TestFailure::getTestLineNumber() const { return testLineNumber_; } SimpleString TestFailure::getMessage() const { return message_; } bool TestFailure::isOutsideTestFile() const { return testFileName_ != fileName_; } bool TestFailure::isInHelperFunction() const { return lineNumber_ < testLineNumber_; } SimpleString TestFailure::createButWasString(const SimpleString& expected, const SimpleString& actual) { const char* format = "expected <%s>\n\tbut was <%s>"; return StringFromFormat(format, expected.asCharString(), actual.asCharString()); } SimpleString TestFailure::createDifferenceAtPosString(const SimpleString& actual, int position) { SimpleString result; const int extraCharactersWindow = 20; const int halfOfExtraCharactersWindow = extraCharactersWindow / 2; SimpleString paddingForPreventingOutOfBounds (" ", halfOfExtraCharactersWindow); SimpleString actualString = paddingForPreventingOutOfBounds + actual + paddingForPreventingOutOfBounds; SimpleString differentString = StringFromFormat("difference starts at position %d at: <", position); result += "\n"; result += StringFromFormat("\t%s%s>\n", differentString.asCharString(), actualString.subString(position, extraCharactersWindow).asCharString()); SimpleString markString = actualString.subString(position, halfOfExtraCharactersWindow+1); markString = removeAllPrintableCharactersFrom(markString); markString = addMarkerToString(markString, halfOfExtraCharactersWindow); result += StringFromFormat("\t%s%s", SimpleString(" ", differentString.size()).asCharString(), markString.asCharString()); return result; } EqualsFailure::EqualsFailure(Utest* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : TestFailure(test, fileName, lineNumber) { message_ = createButWasString(StringFromOrNull(expected), StringFromOrNull(actual)); } EqualsFailure::EqualsFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) : TestFailure(test, fileName, lineNumber) { message_ = createButWasString(expected, actual); } static SimpleString StringFromOrNan(double d) { if (PlatformSpecificIsNan(d)) return "Nan - Not a number"; return StringFrom(d); } DoublesEqualFailure::DoublesEqualFailure(Utest* test, const char* fileName, int lineNumber, double expected, double actual, double threshold) : TestFailure(test, fileName, lineNumber) { message_ = createButWasString(StringFromOrNan(expected), StringFromOrNan(actual)); message_ += " threshold used was <"; message_ += StringFromOrNan(threshold); message_ += ">"; if (PlatformSpecificIsNan(expected) || PlatformSpecificIsNan(actual) || PlatformSpecificIsNan(threshold)) message_ += "\n\tCannot make comparisons with Nan"; } CheckEqualFailure::CheckEqualFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) : TestFailure(test, fileName, lineNumber) { int failStart; for (failStart = 0; actual.asCharString()[failStart] == expected.asCharString()[failStart]; failStart++) ; message_ = createButWasString(expected, actual); message_ += createDifferenceAtPosString(actual, failStart); } ContainsFailure::ContainsFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& expected, const SimpleString& actual) : TestFailure(test, fileName, lineNumber) { const char* format = "actual <%s>\n\tdid not contain <%s>"; message_ = StringFromFormat(format, actual.asCharString(), expected.asCharString()); } CheckFailure::CheckFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& checkString, const SimpleString& conditionString) : TestFailure(test, fileName, lineNumber) { message_ = checkString; message_ += "("; message_ += conditionString; message_ += ") failed"; } FailFailure::FailFailure(Utest* test, const char* fileName, int lineNumber, const SimpleString& message) : TestFailure(test, fileName, lineNumber) { message_ = message; } LongsEqualFailure::LongsEqualFailure(Utest* test, const char* fileName, int lineNumber, long expected, long actual) : TestFailure(test, fileName, lineNumber) { SimpleString aDecimal = StringFrom(actual); SimpleString aHex = HexStringFrom(actual); SimpleString eDecimal = StringFrom(expected); SimpleString eHex = HexStringFrom(expected); SimpleString::padStringsToSameLength(aDecimal, eDecimal, ' '); SimpleString::padStringsToSameLength(aHex, eHex, '0'); SimpleString actualReported = aDecimal + " 0x" + aHex; SimpleString expectedReported = eDecimal + " 0x" + eHex; message_ = createButWasString(expectedReported, actualReported); } StringEqualFailure::StringEqualFailure(Utest* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : TestFailure(test, fileName, lineNumber) { int failStart; for (failStart = 0; actual[failStart] == expected[failStart]; failStart++) ; message_ = createButWasString(expected, actual); message_ += createDifferenceAtPosString(actual, failStart); } StringEqualNoCaseFailure::StringEqualNoCaseFailure(Utest* test, const char* fileName, int lineNumber, const char* expected, const char* actual) : TestFailure(test, fileName, lineNumber) { int failStart; for (failStart = 0; PlatformSpecificToLower(actual[failStart]) == PlatformSpecificToLower(expected[failStart]); failStart++) ; message_ = createButWasString(expected, actual); message_ += createDifferenceAtPosString(actual, failStart); }
null
302
cpp
blalor-cpputest
MemoryLeakAllocator.cpp
src/CppUTest/MemoryLeakAllocator.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/MemoryLeakAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" static char* checkedMalloc(size_t size) { char* mem = (char*) PlatformSpecificMalloc(size); if (mem == 0) FAIL("malloc returned nul pointer"); return mem; } MemoryLeakAllocator* MemoryLeakAllocator::currentNewAllocator = 0; MemoryLeakAllocator* MemoryLeakAllocator::currentNewArrayAllocator = 0; MemoryLeakAllocator* MemoryLeakAllocator::currentMallocAllocator = 0; bool MemoryLeakAllocator::isOfEqualType(MemoryLeakAllocator* allocator) { return PlatformSpecificStrCmp(this->name(), allocator->name()) == 0; } void MemoryLeakAllocator::setCurrentNewAllocator(MemoryLeakAllocator* allocator) { currentNewAllocator = allocator; } MemoryLeakAllocator* MemoryLeakAllocator::getCurrentNewAllocator() { if (currentNewAllocator == 0) setCurrentNewAllocatorToDefault(); return currentNewAllocator; } void MemoryLeakAllocator::setCurrentNewAllocatorToDefault() { currentNewAllocator = StandardNewAllocator::defaultAllocator(); } void MemoryLeakAllocator::setCurrentNewArrayAllocator(MemoryLeakAllocator* allocator) { currentNewArrayAllocator = allocator; } MemoryLeakAllocator* MemoryLeakAllocator::getCurrentNewArrayAllocator() { if (currentNewArrayAllocator == 0) setCurrentNewArrayAllocatorToDefault(); return currentNewArrayAllocator; } void MemoryLeakAllocator::setCurrentNewArrayAllocatorToDefault() { currentNewArrayAllocator = StandardNewArrayAllocator::defaultAllocator(); } void MemoryLeakAllocator::setCurrentMallocAllocator(MemoryLeakAllocator* allocator) { currentMallocAllocator = allocator; } MemoryLeakAllocator* MemoryLeakAllocator::getCurrentMallocAllocator() { if (currentMallocAllocator == 0) setCurrentMallocAllocatorToDefault(); return currentMallocAllocator; } void MemoryLeakAllocator::setCurrentMallocAllocatorToDefault() { currentMallocAllocator = StandardMallocAllocator::defaultAllocator(); } bool MemoryLeakAllocator::allocateMemoryLeakNodeSeparately() { return false; } char* MemoryLeakAllocator::allocMemoryLeakNode(size_t size) { return alloc_memory(size, "MemoryLeakNode", 1); } void MemoryLeakAllocator::freeMemoryLeakNode(char* memory) { free_memory(memory, "MemoryLeakNode", 1); } char* StandardMallocAllocator::alloc_memory(size_t size, const char*, int) { return checkedMalloc(size); } void StandardMallocAllocator::free_memory(char* memory, const char*, int) { PlatformSpecificFree(memory); } const char* StandardMallocAllocator::name() { return "Standard Malloc Allocator"; } const char* StandardMallocAllocator::alloc_name() { return "malloc"; } const char* StandardMallocAllocator::free_name() { return "free"; } bool StandardMallocAllocator::allocateMemoryLeakNodeSeparately() { return true; } MemoryLeakAllocator* StandardMallocAllocator::defaultAllocator() { static StandardMallocAllocator allocator; return &allocator; } char* StandardNewAllocator::alloc_memory(size_t size, const char*, int) { return checkedMalloc(size); } void StandardNewAllocator::free_memory(char* memory, const char*, int) { PlatformSpecificFree(memory); } const char* StandardNewAllocator::name() { return "Standard New Allocator"; } const char* StandardNewAllocator::alloc_name() { return "new"; } const char* StandardNewAllocator::free_name() { return "delete"; } MemoryLeakAllocator* StandardNewAllocator::defaultAllocator() { static StandardNewAllocator allocator; return &allocator; } char* StandardNewArrayAllocator::alloc_memory(size_t size, const char*, int) { return checkedMalloc(size); } void StandardNewArrayAllocator::free_memory(char* memory, const char*, int) { PlatformSpecificFree(memory); } const char* StandardNewArrayAllocator::name() { return "Standard New [] Allocator"; } const char* StandardNewArrayAllocator::alloc_name() { return "new []"; } const char* StandardNewArrayAllocator::free_name() { return "delete []"; } MemoryLeakAllocator* StandardNewArrayAllocator::defaultAllocator() { static StandardNewArrayAllocator allocator; return &allocator; } char* NullUnknownAllocator::alloc_memory(size_t /*size*/, const char*, int) { return 0; } void NullUnknownAllocator::free_memory(char* /*memory*/, const char*, int) { } const char* NullUnknownAllocator::name() { return "Null Allocator"; } const char* NullUnknownAllocator::alloc_name() { return "unknown"; } const char* NullUnknownAllocator::free_name() { return "unknown"; } MemoryLeakAllocator* NullUnknownAllocator::defaultAllocator() { static NullUnknownAllocator allocator; return &allocator; }
null
303
cpp
blalor-cpputest
TestRegistry.cpp
src/CppUTest/TestRegistry.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" TestRegistry::TestRegistry() : tests_(&NullTest::instance()), nameFilter_(0), groupFilter_(0), firstPlugin_(NullTestPlugin::instance()) { } TestRegistry::~TestRegistry() { cleanup(); } void TestRegistry::cleanup() { delete nameFilter_; delete groupFilter_; nameFilter_ = 0; groupFilter_ = 0; } void TestRegistry::addTest(Utest *test) { tests_ = test->addTest(tests_); } void TestRegistry::runAllTests(TestResult& result) { bool groupStart = true; result.testsStarted(); for (Utest *test = tests_; !test->isNull(); test = test->getNext()) { if (groupStart) { result.currentGroupStarted(test); groupStart = false; } result.setProgressIndicator(test->getProgressIndicator()); result.countTest(); if (testShouldRun(test, result)) { result.currentTestStarted(test); test->runOneTestWithPlugins(firstPlugin_, result); result.currentTestEnded(test); } if (endOfGroup(test)) { groupStart = true; result.currentGroupEnded(test); } } result.testsEnded(); } bool TestRegistry::endOfGroup(Utest* test) { return (test->isNull() || test->getGroup() != test->getNext()->getGroup()); } int TestRegistry::countTests() { return tests_->countTests(); } TestRegistry* TestRegistry::currentRegistry_ = 0; TestRegistry* TestRegistry::getCurrentRegistry() { static TestRegistry registry; return (currentRegistry_ == 0) ? &registry : currentRegistry_; } void TestRegistry::setCurrentRegistry(TestRegistry* registry) { currentRegistry_ = registry; } void TestRegistry::unDoLastAddTest() { tests_ = tests_->getNext(); } void TestRegistry::nameFilter(SimpleString f) { delete nameFilter_; nameFilter_ = new SimpleString(f); } void TestRegistry::groupFilter(SimpleString f) { delete groupFilter_; groupFilter_ = new SimpleString(f); } SimpleString TestRegistry::getGroupFilter() { return *groupFilter_; } SimpleString TestRegistry::getNameFilter() { return *nameFilter_; } bool TestRegistry::testShouldRun(Utest* test, TestResult& result) { if (groupFilter_ == 0) groupFilter_ = new SimpleString(); if (nameFilter_ == 0) nameFilter_ = new SimpleString(); if (test->shouldRun(*groupFilter_, *nameFilter_)) return true; else { result.countFilteredOut(); return false; } } void TestRegistry::resetPlugins() { firstPlugin_ = NullTestPlugin::instance(); } void TestRegistry::installPlugin(TestPlugin* plugin) { firstPlugin_ = plugin->addPlugin(firstPlugin_); } TestPlugin* TestRegistry::getFirstPlugin() { return firstPlugin_; } TestPlugin* TestRegistry::getPluginByName(const SimpleString& name) { return firstPlugin_->getPluginByName(name); } void TestRegistry::removePluginByName(const SimpleString& name) { if (firstPlugin_->removePluginByName(name) == firstPlugin_) firstPlugin_ = firstPlugin_->getNext(); if (firstPlugin_->getName() == name) firstPlugin_ = firstPlugin_->getNext(); firstPlugin_->removePluginByName(name); } Utest* TestRegistry::getFirstTest() { return tests_; } Utest* TestRegistry::getLastTest() { Utest* current = tests_; while (!current->getNext()->isNull()) current = current->getNext(); return current; } Utest* TestRegistry::getTestWithNext(Utest* test) { Utest* current = tests_; while (!current->getNext()->isNull() && current->getNext() != test) current = current->getNext(); return current; }
null
304
cpp
blalor-cpputest
Utest.cpp
src/CppUTest/Utest.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestRegistry.h" #include "CppUTest/PlatformSpecificFunctions.h" #include "CppUTest/TestOutput.h" bool doubles_equal(double d1, double d2, double threshold) { if (PlatformSpecificIsNan(d1) || PlatformSpecificIsNan(d2) || PlatformSpecificIsNan(threshold)) return false; return PlatformSpecificFabs(d1 - d2) <= threshold; } /* Sometimes stubs use the CppUTest assertions. * Its not correct to do so, but this small helper class will prevent a segmentation fault and instead * will give an error message and also the file/line of the check that was executed outside the tests. */ class OutsideTestRunnerUTest: public Utest { public: static OutsideTestRunnerUTest& instance() { static OutsideTestRunnerUTest instance_; return instance_; } virtual TestResult& getTestResult() { return defaultTestResult; } virtual void exitCurrentTest() { } virtual ~OutsideTestRunnerUTest() { } private: OutsideTestRunnerUTest() : Utest("\n\t NOTE: Assertion happened without being in a test run (perhaps in main?)", "\n\t Something is very wrong. Check this assertion and fix", "unknown file", 0), defaultTestResult(defaultOutput) { } ConsoleTestOutput defaultOutput; TestResult defaultTestResult; }; Utest::Utest() : group_("UndefinedTestGroup"), name_("UndefinedTest"), file_("UndefinedFile"), lineNumber_(0), next_(&NullTest::instance()) { } Utest::Utest(const char* groupName, const char* testName, const char* fileName, int lineNumber) : group_(groupName), name_(testName), file_(fileName), lineNumber_(lineNumber), next_(&NullTest::instance()) { } Utest::Utest(const char* groupName, const char* testName, const char* fileName, int lineNumber, Utest* nextTest) : group_(groupName), name_(testName), file_(fileName), lineNumber_(lineNumber), next_(nextTest) { } Utest::~Utest() { } void Utest::runOneTestWithPlugins(TestPlugin* plugin, TestResult& result) { executePlatformSpecificRunOneTest(plugin, result); } void Utest::runOneTest(TestPlugin* plugin, TestResult& result) { plugin->runAllPreTestAction(*this, result); run(result); plugin->runAllPostTestAction(*this, result); } void Utest::run(TestResult& result) { //save test context, so that test class can be tested Utest* savedTest = getCurrent(); TestResult* savedResult = getTestResult(); result.countRun(); setTestResult(&result); setCurrentTest(this); if (executePlatformSpecificSetup()) { executePlatformSpecificTestBody(); } executePlatformSpecificTeardown(); setCurrentTest(savedTest); setTestResult(savedResult); } void Utest::exitCurrentTest() { executePlatformSpecificExitCurrentTest(); } Utest *Utest::getNext() const { return next_; } Utest* Utest::addTest(Utest *test) { next_ = test; return this; } int Utest::countTests() { return next_->countTests() + 1; } bool Utest::isNull() const { return false; } SimpleString Utest::getMacroName() const { return "TEST"; } const SimpleString Utest::getName() const { return SimpleString(name_); } const SimpleString Utest::getGroup() const { return SimpleString(group_); } SimpleString Utest::getFormattedName() const { SimpleString formattedName(getMacroName()); formattedName += "("; formattedName += group_; formattedName += ", "; formattedName += name_; formattedName += ")"; return formattedName; } const char* Utest::getProgressIndicator() const { return "."; } void Utest::setFileName(const char* fileName) { file_ = fileName; } void Utest::setLineNumber(int lineNumber) { lineNumber_ = lineNumber; } void Utest::setGroupName(const char* groupName) { group_ = groupName; } void Utest::setTestName(const char* testName) { name_ = testName; } const SimpleString Utest::getFile() const { return SimpleString(file_); } int Utest::getLineNumber() const { return lineNumber_; } void Utest::setup() { } void Utest::testBody() { } void Utest::teardown() { } bool Utest::shouldRun(const SimpleString& groupFilter, const SimpleString& nameFilter) const { SimpleString group(group_); SimpleString name(name_); if (group.contains(groupFilter) && name.contains(nameFilter)) return true; return false; } void Utest::failWith(const TestFailure& failure) { getTestResult()->addFailure(failure); Utest::getCurrent()->exitCurrentTest(); } void Utest::assertTrue(bool condition, const char * checkString, const char* conditionString, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (!condition) failWith(CheckFailure(this, fileName, lineNumber, checkString, conditionString)); } void Utest::fail(const char *text, const char* fileName, int lineNumber) { failWith(FailFailure(this, fileName, lineNumber, text)); } void Utest::assertCstrEqual(const char* expected, const char* actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if (actual == 0 || expected == 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual)); if (PlatformSpecificStrCmp(expected, actual) != 0) failWith(StringEqualFailure(this, fileName, lineNumber, expected, actual)); } void Utest::assertCstrNoCaseEqual(const char* expected, const char* actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if (actual == 0 || expected == 0) failWith(StringEqualNoCaseFailure(this, fileName, lineNumber, expected, actual)); if (!SimpleString(expected).equalsNoCase(actual)) failWith(StringEqualNoCaseFailure(this, fileName, lineNumber, expected, actual)); } void Utest::assertCstrContains(const char* expected, const char* actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if(actual == 0 || expected == 0) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual)); if (!SimpleString(actual).contains(expected)) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual)); } void Utest::assertCstrNoCaseContains(const char* expected, const char* actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (actual == 0 && expected == 0) return; if(actual == 0 || expected == 0) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual)); if (!SimpleString(actual).containsNoCase(expected)) failWith(ContainsFailure(this, fileName, lineNumber, expected, actual)); } void Utest::assertLongsEqual(long expected, long actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (expected != actual) { LongsEqualFailure f(this, fileName, lineNumber, expected, actual); getTestResult()->addFailure(f); Utest::getCurrent()->exitCurrentTest(); } } void Utest::assertPointersEqual(const void* expected, const void* actual, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (expected != actual) failWith(EqualsFailure(this, fileName, lineNumber, StringFrom(expected), StringFrom(actual))); } void Utest::assertDoublesEqual(double expected, double actual, double threshold, const char* fileName, int lineNumber) { getTestResult()->countCheck(); if (!doubles_equal(expected, actual, threshold)) failWith(DoublesEqualFailure(this, fileName, lineNumber, expected, actual, threshold)); } void Utest::print(const char *text, const char* fileName, int lineNumber) { SimpleString stringToPrint = "\n"; stringToPrint += fileName; stringToPrint += ":"; stringToPrint += StringFrom(lineNumber); stringToPrint += " "; stringToPrint += text; getTestResult()->print(stringToPrint.asCharString()); } void Utest::print(const SimpleString& text, const char* fileName, int lineNumber) { print(text.asCharString(), fileName, lineNumber); } TestResult* Utest::testResult_ = NULL; Utest* Utest::currentTest_ = NULL; void Utest::setTestResult(TestResult* result) { testResult_ = result; } void Utest::setCurrentTest(Utest* test) { currentTest_ = test; } TestResult* Utest::getTestResult() { if (testResult_ == NULL) return &OutsideTestRunnerUTest::instance().getTestResult(); return testResult_; } Utest* Utest::getCurrent() { if (currentTest_ == NULL) return &OutsideTestRunnerUTest::instance(); return currentTest_; } ////////////// NullTest //////////// NullTest::NullTest() : Utest("NullGroup", "NullName", "NullFile", -1, 0) { } NullTest::NullTest(const char* fileName, int lineNumber) : Utest("NullGroup", "NullName", fileName, lineNumber, 0) { } NullTest::~NullTest() { } NullTest& NullTest::instance() { static NullTest _instance; return _instance; } int NullTest::countTests() { return 0; } Utest* NullTest::getNext() const { return &instance(); } bool NullTest::isNull() const { return true; } ////////////// TestInstaller //////////// TestInstaller::TestInstaller(Utest* t, const char* groupName, const char* testName, const char* fileName, int lineNumber) { t->setGroupName(groupName); t->setTestName(testName); t->setFileName(fileName); t->setLineNumber(lineNumber); TestRegistry::getCurrentRegistry()->addTest(t); } TestInstaller::~TestInstaller() { } void TestInstaller::unDo() { TestRegistry::getCurrentRegistry()->unDoLastAddTest(); }
null
305
cpp
blalor-cpputest
TestHarness_c.cpp
src/CppUTest/TestHarness_c.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /////////////////////////////////////////////////////////////////////////////// // // TESTHARNESS_c.H // // /////////////////////////////////////////////////////////////////////////////// #include "CppUTest/TestHarness.h" #include "CppUTest/MemoryLeakDetector.h" #include "CppUTest/MemoryLeakAllocator.h" #include "CppUTest/PlatformSpecificFunctions.h" extern "C" { #include "CppUTest/TestHarness_c.h" void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, const char* fileName, int lineNumber) { CHECK_EQUAL_LOCATION((long)expected, (long)actual, fileName, lineNumber); } void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* fileName, int lineNumber) { DOUBLES_EQUAL_LOCATION(expected, actual, threshold, fileName, lineNumber); } void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* fileName, int lineNumber) { CHECK_EQUAL_LOCATION(expected, actual, fileName, lineNumber); } void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* fileName, int lineNumber) { STRCMP_EQUAL_LOCATION(expected, actual, fileName, lineNumber); } void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, int lineNumber) { FAIL_LOCATION(text, fileName, lineNumber); } void FAIL_C_LOCATION(const char* fileName, int lineNumber) { FAIL_LOCATION("", fileName, lineNumber); } void CHECK_C_LOCATION(int condition, const char* conditionString, const char* fileName, int lineNumber) { CHECK_LOCATION_TRUE(((condition) == 0 ? false : true), "CHECK_C", conditionString, fileName, lineNumber); } enum { NO_COUNTDOWN = -1, OUT_OF_MEMORRY = 0 }; static int malloc_out_of_memory_counter = NO_COUNTDOWN; static int malloc_count = 0; void cpputest_malloc_count_reset(void) { malloc_count = 0; } int cpputest_malloc_get_count() { return malloc_count; } void cpputest_malloc_set_out_of_memory() { MemoryLeakAllocator::setCurrentMallocAllocator(NullUnknownAllocator::defaultAllocator()); } void cpputest_malloc_set_not_out_of_memory() { malloc_out_of_memory_counter = NO_COUNTDOWN; MemoryLeakAllocator::setCurrentMallocAllocatorToDefault(); } void cpputest_malloc_set_out_of_memory_countdown(int count) { malloc_out_of_memory_counter = count; if (malloc_out_of_memory_counter == OUT_OF_MEMORRY) cpputest_malloc_set_out_of_memory(); } void* cpputest_malloc(size_t size) { return cpputest_malloc_location(size, "<unknown>", 0); } void* cpputest_calloc(size_t num, size_t size) { return cpputest_calloc_location(num, size, "<unknown>", 0); } void* cpputest_realloc(void* ptr, size_t size) { return cpputest_realloc_location(ptr, size, "<unknown>", 0); } void cpputest_free(void* buffer) { cpputest_free_location(buffer, "<unknown>", 0); } static void countdown() { if (malloc_out_of_memory_counter <= NO_COUNTDOWN) return; if (malloc_out_of_memory_counter == OUT_OF_MEMORRY) return; malloc_out_of_memory_counter--; if (malloc_out_of_memory_counter == OUT_OF_MEMORRY) cpputest_malloc_set_out_of_memory(); } void* cpputest_malloc_location(size_t size, const char* file, int line) { countdown(); malloc_count++; return MemoryLeakWarningPlugin::getGlobalDetector()->allocMemory(MemoryLeakAllocator::getCurrentMallocAllocator(), size, file, line); } void* cpputest_calloc_location(size_t num, size_t size, const char* file, int line) { void* mem = cpputest_malloc_location(num * size, file, line); PlatformSpecificMemset(mem, 0, num*size); return mem; } void* cpputest_realloc_location(void* memory, size_t size, const char* file, int line) { return MemoryLeakWarningPlugin::getGlobalDetector()->reallocMemory(MemoryLeakAllocator::getCurrentMallocAllocator(), (char*) memory, size, file, line); } void cpputest_free_location(void* buffer, const char* file, int line) { MemoryLeakWarningPlugin::getGlobalDetector()->invalidateMemory((char*) buffer); MemoryLeakWarningPlugin::getGlobalDetector()->deallocMemory(MemoryLeakAllocator::getCurrentMallocAllocator(), (char*) buffer, file, line); } }
null
306
cpp
blalor-cpputest
CommandLineArguments.cpp
src/CppUTest/CommandLineArguments.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/CommandLineArguments.h" #include "CppUTest/PlatformSpecificFunctions.h" CommandLineArguments::CommandLineArguments(int ac, const char** av) : ac_(ac), av_(av), verbose_(false), repeat_(1), groupFilter_(""), nameFilter_(""), outputType_(OUTPUT_ECLIPSE) { } CommandLineArguments::~CommandLineArguments() { } bool CommandLineArguments::parse(TestPlugin* plugin) { bool correctParameters = true; for (int i = 1; i < ac_; i++) { SimpleString argument = av_[i]; if (argument == "-v") verbose_ = true; else if (argument.startsWith("-r")) SetRepeatCount(ac_, av_, i); else if (argument.startsWith("-g")) SetGroupFilter(ac_, av_, i); else if (argument.startsWith("-n")) SetNameFilter(ac_, av_, i); else if (argument.startsWith("-o")) correctParameters = SetOutputType(ac_, av_, i); else if (argument.startsWith("-p")) correctParameters = plugin->parseAllArguments(ac_, av_, i); else correctParameters = false; if (correctParameters == false) { return false; } } return true; } const char* CommandLineArguments::usage() const { return "usage [-v] [-r#] [-g groupName] [-n testName] [-o{normal, junit}]\n"; } bool CommandLineArguments::isVerbose() const { return verbose_; } int CommandLineArguments::getRepeatCount() const { return repeat_; } SimpleString CommandLineArguments::getGroupFilter() const { return groupFilter_; } SimpleString CommandLineArguments::getNameFilter() const { return nameFilter_; } void CommandLineArguments::SetRepeatCount(int ac, const char** av, int& i) { repeat_ = 0; SimpleString repeatParameter(av[i]); if (repeatParameter.size() > 2) repeat_ = PlatformSpecificAtoI(av[i] + 2); else if (i + 1 < ac) { repeat_ = PlatformSpecificAtoI(av[i + 1]); if (repeat_ != 0) i++; } if (0 == repeat_) repeat_ = 2; } SimpleString CommandLineArguments::getParameterField(int ac, const char** av, int& i) { SimpleString parameter(av[i]); if (parameter.size() > 2) return av[i] + 2; else if (i + 1 < ac) return av[++i]; return ""; } void CommandLineArguments::SetGroupFilter(int ac, const char** av, int& i) { SimpleString gf = getParameterField(ac, av, i); groupFilter_ = gf; } void CommandLineArguments::SetNameFilter(int ac, const char** av, int& i) { nameFilter_ = getParameterField(ac, av, i); } bool CommandLineArguments::SetOutputType(int ac, const char** av, int& i) { SimpleString outputType = getParameterField(ac, av, i); if (outputType.size() == 0) return false; if (outputType == "normal" || outputType == "eclipse") { outputType_ = OUTPUT_ECLIPSE; return true; } if (outputType == "junit") { outputType_ = OUTPUT_JUNIT; return true; } return false; } bool CommandLineArguments::isEclipseOutput() const { return outputType_ == OUTPUT_ECLIPSE; } bool CommandLineArguments::isJUnitOutput() const { return outputType_ == OUTPUT_JUNIT; }
null
307
cpp
blalor-cpputest
NullJUnitTestOutput.cpp
src/CppUTest/Nulls/NullJUnitTestOutput.cpp
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/JUnitTestOutput.h" #include "CppUTest/TestResult.h" #include "CppUTest/Failure.h" //struct JUnitTestOutputImpl //{ // //}; // JUnitTestOutput::JUnitTestOutput() : impl_(0) { } JUnitTestOutput::~JUnitTestOutput() { } void JUnitTestOutput::resetTestGroupResult() { } void JUnitTestOutput::printTestsStarted() { } void JUnitTestOutput::printCurrentGroupStarted(const Utest& test) { } void JUnitTestOutput::printCurrentTestEnded(const TestResult& result) { } void JUnitTestOutput::printTestsEnded(const TestResult& result) { } void JUnitTestOutput::printCurrentGroupEnded(const TestResult& result) { } void JUnitTestOutput::printCurrentTestStarted(const Utest& test) { } void JUnitTestOutput::writeXmlHeader() { } void JUnitTestOutput::writeTestSuiteSummery() { } void JUnitTestOutput::writeProperties() { } void JUnitTestOutput::writeTestCases() { } void JUnitTestOutput::writeFailure(JUnitTestCaseResultNode* node) { } void JUnitTestOutput::writeFileEnding() { } void JUnitTestOutput::writeTestGroupToFile() { } void JUnitTestOutput::verbose() { } void JUnitTestOutput::print(const char*) { } void JUnitTestOutput::print(long) { } void JUnitTestOutput::print(const TestFailure& failure) { } void JUnitTestOutput::printTestRun(int number, int total) { } void JUnitTestOutput::flush() { } void JUnitTestOutput::openFileForWrite(const SimpleString& fileName) { } void JUnitTestOutput::writeToFile(const SimpleString& buffer) { } void JUnitTestOutput::closeFile() { }
null
308
cpp
blalor-cpputest
Platform.h
include/Platforms/StarterKit/Platform.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_Gcc_Platform_H #define D_Gcc_Platform_H #endif
null
309
cpp
blalor-cpputest
Platform.h
include/Platforms/VisualCpp/Platform.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. */ #ifdef _MSC_VER #pragma warning(disable:4786) #pragma warning(disable:4290) #pragma warning(disable:4996) #endif #ifdef WIN32 #ifdef _VC80_UPGRADE #pragma warning(disable:4996) #pragma warning(disable:4290) #else #define vsnprintf _vsnprintf #endif #endif
null
310
cpp
blalor-cpputest
stdint.h
include/Platforms/VisualCpp/stdint.h
null
/* ISO C9x 7.18 Integer types <stdint.h> * Based on ISO/IEC SC22/WG14 9899 Committee draft (SC22 N2794) * * THIS SOFTWARE IS NOT COPYRIGHTED * * Contributor: Danny Smith <[email protected]> * * This source code is offered for use in the public domain. You may * use, modify or distribute it freely. * * This code is distributed in the hope that it will be useful but * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY * DISCLAIMED. This includes but is not limited to warranties of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * Date: 2000-12-02 */ #ifndef _STDINT_H #define _STDINT_H #define __need_wint_t #define __need_wchar_t #include <stddef.h> /* 7.18.1.1 Exact-width integer types */ typedef signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned uint32_t; //typedef long long int64_t; //typedef unsigned long long uint64_t; /* 7.18.1.2 Minimum-width integer types */ typedef signed char int_least8_t; typedef unsigned char uint_least8_t; typedef short int_least16_t; typedef unsigned short uint_least16_t; typedef int int_least32_t; typedef unsigned uint_least32_t; //typedef long long int_least64_t; //typedef unsigned long long uint_least64_t; /* 7.18.1.3 Fastest minimum-width integer types * Not actually guaranteed to be fastest for all purposes * Here we use the exact-width types for 8 and 16-bit ints. */ typedef signed char int_fast8_t; typedef unsigned char uint_fast8_t; typedef short int_fast16_t; typedef unsigned short uint_fast16_t; typedef int int_fast32_t; typedef unsigned int uint_fast32_t; //typedef long long int_fast64_t; //typedef unsigned long long uint_fast64_t; /* 7.18.1.4 Integer types capable of holding object pointers */ #ifndef _INTPTR_T_DEFINED #define _INTPTR_T_DEFINED #ifdef _WIN64 typedef __int64 intptr_t; #else typedef int intptr_t; #endif #endif #ifndef _UINTPTR_T_DEFINED #define _UINTPTR_T_DEFINED #ifdef _WIN64 typedef unsigned __int64 uintptr_t; #else typedef unsigned int uintptr_t; #endif #endif /* 7.18.1.5 Greatest-width integer types */ //typedef long long intmax_t; //typedef unsigned long long uintmax_t; /* 7.18.2 Limits of specified-width integer types */ #if !defined ( __cplusplus) || defined (__STDC_LIMIT_MACROS) /* 7.18.2.1 Limits of exact-width integer types */ #define INT8_MIN (-128) #define INT16_MIN (-32768) #define INT32_MIN (-2147483647 - 1) #define INT64_MIN (-9223372036854775807LL - 1) #define INT8_MAX 127 #define INT16_MAX 32767 #define INT32_MAX 2147483647 #define INT64_MAX 9223372036854775807LL #define UINT8_MAX 0xff /* 255U */ #define UINT16_MAX 0xffff /* 65535U */ #define UINT32_MAX 0xffffffff /* 4294967295U */ #define UINT64_MAX 0xffffffffffffffffULL /* 18446744073709551615ULL */ /* 7.18.2.2 Limits of minimum-width integer types */ #define INT_LEAST8_MIN INT8_MIN #define INT_LEAST16_MIN INT16_MIN #define INT_LEAST32_MIN INT32_MIN #define INT_LEAST64_MIN INT64_MIN #define INT_LEAST8_MAX INT8_MAX #define INT_LEAST16_MAX INT16_MAX #define INT_LEAST32_MAX INT32_MAX #define INT_LEAST64_MAX INT64_MAX #define UINT_LEAST8_MAX UINT8_MAX #define UINT_LEAST16_MAX UINT16_MAX #define UINT_LEAST32_MAX UINT32_MAX #define UINT_LEAST64_MAX UINT64_MAX /* 7.18.2.3 Limits of fastest minimum-width integer types */ #define INT_FAST8_MIN INT8_MIN #define INT_FAST16_MIN INT16_MIN #define INT_FAST32_MIN INT32_MIN #define INT_FAST64_MIN INT64_MIN #define INT_FAST8_MAX INT8_MAX #define INT_FAST16_MAX INT16_MAX #define INT_FAST32_MAX INT32_MAX #define INT_FAST64_MAX INT64_MAX #define UINT_FAST8_MAX UINT8_MAX #define UINT_FAST16_MAX UINT16_MAX #define UINT_FAST32_MAX UINT32_MAX #define UINT_FAST64_MAX UINT64_MAX /* 7.18.2.4 Limits of integer types capable of holding object pointers */ #ifdef _WIN64 #define INTPTR_MIN INT64_MIN #define INTPTR_MAX INT64_MAX #define UINTPTR_MAX UINT64_MAX #else #define INTPTR_MIN INT32_MIN #define INTPTR_MAX INT32_MAX #define UINTPTR_MAX UINT32_MAX #endif /* 7.18.2.5 Limits of greatest-width integer types */ #define INTMAX_MIN INT64_MIN #define INTMAX_MAX INT64_MAX #define UINTMAX_MAX UINT64_MAX /* 7.18.3 Limits of other integer types */ #define PTRDIFF_MIN INTPTR_MIN #define PTRDIFF_MAX INTPTR_MAX #define SIG_ATOMIC_MIN INTPTR_MIN #define SIG_ATOMIC_MAX INTPTR_MAX #define SIZE_MAX UINTPTR_MAX #ifndef WCHAR_MIN /* also in wchar.h */ #define WCHAR_MIN 0 #define WCHAR_MAX 0xffff /* UINT16_MAX */ #endif /* * wint_t is unsigned short for compatibility with MS runtime */ #define WINT_MIN 0 #define WINT_MAX 0xffff /* UINT16_MAX */ #endif /* !defined ( __cplusplus) || defined __STDC_LIMIT_MACROS */ /* 7.18.4 Macros for integer constants */ #if !defined ( __cplusplus) || defined (__STDC_CONSTANT_MACROS) /* 7.18.4.1 Macros for minimum-width integer constants Accoding to Douglas Gwyn <[email protected]>: "This spec was changed in ISO/IEC 9899:1999 TC1; in ISO/IEC 9899:1999 as initially published, the expansion was required to be an integer constant of precisely matching type, which is impossible to accomplish for the shorter types on most platforms, because C99 provides no standard way to designate an integer constant with width less than that of type int. TC1 changed this to require just an integer constant *expression* with *promoted* type." */ #define INT8_C(val) val #define UINT8_C(val) val #define INT16_C(val) val #define UINT16_C(val) val #define INT32_C(val) val #define UINT32_C(val) val##U #define INT64_C(val) val##LL #define UINT64_C(val) val##ULL /* 7.18.4.2 Macros for greatest-width integer constants */ #define INTMAX_C(val) INT64_C(val) #define UINTMAX_C(val) UINT64_C(val) #endif /* !defined ( __cplusplus) || defined __STDC_CONSTANT_MACROS */ #endif
null
311
cpp
blalor-cpputest
Platform.h
include/Platforms/Symbian/Platform.h
null
#ifndef PLATFORM_H_ #define PLATFORM_H_ #endif /*PLATFORM_H_*/
null
312
cpp
blalor-cpputest
Platform.h
include/Platforms/Gcc/Platform.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_Gcc_Platform_H #define D_Gcc_Platform_H #endif
null
313
cpp
blalor-cpputest
MemoryReportFormatter.h
include/CppUTestExt/MemoryReportFormatter.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MemoryReportFormatter_h #define D_MemoryReportFormatter_h class TestOutput; class Utest; class MemoryReportFormatter { public: virtual ~MemoryReportFormatter(){} virtual void report_testgroup_start(TestResult* result, Utest& test)=0; virtual void report_testgroup_end(TestResult* result, Utest& test)=0; virtual void report_test_start(TestResult* result, Utest& test)=0; virtual void report_test_end(TestResult* result, Utest& test)=0; virtual void report_alloc_memory(TestResult* result, MemoryLeakAllocator* allocator, size_t size, char* memory, const char* file, int line)=0; virtual void report_free_memory(TestResult* result, MemoryLeakAllocator* allocator, char* memory, const char* file, int line)=0; }; class NormalMemoryReportFormatter : public MemoryReportFormatter { public: NormalMemoryReportFormatter(); virtual ~NormalMemoryReportFormatter(); virtual void report_testgroup_start(TestResult* /*result*/, Utest& /*test*/); virtual void report_testgroup_end(TestResult* /*result*/, Utest& /*test*/){}; virtual void report_test_start(TestResult* result, Utest& test); virtual void report_test_end(TestResult* result, Utest& test); virtual void report_alloc_memory(TestResult* result, MemoryLeakAllocator* allocator, size_t size, char* memory, const char* file, int line); virtual void report_free_memory(TestResult* result, MemoryLeakAllocator* allocator, char* memory, const char* file, int line); }; #endif
null
314
cpp
blalor-cpputest
OrderedTest.h
include/CppUTestExt/OrderedTest.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_OrderedTest_h #define D_OrderedTest_h class OrderedTest : public Utest { public: OrderedTest(); virtual ~OrderedTest(); virtual OrderedTest* addOrderedTest(OrderedTest* test); virtual OrderedTest* getNextOrderedTest(); int getLevel(); void setLevel(int level); static void addOrderedTestToHead(OrderedTest* test); static OrderedTest* getOrderedTestHead(); static bool firstOrderedTest(); static void setOrderedTestHead(OrderedTest* test); private: static OrderedTest* _orderedTestsHead; OrderedTest* _nextOrderedTest; int _level; }; class OrderedTestInstaller { public: explicit OrderedTestInstaller(OrderedTest* test, const char* groupName, const char* testName, const char* fileName, int lineNumber, int level); virtual ~OrderedTestInstaller(); private: void addOrderedTestInOrder(OrderedTest* test); void addOrderedTestInOrderNotAtHeadPosition(OrderedTest* test); }; #define TEST_ORDERED(testGroup, testName, testLevel) \ class TEST_##testGroup##_##testName##_Test : public TEST_GROUP_##CppUTestGroup##testGroup \ { public: TEST_##testGroup##_##testName##_Test () : TEST_GROUP_##CppUTestGroup##testGroup () {} \ void testBody(); } \ TEST_##testGroup##_##testName##_Instance; \ OrderedTestInstaller TEST_##testGroup##_##testName##_Installer(&TEST_##testGroup##_##testName##_Instance, #testGroup, #testName, __FILE__,__LINE__, testLevel); \ void TEST_##testGroup##_##testName##_Test::testBody() #endif
null
315
cpp
blalor-cpputest
MockExpectedFunctionsList.h
include/CppUTestExt/MockExpectedFunctionsList.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MockExpectedFunctionsList_h #define D_MockExpectedFunctionsList_h class MockExpectedFunctionCall; class MockNamedValue; class MockExpectedFunctionsList { public: MockExpectedFunctionsList(); virtual ~MockExpectedFunctionsList(); virtual void deleteAllExpectationsAndClearList(); virtual int size() const; virtual int amountOfExpectationsFor(const SimpleString& name) const; virtual int amountOfUnfulfilledExpectations() const; virtual bool hasUnfullfilledExpectations() const; virtual bool hasFulfilledExpectations() const; virtual bool hasUnfulfilledExpectationsBecauseOfMissingParameters() const; virtual bool hasExpectationWithName(const SimpleString& name) const; virtual bool hasCallsOutOfOrder() const; virtual bool isEmpty() const; virtual void addExpectedCall(MockExpectedFunctionCall* call); virtual void addExpectations(const MockExpectedFunctionsList& list); virtual void addExpectationsRelatedTo(const SimpleString& name, const MockExpectedFunctionsList& list); virtual void addUnfilfilledExpectations(const MockExpectedFunctionsList& list); virtual void onlyKeepExpectationsRelatedTo(const SimpleString& name); virtual void onlyKeepExpectationsWithParameter(const MockNamedValue& parameter); virtual void onlyKeepExpectationsWithParameterName(const SimpleString& name); virtual void onlyKeepExpectationsOnObject(void* objectPtr); virtual void onlyKeepUnfulfilledExpectations(); virtual void onlyKeepUnfulfilledExpectationsRelatedTo(const SimpleString& name); virtual void onlyKeepUnfulfilledExpectationsWithParameter(const MockNamedValue& parameter); virtual void onlyKeepUnfulfilledExpectationsOnObject(void* objectPtr); virtual MockExpectedFunctionCall* removeOneFulfilledExpectation(); virtual MockExpectedFunctionCall* removeOneFulfilledExpectationWithIgnoredParameters(); virtual void resetExpectations(); virtual void callWasMade(int callOrder); virtual void wasPassedToObject(); virtual void parameterWasPassed(const SimpleString& parameterName); virtual SimpleString unfulfilledFunctionsToString(const SimpleString& linePrefix = "") const; virtual SimpleString fulfilledFunctionsToString(const SimpleString& linePrefix = "") const; virtual SimpleString missingParametersToString() const; protected: virtual void pruneEmptyNodeFromList(); class MockExpectedFunctionsListNode { public: MockExpectedFunctionCall* expectedCall_; MockExpectedFunctionsListNode* next_; MockExpectedFunctionsListNode(MockExpectedFunctionCall* expectedCall) : expectedCall_(expectedCall), next_(NULL) {}; }; virtual MockExpectedFunctionsListNode* findNodeWithCallOrderOf(int callOrder) const; private: MockExpectedFunctionsListNode* head_; MockExpectedFunctionsList(const MockExpectedFunctionsList&); }; #endif
null
316
cpp
blalor-cpputest
MockActualFunctionCall.h
include/CppUTestExt/MockActualFunctionCall.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MockActualFunctionCall_h #define D_MockActualFunctionCall_h #include "CppUTestExt/MockFunctionCall.h" #include "CppUTestExt/MockExpectedFunctionsList.h" class MockFailureReporter; class MockFailure; class MockNamedValue; class MockActualFunctionCall : public MockFunctionCall { public: MockActualFunctionCall(int callOrder, MockFailureReporter* reporter, const MockExpectedFunctionsList& expectations); virtual ~MockActualFunctionCall(); virtual MockFunctionCall& withName(const SimpleString& name); virtual MockFunctionCall& withCallOrder(int); virtual MockFunctionCall& withParameter(const SimpleString& name, int value); virtual MockFunctionCall& withParameter(const SimpleString& name, double value); virtual MockFunctionCall& withParameter(const SimpleString& name, const char* value); virtual MockFunctionCall& withParameter(const SimpleString& name, void* value); virtual MockFunctionCall& withParameterOfType(const SimpleString& type, const SimpleString& name, void* value); virtual MockFunctionCall& andReturnValue(int value); virtual MockFunctionCall& andReturnValue(double value); virtual MockFunctionCall& andReturnValue(const char* value); virtual MockFunctionCall& andReturnValue(void* value); virtual bool hasReturnValue(); virtual MockNamedValue returnValue(); virtual MockFunctionCall& onObject(void* objectPtr); virtual bool isFulfilled() const; virtual bool hasFailed() const; virtual void checkExpectations(); virtual void setMockFailureReporter(MockFailureReporter* reporter); protected: virtual Utest* getTest() const; virtual void callHasSucceeded(); virtual void finnalizeCallWhenFulfilled(); virtual void failTest(const MockFailure& failure); virtual void checkActualParameter(const MockNamedValue& actualParameter); enum ActualCallState { CALL_IN_PROGESS, CALL_FAILED, CALL_SUCCEED }; virtual const char* stringFromState(ActualCallState state); virtual void setState(ActualCallState state); virtual void checkStateConsistency(ActualCallState oldState, ActualCallState newState); private: int callOrder_; MockFailureReporter* reporter_; ActualCallState state_; MockExpectedFunctionCall* _fulfilledExpectation; MockExpectedFunctionsList unfulfilledExpectations_; const MockExpectedFunctionsList& allExpectations_; }; #endif
null
317
cpp
blalor-cpputest
MockSupportPlugin.h
include/CppUTestExt/MockSupportPlugin.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MockSupportPlugin_h #define D_MockSupportPlugin_h #include "CppUTest/TestPlugin.h" #include "CppUTestExt/MockNamedValue.h" class MockSupportPlugin : public TestPlugin { public: MockSupportPlugin(const SimpleString& name = "MockSupportPLugin"); virtual ~MockSupportPlugin(); virtual void preTestAction(Utest&, TestResult&); virtual void postTestAction(Utest&, TestResult&); virtual void installComparator(const SimpleString& name, MockNamedValueComparator& comparator); private: MockNamedValueComparatorRepository repository_; }; #endif
null
318
cpp
blalor-cpputest
CodeMemoryReportFormatter.h
include/CppUTestExt/CodeMemoryReportFormatter.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_CodeMemoryReportFormatter_h #define D_CodeMemoryReportFormatter_h #include "CppUTestExt/MemoryReportFormatter.h" class CodeReportingAllocationNode; class CodeMemoryReportFormatter : public MemoryReportFormatter { private: CodeReportingAllocationNode* codeReportingList_; MemoryLeakAllocator* internalAllocator_; public: CodeMemoryReportFormatter(MemoryLeakAllocator* internalAllocator); virtual ~CodeMemoryReportFormatter(); virtual void report_testgroup_start(TestResult* result, Utest& test); virtual void report_testgroup_end(TestResult* /*result*/, Utest& /*test*/){}; virtual void report_test_start(TestResult* result, Utest& test); virtual void report_test_end(TestResult* result, Utest& test); virtual void report_alloc_memory(TestResult* result, MemoryLeakAllocator* allocator, size_t size, char* memory, const char* file, int line); virtual void report_free_memory(TestResult* result, MemoryLeakAllocator* allocator, char* memory, const char* file, int line); private: void addNodeToList(const char* variableName, void* memory, CodeReportingAllocationNode* next); CodeReportingAllocationNode* findNode(void* memory); bool variableExists(const SimpleString& variableName); void clearReporting(); bool isNewAllocator(MemoryLeakAllocator* allocator); SimpleString createVariableNameFromFileLineInfo(const char *file, int line); SimpleString getAllocationString(MemoryLeakAllocator* allocator, const SimpleString& variableName, size_t size); SimpleString getDeallocationString(MemoryLeakAllocator* allocator, const SimpleString& variableName, const char* file, int line); }; #endif
null
319
cpp
blalor-cpputest
MemoryReportAllocator.h
include/CppUTestExt/MemoryReportAllocator.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MemoryReportAllocator_h #define D_MemoryReportAllocator_h #include "CppUTest/MemoryLeakAllocator.h" class MemoryReportFormatter; class MemoryReportAllocator : public MemoryLeakAllocator { protected: TestResult* result_; MemoryLeakAllocator* realAllocator_; MemoryReportFormatter* formatter_; public: MemoryReportAllocator(); virtual ~MemoryReportAllocator(); virtual void setFormatter(MemoryReportFormatter* formatter); virtual void setTestResult(TestResult* result); virtual void setRealAllocator(MemoryLeakAllocator* allocator); virtual bool allocateMemoryLeakNodeSeparately(); virtual MemoryLeakAllocator* getRealAllocator(); virtual char* alloc_memory(size_t size, const char* file, int line); virtual void free_memory(char* memory, const char* file, int line); virtual const char* name(); virtual const char* alloc_name(); virtual const char* free_name(); }; #endif
null
320
cpp
blalor-cpputest
MockExpectedFunctionCall.h
include/CppUTestExt/MockExpectedFunctionCall.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MockExpectedFunctionCall_h #define D_MockExpectedFunctionCall_h #include "CppUTestExt/MockFunctionCall.h" #include "CppUTestExt/MockNamedValue.h" extern SimpleString StringFrom(const MockNamedValue& parameter); class MockExpectedFunctionCall : public MockFunctionCall { public: MockExpectedFunctionCall(); virtual ~MockExpectedFunctionCall(); virtual MockFunctionCall& withName(const SimpleString& name); virtual MockFunctionCall& withCallOrder(int); virtual MockFunctionCall& withParameter(const SimpleString& name, int value); virtual MockFunctionCall& withParameter(const SimpleString& name, double value); virtual MockFunctionCall& withParameter(const SimpleString& name, const char* value); virtual MockFunctionCall& withParameter(const SimpleString& name, void* value); virtual MockFunctionCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, void* value); virtual MockFunctionCall& ignoreOtherParameters(); virtual MockFunctionCall& andReturnValue(int value); virtual MockFunctionCall& andReturnValue(double value); virtual MockFunctionCall& andReturnValue(const char* value); virtual MockFunctionCall& andReturnValue(void* value); virtual bool hasReturnValue(); virtual MockNamedValue returnValue(); virtual MockFunctionCall& onObject(void* objectPtr); virtual MockNamedValue getParameter(const SimpleString& name); virtual SimpleString getParameterType(const SimpleString& name); virtual SimpleString getParameterValueString(const SimpleString& name); virtual bool hasParameterWithName(const SimpleString& name); virtual bool hasParameter(const MockNamedValue& parameter); virtual bool relatesTo(const SimpleString& functionName); virtual bool relatesToObject(void*objectPtr) const; virtual bool isFulfilled(); virtual bool isFulfilledWithoutIgnoredParameters(); virtual bool areParametersFulfilled(); virtual bool areIgnoredParametersFulfilled(); virtual bool isOutOfOrder() const; virtual void callWasMade(int callOrder); virtual void parameterWasPassed(const SimpleString& name); virtual void parametersWereIgnored(); virtual void wasPassedToObject(); virtual void resetExpectation(); virtual SimpleString callToString(); virtual SimpleString missingParametersToString(); enum { NOT_CALLED_YET = -1, NO_EXPECTED_CALL_ORDER = -1}; virtual int getCallOrder() const; private: class MockExpectedFunctionParameter : public MockNamedValue { public: MockExpectedFunctionParameter(const SimpleString& name); void setFulfilled(bool b); bool isFulfilled() const; private: bool fulfilled_; }; MockExpectedFunctionParameter* item(MockNamedValueListNode* node); bool ignoreOtherParameters_; bool parametersWereIgnored_; int callOrder_; int expectedCallOrder_; bool outOfOrder_; MockNamedValueList* parameters_; MockNamedValue returnValue_; void* objectPtr_; bool wasPassedToObject_; }; #endif
null
321
cpp
blalor-cpputest
MockFunctionCall.h
include/CppUTestExt/MockFunctionCall.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MockFunctionCall_h #define D_MockFunctionCall_h /* * MockFunctionCall is the main interface for recording and actualizing mock calls. * */ class MockNamedValueComparator; class MockNamedValueComparatorRepository; #include "CppUTestExt/MockNamedValue.h" class MockFunctionCall { public: MockFunctionCall(); virtual ~MockFunctionCall(); virtual MockFunctionCall& withName(const SimpleString& name)=0; virtual MockFunctionCall& withCallOrder(int)=0; virtual MockFunctionCall& withParameter(const SimpleString& name, int value)=0; virtual MockFunctionCall& withParameter(const SimpleString& name, double value)=0; virtual MockFunctionCall& withParameter(const SimpleString& name, const char* value)=0; virtual MockFunctionCall& withParameter(const SimpleString& name, void* value)=0; virtual MockFunctionCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, void* value)=0; virtual MockFunctionCall& ignoreOtherParameters() { return *this;}; virtual MockFunctionCall& andReturnValue(int value)=0; virtual MockFunctionCall& andReturnValue(double value)=0; virtual MockFunctionCall& andReturnValue(const char* value)=0; virtual MockFunctionCall& andReturnValue(void* value)=0; virtual bool hasReturnValue()=0; virtual MockNamedValue returnValue()=0; virtual MockFunctionCall& onObject(void* objectPtr)=0; virtual void setComparatorRepository(MockNamedValueComparatorRepository* repository); protected: void setName(const SimpleString& name); SimpleString getName() const; MockNamedValueComparator* getComparatorForType(const SimpleString& type) const; private: SimpleString functionName_; MockNamedValueComparatorRepository* comparatorRepository_; }; struct MockFunctionCallCompositeNode; class MockFunctionCallComposite : public MockFunctionCall { public: MockFunctionCallComposite(); virtual ~MockFunctionCallComposite(); virtual MockFunctionCall& withName(const SimpleString&); virtual MockFunctionCall& withCallOrder(int); virtual MockFunctionCall& withParameter(const SimpleString&, int); virtual MockFunctionCall& withParameter(const SimpleString&, double); virtual MockFunctionCall& withParameter(const SimpleString&, const char*); virtual MockFunctionCall& withParameter(const SimpleString& , void*); virtual MockFunctionCall& withParameterOfType(const SimpleString&, const SimpleString&, void*); virtual MockFunctionCall& ignoreOtherParameters(); virtual MockFunctionCall& andReturnValue(int); virtual MockFunctionCall& andReturnValue(double); virtual MockFunctionCall& andReturnValue(const char*); virtual MockFunctionCall& andReturnValue(void*); virtual bool hasReturnValue(); virtual MockNamedValue returnValue(); virtual MockFunctionCall& onObject(void* ); virtual void add(MockFunctionCall& call); virtual void clear(); private: MockFunctionCallCompositeNode* head_; }; class MockIgnoredCall : public MockFunctionCall { public: virtual MockFunctionCall& withName(const SimpleString&) { return *this;} virtual MockFunctionCall& withCallOrder(int) { return *this; } virtual MockFunctionCall& withParameter(const SimpleString&, int) { return *this; } virtual MockFunctionCall& withParameter(const SimpleString&, double) { return *this; } virtual MockFunctionCall& withParameter(const SimpleString&, const char*) { return *this; } virtual MockFunctionCall& withParameter(const SimpleString& , void*) { return *this; } virtual MockFunctionCall& withParameterOfType(const SimpleString&, const SimpleString&, void*) { return *this; } virtual MockFunctionCall& andReturnValue(int) { return *this; } virtual MockFunctionCall& andReturnValue(double) { return *this;} virtual MockFunctionCall& andReturnValue(const char*) { return *this; } virtual MockFunctionCall& andReturnValue(void*) { return *this; } virtual bool hasReturnValue() { return false; } virtual MockNamedValue returnValue() { return MockNamedValue(""); } virtual MockFunctionCall& onObject(void* ) { return *this; } static MockFunctionCall& instance() { static MockIgnoredCall call; return call; }; }; class MockFunctionCallTrace : public MockFunctionCall { public: MockFunctionCallTrace(); virtual ~MockFunctionCallTrace(); virtual MockFunctionCall& withName(const SimpleString& name); virtual MockFunctionCall& withCallOrder(int); virtual MockFunctionCall& withParameter(const SimpleString& name, int value); virtual MockFunctionCall& withParameter(const SimpleString& name, double value); virtual MockFunctionCall& withParameter(const SimpleString& name, const char* value); virtual MockFunctionCall& withParameter(const SimpleString& name, void* value); virtual MockFunctionCall& withParameterOfType(const SimpleString& typeName, const SimpleString& name, void* value); virtual MockFunctionCall& ignoreOtherParameters(); virtual MockFunctionCall& andReturnValue(int value); virtual MockFunctionCall& andReturnValue(double value); virtual MockFunctionCall& andReturnValue(const char* value); virtual MockFunctionCall& andReturnValue(void* value); virtual bool hasReturnValue(); virtual MockNamedValue returnValue(); virtual MockFunctionCall& onObject(void* objectPtr); const char* getTraceOutput(); void clear(); static MockFunctionCallTrace& instance(); private: SimpleString traceBuffer_; }; #endif
null
322
cpp
blalor-cpputest
MockNamedValue.h
include/CppUTestExt/MockNamedValue.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MockNamedValue_h #define D_MockNamedValue_h /* * MockParameterComparator is an interface that needs to be used when creating Comparators. * This is needed when comparing values of non-native type. */ class MockNamedValueComparator { public: MockNamedValueComparator() {}; virtual ~MockNamedValueComparator() {}; virtual bool isEqual(void* object1, void* object2)=0; virtual SimpleString valueToString(void* object)=0; }; class MockFunctionComparator : public MockNamedValueComparator { public: typedef bool (*isEqualFunction)(void*, void*); typedef SimpleString (*valueToStringFunction)(void*); MockFunctionComparator(isEqualFunction equal, valueToStringFunction valToString) : equal_(equal), valueToString_(valToString) {} virtual ~MockFunctionComparator(){}; virtual bool isEqual(void* object1, void* object2){ return equal_(object1, object2); } virtual SimpleString valueToString(void* object) { return valueToString_(object); } private: isEqualFunction equal_; valueToStringFunction valueToString_; }; /* * MockNamedValue is the generic value class used. It encapsulates basic types and can use them "as if one" * Also it enables other types by putting object pointers. They can be compared with comparators. * * Basically this class ties together a Name, a Value, a Type, and a Comparator */ class MockNamedValue { public: MockNamedValue(const SimpleString& name); virtual ~MockNamedValue(); virtual void setValue(int value); virtual void setValue(double value); virtual void setValue(void* value); virtual void setValue(const char* value); virtual void setObjectPointer(const SimpleString& type, void* objectPtr); virtual void setComparator(MockNamedValueComparator* comparator); virtual void setName(const char* name); virtual bool equals(const MockNamedValue& p) const; virtual SimpleString toString() const; virtual SimpleString getName() const; virtual SimpleString getType() const; virtual int getIntValue() const; virtual double getDoubleValue() const; virtual const char* getStringValue() const; virtual void* getPointerValue() const; virtual void* getObjectPointer() const; private: SimpleString name_; SimpleString type_; union { int intValue_; double doubleValue_; const char* stringValue_; void* pointerValue_; void* objectPointerValue_; } value_; MockNamedValueComparator* comparator_; }; class MockNamedValueListNode { public: MockNamedValueListNode(MockNamedValue* newValue); SimpleString getName() const; SimpleString getType() const; MockNamedValueListNode* next(); MockNamedValue* item(); void destroy(); void setNext(MockNamedValueListNode* node); private: MockNamedValue* data_; MockNamedValueListNode* next_; }; class MockNamedValueList { public: MockNamedValueList(); MockNamedValueListNode* begin(); void add(MockNamedValue* newValue); void clear(); MockNamedValue* getValueByName(const SimpleString& name); private: MockNamedValueListNode* head_; }; /* * MockParameterComparatorRepository is a class which stores comparators which can be used for comparing non-native types * */ struct MockNamedValueComparatorRepositoryNode; class MockNamedValueComparatorRepository { MockNamedValueComparatorRepositoryNode* head_; public: MockNamedValueComparatorRepository(); virtual ~MockNamedValueComparatorRepository(); virtual void installComparator(const SimpleString& name, MockNamedValueComparator& comparator); virtual void installComparators(const MockNamedValueComparatorRepository& repository); virtual MockNamedValueComparator* getComparatorForType(const SimpleString& name); void clear(); }; #endif
null
323
cpp
blalor-cpputest
MockFailure.h
include/CppUTestExt/MockFailure.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MockFailure_h #define D_MockFailure_h #include "CppUTest/TestFailure.h" class MockExpectedFunctionsList; class MockActualFunctionCall; class MockNamedValue; class MockFailure; class MockFailureReporter { protected: bool crashOnFailure_; public: MockFailureReporter() : crashOnFailure_(false){}; virtual ~MockFailureReporter() {}; virtual void failTest(const MockFailure& failure); virtual Utest* getTestToFail(); virtual void crashOnFailure() {crashOnFailure_ = true; } }; class MockFailure : public TestFailure { public: MockFailure(Utest* test); virtual ~MockFailure(){}; protected: void addExpectationsAndCallHistory(const MockExpectedFunctionsList& expectations); void addExpectationsAndCallHistoryRelatedTo(const SimpleString& function, const MockExpectedFunctionsList& expectations); }; class MockExpectedCallsDidntHappenFailure : public MockFailure { public: MockExpectedCallsDidntHappenFailure(Utest* test, const MockExpectedFunctionsList& expectations); virtual ~MockExpectedCallsDidntHappenFailure(){}; }; class MockUnexpectedCallHappenedFailure : public MockFailure { public: MockUnexpectedCallHappenedFailure(Utest* test, const SimpleString& name, const MockExpectedFunctionsList& expectations); virtual ~MockUnexpectedCallHappenedFailure(){}; }; class MockCallOrderFailure : public MockFailure { public: MockCallOrderFailure(Utest* test, const MockExpectedFunctionsList& expectations); virtual ~MockCallOrderFailure(){}; }; class MockUnexpectedParameterFailure : public MockFailure { public: MockUnexpectedParameterFailure(Utest* test, const SimpleString& functionName, const MockNamedValue& parameter, const MockExpectedFunctionsList& expectations); virtual ~MockUnexpectedParameterFailure(){}; }; class MockExpectedParameterDidntHappenFailure : public MockFailure { public: MockExpectedParameterDidntHappenFailure(Utest* test, const SimpleString& functionName, const MockExpectedFunctionsList& expectations); virtual ~MockExpectedParameterDidntHappenFailure(){}; }; class MockNoWayToCompareCustomTypeFailure : public MockFailure { public: MockNoWayToCompareCustomTypeFailure(Utest* test, const SimpleString& typeName); virtual ~MockNoWayToCompareCustomTypeFailure(){}; }; class MockUnexpectedObjectFailure : public MockFailure { public: MockUnexpectedObjectFailure(Utest* test, const SimpleString& functionName, void* expected, const MockExpectedFunctionsList& expectations); virtual ~MockUnexpectedObjectFailure(){} }; class MockExpectedObjectDidntHappenFailure : public MockFailure { public: MockExpectedObjectDidntHappenFailure(Utest* test, const SimpleString& functionName, const MockExpectedFunctionsList& expectations); virtual ~MockExpectedObjectDidntHappenFailure(){} }; #endif
null
324
cpp
blalor-cpputest
MockSupport.h
include/CppUTestExt/MockSupport.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MockSupport_h #define D_MockSupport_h #include "CppUTestExt/MockFailure.h" #include "CppUTestExt/MockFunctionCall.h" #include "CppUTestExt/MockExpectedFunctionCall.h" #include "CppUTestExt/MockExpectedFunctionsList.h" class Utest; class MockSupport; /* This allows access to "the global" mocking support for easier testing */ MockSupport& mock(const SimpleString& mockName = ""); class MockSupport { public: MockSupport(); virtual ~MockSupport(); virtual void strictOrder(); virtual MockFunctionCall& expectOneCall(const SimpleString& functionName); virtual MockFunctionCall& expectNCalls(int amount, const SimpleString& functionName); virtual MockFunctionCall& actualCall(const SimpleString& functionName); virtual bool hasReturnValue(); virtual MockNamedValue returnValue(); virtual int intReturnValue(); virtual const char* stringReturnValue(); virtual double doubleReturnValue(); virtual void* pointerReturnValue(); bool hasData(const SimpleString& name); void setData(const SimpleString& name, int value); void setData(const SimpleString& name, const char* value); void setData(const SimpleString& name, double value); void setData(const SimpleString& name, void* value); void setDataObject(const SimpleString& name, const SimpleString& type, void* value); MockNamedValue getData(const SimpleString& name); MockSupport* getMockSupportScope(const SimpleString& name); const char* getTraceOutput(); /* * The following functions are recursively through the lower MockSupports scopes * This means, if you do mock().disable() it will disable *all* mocking scopes, including mock("myScope"). */ virtual void disable(); virtual void enable(); virtual void tracing(bool enabled); virtual void ignoreOtherCalls(); virtual void checkExpectations(); virtual bool expectedCallsLeft(); virtual void clear(); virtual void setMockFailureReporter(MockFailureReporter* reporter); virtual void crashOnFailure(); virtual void installComparator(const SimpleString& typeName, MockNamedValueComparator& comparator); virtual void installComparators(const MockNamedValueComparatorRepository& repository); virtual void removeAllComparators(); protected: virtual MockActualFunctionCall *createActualFunctionCall(); private: static int callOrder_; static int expectedCallOrder_; bool strictOrdering_; MockFailureReporter *reporter_; MockFailureReporter defaultReporter_; MockExpectedFunctionsList expectations_; bool ignoreOtherCalls_; bool enabled_; MockActualFunctionCall *lastActualFunctionCall_; MockFunctionCallComposite compositeCalls_; MockNamedValueComparatorRepository comparatorRepository_; MockNamedValueList data_; bool tracing_; void checkExpectationsOfLastCall(); bool wasLastCallFulfilled(); void failTestWithUnexpectedCalls(); void failTestWithOutOfOrderCalls(); MockNamedValue* retrieveDataFromStore(const SimpleString& name); MockSupport* getMockSupport(MockNamedValueListNode* node); }; #endif
null
325
cpp
blalor-cpputest
MemoryReporterPlugin.h
include/CppUTestExt/MemoryReporterPlugin.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MemoryReporterPlugin_h #define D_MemoryReporterPlugin_h #include "CppUTest/TestPlugin.h" #include "CppUTestExt/MemoryReportAllocator.h" class MemoryReportFormatter; class MemoryReporterPlugin : public TestPlugin { MemoryReportFormatter* formatter_; MemoryReportAllocator mallocAllocator; MemoryReportAllocator newAllocator; MemoryReportAllocator newArrayAllocator; SimpleString currentTestGroup_; public: MemoryReporterPlugin(); virtual ~MemoryReporterPlugin(); virtual void preTestAction(Utest & test, TestResult & result); virtual void postTestAction(Utest & test, TestResult & result); virtual bool parseArguments(int, const char**, int); protected: virtual MemoryReportFormatter* createMemoryFormatter(const SimpleString& type); private: void destroyMemoryFormatter(MemoryReportFormatter* formatter); void setGlobalMemoryReportAllocators(); void removeGlobalMemoryReportAllocators(); void initializeAllocator(MemoryReportAllocator* allocator, TestResult & result); }; #endif
null
326
cpp
blalor-cpputest
MockSupport_c.h
include/CppUTestExt/MockSupport_c.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MockSupport_c_h #define D_MockSupport_c_h typedef enum { MOCKVALUETYPE_INTEGER, MOCKVALUETYPE_DOUBLE, MOCKVALUETYPE_STRING, MOCKVALUETYPE_POINTER, MOCKVALUETYPE_OBJECT } MockValueType_c; typedef struct SMockValue_c { MockValueType_c type; union { int intValue; double doubleValue; const char* stringValue; void* pointerValue; void* objectValue; } value; } MockValue_c; typedef struct SMockFunctionCall_c MockFunctionCall_c; struct SMockFunctionCall_c { MockFunctionCall_c* (*withIntParameters)(const char* name, int value); MockFunctionCall_c* (*withDoubleParameters)(const char* name, double value); MockFunctionCall_c* (*withStringParameters)(const char* name, const char* value); MockFunctionCall_c* (*withPointerParameters)(const char* name, void* value); MockFunctionCall_c* (*withParameterOfType)(const char* type, const char* name, void* value); MockFunctionCall_c* (*andReturnIntValue)(int value); MockFunctionCall_c* (*andReturnDoubleValue)(double value); MockFunctionCall_c* (*andReturnStringValue)(const char* value); MockFunctionCall_c* (*andReturnPointerValue)(void* value); MockValue_c (*returnValue)(); }; typedef int (*MockTypeEqualFunction_c)(void* object1, void* object2); typedef char* (*MockTypeValueToStringFunction_c)(void* object1); typedef struct SMockSupport_c MockSupport_c; struct SMockSupport_c { MockFunctionCall_c* (*expectOneCall)(const char* name); MockFunctionCall_c* (*actualCall)(const char* name); MockValue_c (*returnValue)(); void (*setIntData) (const char* name, int value); void (*setDoubleData) (const char* name, double value); void (*setStringData) (const char* name, const char* value); void (*setPointerData) (const char* name, void* value); void (*setDataObject) (const char* name, const char* type, void* value); MockValue_c (*getData)(const char* name); void (*checkExpectations)(); int (*expectedCallsLeft)(); void (*clear)(); void (*installComparator) (const char* typeName, MockTypeEqualFunction_c isEqual, MockTypeValueToStringFunction_c valueToString); void (*removeAllComparators)(); }; MockSupport_c* mock_c(); MockSupport_c* mock_scope_c(const char* scope); #endif
null
327
cpp
blalor-cpputest
TestOutput.h
include/CppUTest/TestOutput.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_TestOutput_h #define D_TestOutput_h /////////////////////////////////////////////////////////////////////////////// // // TestOutput.h // // This is a minimal printer inteface. // We kept streams out too keep footprint small, and so the test // harness could be used with less capable compilers so more // platforms could use this test harness // /////////////////////////////////////////////////////////////////////////////// class Utest; class TestFailure; class TestResult; class TestOutput { public: explicit TestOutput(); virtual ~TestOutput(); virtual void printTestsStarted(); virtual void printTestsEnded(const TestResult& result); virtual void printCurrentTestStarted(const Utest& test); virtual void printCurrentTestEnded(const TestResult& res); virtual void printCurrentGroupStarted(const Utest& test); virtual void printCurrentGroupEnded(const TestResult& res); virtual void verbose(); virtual void printBuffer(const char*)=0; virtual void print(const char*); virtual void print(long); virtual void printDouble(double); virtual void printHex(long); virtual void print(const TestFailure& failure); virtual void printTestRun(int number, int total); virtual void setProgressIndicator(const char*); virtual void flush(); private: virtual void printProgressIndicator(); void printFileAndLineForTestAndFailure(const TestFailure& failure); void printFileAndLineForFailure(const TestFailure& failure); void printFailureInTest(SimpleString testName); void printFailureMessage(SimpleString reason); void printEclipseErrorInFileOnLine(SimpleString testFile, int lineNumber); TestOutput(const TestOutput&); TestOutput& operator=(const TestOutput&); int dotCount_; bool verbose_; const char* progressIndication_; }; TestOutput& operator<<(TestOutput&, const char*); TestOutput& operator<<(TestOutput&, long); /////////////////////////////////////////////////////////////////////////////// // // ConsoleTestOutput.h // // Printf Based Solution // /////////////////////////////////////////////////////////////////////////////// class ConsoleTestOutput: public TestOutput { public: explicit ConsoleTestOutput() { } ; virtual ~ConsoleTestOutput() { } ; virtual void printBuffer(const char* s); virtual void flush(); private: ConsoleTestOutput(const ConsoleTestOutput&); ConsoleTestOutput& operator=(const ConsoleTestOutput&); }; /////////////////////////////////////////////////////////////////////////////// // // StringBufferTestOutput.h // // TestOutput for test purposes // /////////////////////////////////////////////////////////////////////////////// class StringBufferTestOutput: public TestOutput { public: explicit StringBufferTestOutput() { } ; virtual ~StringBufferTestOutput() { } ; void printBuffer(const char* s) { output += s; } void flush() { output = ""; } const SimpleString& getOutput() { return output; } private: SimpleString output; StringBufferTestOutput(const StringBufferTestOutput&); StringBufferTestOutput& operator=(const StringBufferTestOutput&); }; #endif // D_TestOutput_h
null
328
cpp
blalor-cpputest
MemoryLeakDetector.h
include/CppUTest/MemoryLeakDetector.h
null
#ifndef D_MemoryLeakDetector_h #define D_MemoryLeakDetector_h #define MEM_LEAK_NONE "No memory leaks were detected." #define MEM_LEAK_HEADER "Memory leak(s) found.\n" #define MEM_LEAK_LEAK "Leak size: %d Allocated at: %s and line: %d. Type: \"%s\" Content: \"%.15s\"\n" #define MEM_LEAK_TOO_MUCH "\netc etc etc etc. !!!! Too much memory leaks to report. Bailing out\n" #define MEM_LEAK_FOOTER "Total number of leaks: " #define MEM_LEAK_ADDITION_MALLOC_WARNING "NOTE:\n" \ "\tMemory leak reports about malloc and free can be caused by allocating using the cpputest version of malloc,\n" \ "\tbut deallocate using the standard free.\n" \ "\tIf this is the case, check whether your malloc/free replacements are working (#define malloc cpputest_malloc etc).\n" #define MEM_LEAK_NORMAL_FOOTER_SIZE (sizeof(MEM_LEAK_FOOTER) + 10 + sizeof(MEM_LEAK_TOO_MUCH)) /* the number of leaks */ #define MEM_LEAK_NORMAL_MALLOC_FOOTER_SIZE (MEM_LEAK_NORMAL_FOOTER_SIZE + sizeof(MEM_LEAK_ADDITION_MALLOC_WARNING)) #define MEM_LEAK_ALLOC_DEALLOC_MISMATCH "Allocation/deallocation type mismatch\n" #define MEM_LEAK_MEMORY_CORRUPTION "Memory corruption (written out of bounds?)\n" #define MEM_LEAK_ALLOC_LOCATION " allocated at file: %s line: %d size: %d type: %s\n" #define MEM_LEAK_DEALLOC_LOCATION " deallocated at file: %s line: %d type: %s\n" #define MEM_LEAK_DEALLOC_NON_ALLOCATED "Deallocating non-allocated memory\n" enum MemLeakPeriod { mem_leak_period_all, mem_leak_period_disabled, mem_leak_period_enabled, mem_leak_period_checking }; class MemoryLeakAllocator; #include "StandardCLibrary.h" class MemoryLeakFailure { public: virtual ~MemoryLeakFailure() { } ; virtual void fail(char* fail_string)=0; }; struct SimpleStringBuffer { enum { SIMPLE_STRING_BUFFER_LEN = 4096 }; SimpleStringBuffer(); void clear(); void add(const char* format, ...); char* toString(); void setWriteLimit(int write_limit); void resetWriteLimit(); bool reachedItsCapacity(); private: char buffer_[SIMPLE_STRING_BUFFER_LEN]; int positions_filled_; int write_limit_; }; struct MemoryLeakDetectorNode { MemoryLeakDetectorNode() : size_(0), next_(0) { } void init(char* memory, size_t size, MemoryLeakAllocator* allocator, MemLeakPeriod period, const char* file, int line); size_t size_; char* memory_; const char* file_; int line_; MemoryLeakAllocator* allocator_; MemLeakPeriod period_; private: friend struct MemoryLeakDetectorList; MemoryLeakDetectorNode* next_; }; struct MemoryLeakDetectorList { MemoryLeakDetectorList() : head_(0) {} void addNewNode(MemoryLeakDetectorNode* node); MemoryLeakDetectorNode* retrieveNode(char* memory); MemoryLeakDetectorNode* removeNode(char* memory); MemoryLeakDetectorNode* getFirstLeak(MemLeakPeriod period); MemoryLeakDetectorNode* getNextLeak(MemoryLeakDetectorNode* node, MemLeakPeriod period); MemoryLeakDetectorNode* getLeakFrom(MemoryLeakDetectorNode* node, MemLeakPeriod period); int getTotalLeaks(MemLeakPeriod period); bool hasLeaks(MemLeakPeriod period); void clearAllAccounting(MemLeakPeriod period); bool isInPeriod(MemoryLeakDetectorNode* node, MemLeakPeriod period); private: MemoryLeakDetectorNode* head_; }; struct MemoryLeakDetectorTable { void clearAllAccounting(MemLeakPeriod period); void addNewNode(MemoryLeakDetectorNode* node); MemoryLeakDetectorNode* retrieveNode(char* memory); MemoryLeakDetectorNode* removeNode(char* memory); bool hasLeaks(MemLeakPeriod period); int getTotalLeaks(MemLeakPeriod period); MemoryLeakDetectorNode* getFirstLeak(MemLeakPeriod period); MemoryLeakDetectorNode* getNextLeak(MemoryLeakDetectorNode* leak, MemLeakPeriod period); private: unsigned long hash(char* memory); enum { hash_prime = MEMORY_LEAK_HASH_TABLE_SIZE }; MemoryLeakDetectorList table_[hash_prime]; }; class MemoryLeakDetector { public: MemoryLeakDetector(); ~MemoryLeakDetector() { } void init(MemoryLeakFailure* reporter); void enable(); void disable(); void disableAllocationTypeChecking(); void enableAllocationTypeChecking(); void startChecking(); void stopChecking(); const char* report(MemLeakPeriod period); void markCheckingPeriodLeaksAsNonCheckingPeriod(); int totalMemoryLeaks(MemLeakPeriod period); void clearAllAccounting(MemLeakPeriod period); char* allocMemory(MemoryLeakAllocator* allocator, size_t size); char* allocMemory(MemoryLeakAllocator* allocator, size_t size, const char* file, int line); void deallocMemory(MemoryLeakAllocator* allocator, void* memory); void deallocMemory(MemoryLeakAllocator* allocator, void* memory, const char* file, int line); char* reallocMemory(MemoryLeakAllocator* allocator, char* memory, size_t size, const char* file, int line); void invalidateMemory(char* memory); void removeMemoryLeakInformationWithoutCheckingOrDeallocating(void* memory); enum { memory_corruption_buffer_size = 3 }; private: MemoryLeakFailure* reporter_; MemLeakPeriod current_period_; SimpleStringBuffer output_buffer_; MemoryLeakDetectorTable memoryTable_; bool doAllocationTypeChecking_; bool validMemoryCorruptionInformation(char* memory); bool matchingAllocation(MemoryLeakAllocator *alloc_allocator, MemoryLeakAllocator *free_allocator); void storeLeakInformation(MemoryLeakDetectorNode *& node, char *new_memory, size_t size, MemoryLeakAllocator *allocator, const char *file, int line); void ConstructMemoryLeakReport(MemLeakPeriod period); void reportFailure(const char* message, const char* allocFile, int allocLine, size_t allocSize, MemoryLeakAllocator* allocAllocator, const char* freeFile, int freeLine, MemoryLeakAllocator* freeAllocator); size_t sizeOfMemoryWithCorruptionInfo(size_t size); MemoryLeakDetectorNode* getNodeFromMemoryPointer(char* memory, size_t size); char* reallocateMemoryAndLeakInformation(MemoryLeakAllocator* allocator, char* memory, size_t size, const char* file, int line); void addMemoryCorruptionInformation(char* memory); void checkForCorruption(MemoryLeakDetectorNode* node, const char* file, int line, MemoryLeakAllocator* allocator); }; #endif
null
329
cpp
blalor-cpputest
TestPlugin.h
include/CppUTest/TestPlugin.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /////////////////////////////////////////////////////////////////////////////// // // TESTPlugin.H // // This file contains the ability to plugin_ general checks to all tests. // /////////////////////////////////////////////////////////////////////////////// #ifndef D_TestPlugin_h #define D_TestPlugin_h class Utest; class TestResult; class TestPlugin { public: TestPlugin(const SimpleString& name); virtual ~TestPlugin(); virtual void preTestAction(Utest&, TestResult&) { } virtual void postTestAction(Utest&, TestResult&) { } virtual bool parseArguments(int /* ac */, const char** /* av */, int /* index */ ) { return false; } virtual void runAllPreTestAction(Utest&, TestResult&); virtual void runAllPostTestAction(Utest&, TestResult&); virtual bool parseAllArguments(int ac, const char** av, int index); virtual bool parseAllArguments(int ac, char** av, int index); virtual TestPlugin* addPlugin(TestPlugin*); virtual TestPlugin* removePluginByName(const SimpleString& name); virtual TestPlugin* getNext(); virtual void disable(); virtual void enable(); virtual bool isEnabled(); const SimpleString& getName(); TestPlugin* getPluginByName(const SimpleString& name); protected: TestPlugin(TestPlugin* next_); private: TestPlugin* next_; SimpleString name_; bool enabled_; }; /////////////////////////////////////////////////////////////////////////////// // // SetPointerPlugin // // This is a very small plugin_ that resets pointers to their original value. // /////////////////////////////////////////////////////////////////////////////// extern void CppUTestStore(void **location, void *value); class SetPointerPlugin: public TestPlugin { public: SetPointerPlugin(const SimpleString& name); virtual ~SetPointerPlugin(); virtual void postTestAction(Utest&, TestResult&); enum { MAX_SET = 1024 }; }; /* C++ standard says we cannot cast function pointers to object pointers. Extra casting to fool the compiler */ #define UT_PTR_SET(a, b) { CppUTestStore( (void**)&a, *((void**) &a)); a = b; } ///////////// Null Plugin class NullTestPlugin: public TestPlugin { public: NullTestPlugin(); virtual ~NullTestPlugin() { } virtual void runAllPreTestAction(Utest& test, TestResult& result); virtual void runAllPostTestAction(Utest& test, TestResult& result); static NullTestPlugin* instance(); }; #endif
null
330
cpp
blalor-cpputest
UtestMacros.h
include/CppUTest/UtestMacros.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_UTestMacros_h #define D_UTestMacros_h /*! \brief Define a group of tests * * All tests in a TEST_GROUP share the same setup * and teardown. setup is run before the opening * curly brace of the test group and teardown is * called after the closing curly brace of the test group. * */ #define TEST_GROUP_BASE(testGroup, baseclass) \ int externTestGroup##testGroup = 0; \ struct TEST_GROUP_##CppUTestGroup##testGroup : public baseclass #define TEST_BASE(testBaseClass) \ struct testBaseClass : public Utest #define TEST_GROUP(testGroup) \ TEST_GROUP_BASE(testGroup, Utest) #define TEST_SETUP() \ virtual void setup() #define TEST_TEARDOWN() \ virtual void teardown() #define TEST(testGroup, testName) \ class TEST_##testGroup##_##testName##_Test : public TEST_GROUP_##CppUTestGroup##testGroup \ { public: TEST_##testGroup##_##testName##_Test () : TEST_GROUP_##CppUTestGroup##testGroup () {} \ void testBody(); } \ TEST_##testGroup##_##testName##_Instance; \ TestInstaller TEST_##testGroup##_##testName##_Installer(&TEST_##testGroup##_##testName##_Instance, #testGroup, #testName, __FILE__,__LINE__); \ void TEST_##testGroup##_##testName##_Test::testBody() #define IGNORE_TEST(testGroup, testName)\ class IGNORE##testGroup##_##testName##_Test : public TEST_GROUP_##CppUTestGroup##testGroup \ { public: IGNORE##testGroup##_##testName##_Test () : TEST_GROUP_##CppUTestGroup##testGroup () {} \ virtual void run (TestResult& result_parameter) { \ result_parameter.countIgnored(); } \ virtual const char* getProgressIndicator() const {return "!";} \ protected: virtual SimpleString getMacroName() const \ { return "IGNORE_TEST"; } \ public: void testBodyThatNeverRuns (); } \ TEST_##testGroup##_##testName##_Instance; \ TestInstaller TEST_##testGroup##testName##_Installer(&TEST_##testGroup##_##testName##_Instance, #testGroup, #testName, __FILE__,__LINE__); \ void IGNORE##testGroup##_##testName##_Test::testBodyThatNeverRuns () #define IMPORT_TEST_GROUP(testGroup) \ extern int externTestGroup##testGroup;\ int* p##testGroup = &externTestGroup##testGroup //Check any boolean condition #define CHECK(condition)\ CHECK_LOCATION_TRUE(condition, "CHECK", #condition, __FILE__, __LINE__) #define CHECK_TRUE(condition)\ CHECK_LOCATION_TRUE(condition, "CHECK_TRUE", #condition, __FILE__, __LINE__) #define CHECK_FALSE(condition)\ CHECK_LOCATION_FALSE(condition, "CHECK_FALSE", #condition, __FILE__, __LINE__) #define CHECK_LOCATION_TRUE(condition, checkString, conditionString, file, line)\ { Utest::getCurrent()->assertTrue((condition) != 0, checkString, conditionString, file, line); } #define CHECK_LOCATION_FALSE(condition, checkString, conditionString, file, line)\ { Utest::getCurrent()->assertTrue((condition) == 0, checkString, conditionString, file, line); } //This check needs the operator!=(), and a StringFrom(YourType) function #define CHECK_EQUAL(expected,actual)\ CHECK_EQUAL_LOCATION(expected, actual, __FILE__, __LINE__) #define CHECK_EQUAL_LOCATION(expected,actual, file, line)\ if ((expected) != (actual))\ {\ { \ Utest::getTestResult()->countCheck();\ CheckEqualFailure _f(Utest::getCurrent(), file, line, StringFrom(expected), StringFrom(actual)); \ Utest::getTestResult()->addFailure(_f);\ } \ Utest::getCurrent()->exitCurrentTest(); \ }\ else\ Utest::getTestResult()->countCheck(); //This check checks for char* string equality using strcmp. //This makes up for the fact that CHECK_EQUAL only compares the pointers to char*'s #define STRCMP_EQUAL(expected,actual)\ STRCMP_EQUAL_LOCATION(expected, actual, __FILE__, __LINE__) #define STRCMP_EQUAL_LOCATION(expected,actual, file, line)\ { Utest::getCurrent()->assertCstrEqual(expected, actual, file, line); } #define STRCMP_NOCASE_EQUAL(expected,actual)\ STRCMP_NOCASE_EQUAL_LOCATION(expected, actual, __FILE__, __LINE__) #define STRCMP_NOCASE_EQUAL_LOCATION(expected,actual, file, line)\ { Utest::getCurrent()->assertCstrNoCaseEqual(expected, actual, file, line); } #define STRCMP_CONTAINS(expected,actual)\ STRCMP_CONTAINS_LOCATION(expected, actual, __FILE__, __LINE__) #define STRCMP_CONTAINS_LOCATION(expected,actual, file, line)\ { Utest::getCurrent()->assertCstrContains(expected, actual, file, line); } #define STRCMP_NOCASE_CONTAINS(expected,actual)\ STRCMP_NOCASE_CONTAINS_LOCATION(expected, actual, __FILE__, __LINE__) #define STRCMP_NOCASE_CONTAINS_LOCATION(expected,actual, file, line)\ { Utest::getCurrent()->assertCstrNoCaseContains(expected, actual, file, line); } //Check two long integers for equality #define LONGS_EQUAL(expected,actual)\ LONGS_EQUAL_LOCATION(expected,actual,__FILE__, __LINE__) #define LONGS_EQUAL_LOCATION(expected,actual,file,line)\ { Utest::getCurrent()->assertLongsEqual(expected, actual, file, line); } #define BYTES_EQUAL(expected, actual)\ LONGS_EQUAL((expected) & 0xff,(actual) & 0xff) #define POINTERS_EQUAL(expected, actual)\ POINTERS_EQUAL_LOCATION((expected),(actual), __FILE__, __LINE__) #define POINTERS_EQUAL_LOCATION(expected,actual,file,line)\ { Utest::getCurrent()->assertPointersEqual((void *)expected, (void *)actual, file, line); } //Check two doubles for equality within a tolerance threshold #define DOUBLES_EQUAL(expected,actual,threshold)\ DOUBLES_EQUAL_LOCATION(expected,actual,threshold,__FILE__,__LINE__) #define DOUBLES_EQUAL_LOCATION(expected,actual,threshold,file,line)\ { Utest::getCurrent()->assertDoublesEqual(expected, actual, threshold, file, line); } //Fail if you get to this macro //The macro FAIL may already be taken, so allow FAIL_TEST too #ifndef FAIL #define FAIL(text)\ FAIL_LOCATION(text, __FILE__,__LINE__) #define FAIL_LOCATION(text, file, line)\ { Utest::getCurrent()->fail(text, file, line); Utest::getCurrent()->exitCurrentTest(); } #endif #define FAIL_TEST(text)\ FAIL_TEST_LOCATION(text, __FILE__,__LINE__) #define FAIL_TEST_LOCATION(text, file,line)\ { Utest::getCurrent()->fail(text, file, line); Utest::getCurrent()->exitCurrentTest(); } #define UT_PRINT_LOCATION(text, file, line) \ { Utest::getCurrent()->print(text, file, line); } #define UT_PRINT(text) \ UT_PRINT_LOCATION(text, __FILE__, __LINE__) #define UT_CRASH() { UT_PRINT("Going to crash here\n"); Utest* ptr = (Utest*) 0x0; ptr->countTests(); } #define RUN_ALL_TESTS(ac, av) CommandLineTestRunner::RunAllTests(ac, av) #endif /*D_UTestMacros_h*/
null
331
cpp
blalor-cpputest
MemoryLeakAllocator.h
include/CppUTest/MemoryLeakAllocator.h
null
#ifndef D_MemoryLeakAllocator_h #define D_MemoryLeakAllocator_h struct MemoryLeakNode; class MemoryLeakAllocator { public: virtual char* alloc_memory(size_t size, const char* file, int line)=0; virtual void free_memory(char* memory, const char* file, int line)=0; virtual const char* name()=0; virtual const char* alloc_name()=0; virtual const char* free_name()=0; virtual bool isOfEqualType(MemoryLeakAllocator* allocator); virtual ~MemoryLeakAllocator() { } virtual bool allocateMemoryLeakNodeSeparately(); virtual char* allocMemoryLeakNode(size_t size); virtual void freeMemoryLeakNode(char* memory); static void setCurrentNewAllocator(MemoryLeakAllocator* allocator); static MemoryLeakAllocator* getCurrentNewAllocator(); static void setCurrentNewAllocatorToDefault(); static void setCurrentNewArrayAllocator(MemoryLeakAllocator* allocator); static MemoryLeakAllocator* getCurrentNewArrayAllocator(); static void setCurrentNewArrayAllocatorToDefault(); static void setCurrentMallocAllocator(MemoryLeakAllocator* allocator); static MemoryLeakAllocator* getCurrentMallocAllocator(); static void setCurrentMallocAllocatorToDefault(); private: static MemoryLeakAllocator* currentNewAllocator; static MemoryLeakAllocator* currentNewArrayAllocator; static MemoryLeakAllocator* currentMallocAllocator; }; class StandardMallocAllocator: public MemoryLeakAllocator { public: virtual char* alloc_memory(size_t size, const char* file, int line); virtual void free_memory(char* memory, const char* file, int line); const char* name(); const char* alloc_name(); const char* free_name(); virtual bool allocateMemoryLeakNodeSeparately(); static MemoryLeakAllocator* defaultAllocator(); }; class StandardNewAllocator: public MemoryLeakAllocator { public: virtual char* alloc_memory(size_t size, const char* file, int line); virtual void free_memory(char* memory, const char* file, int line); const char* name(); const char* alloc_name(); const char* free_name(); static MemoryLeakAllocator* defaultAllocator(); }; class StandardNewArrayAllocator: public MemoryLeakAllocator { public: virtual char* alloc_memory(size_t size, const char* file, int line); virtual void free_memory(char* memory, const char* file, int line); const char* name(); const char* alloc_name(); const char* free_name(); static MemoryLeakAllocator* defaultAllocator(); }; class NullUnknownAllocator: public MemoryLeakAllocator { public: virtual char* alloc_memory(size_t size, const char* file, int line); virtual void free_memory(char* memory, const char* file, int line); const char* name(); const char* alloc_name(); const char* free_name(); static MemoryLeakAllocator* defaultAllocator(); }; #endif
null
332
cpp
blalor-cpputest
PlatformSpecificFunctions.h
include/CppUTest/PlatformSpecificFunctions.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PLATFORMSPECIFICFUNCTIONS_H_ #define PLATFORMSPECIFICFUNCTIONS_H_ /* Platform specific interface we use in order to minimize dependencies with LibC. * This enables porting to different embedded platforms. * */ /* For test execution control (long_jmp set_jmp) */ /* bool Utest::executePlatformSpecificSetup() * void Utest::executePlatformSpecificTestBody() * void Utest::executePlatformSpecificTeardown() * void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) * void Utest::executePlatformSpecificExitCurrentTest() */ /* Time operations */ long GetPlatformSpecificTimeInMillis(); void SetPlatformSpecificTimeInMillisMethod(long(*platformSpecific)()); const char* GetPlatformSpecificTimeString(); void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod)()); /* String operations */ int PlatformSpecificAtoI(const char*str); size_t PlatformSpecificStrLen(const char* str); char* PlatformSpecificStrCat(char* s1, const char* s2); char* PlatformSpecificStrCpy(char* s1, const char* s2); char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size); int PlatformSpecificStrCmp(const char* s1, const char* s2); int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size); char* PlatformSpecificStrStr(const char* s1, const char* s2); int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list va_args_list); char PlatformSpecificToLower(char c); /* Misc */ double PlatformSpecificFabs(double d); int PlatformSpecificIsNan(double d); int PlatformSpecificAtExit(void(*func)()); /* IO operations */ typedef void* PlatformSpecificFile; PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag); void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file); void PlatformSpecificFClose(PlatformSpecificFile file); int PlatformSpecificPutchar(int c); void PlatformSpecificFlush(); /* Dynamic Memory operations */ void* PlatformSpecificMalloc(size_t size); void* PlatformSpecificRealloc(void* memory, size_t size); void PlatformSpecificFree(void* memory); void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size); void* PlatformSpecificMemset(void* mem, int c, size_t size); #endif
null
333
cpp
blalor-cpputest
CommandLineArguments.h
include/CppUTest/CommandLineArguments.h
null
#ifndef D_CommandLineArguments_H #define D_CommandLineArguments_H /////////////////////////////////////////////////////////////////////////////// // // CommandLineArguments is responsible for ... // /////////////////////////////////////////////////////////////////////////////// #include "SimpleString.h" #include "TestOutput.h" class TestPlugin; class CommandLineArguments { public: explicit CommandLineArguments(int ac, const char** av); virtual ~CommandLineArguments(); bool parse(TestPlugin* plugin); bool isVerbose() const; int getRepeatCount() const; SimpleString getGroupFilter() const; SimpleString getNameFilter() const; bool isJUnitOutput() const; bool isEclipseOutput() const; const char* usage() const; private: enum OutputType { OUTPUT_ECLIPSE, OUTPUT_JUNIT }; int ac_; const char** av_; bool verbose_; int repeat_; SimpleString groupFilter_; SimpleString nameFilter_; OutputType outputType_; SimpleString getParameterField(int ac, const char** av, int& i); void SetRepeatCount(int ac, const char** av, int& index); void SetGroupFilter(int ac, const char** av, int& index); void SetNameFilter(int ac, const char** av, int& index); bool SetOutputType(int ac, const char** av, int& index); CommandLineArguments(const CommandLineArguments&); CommandLineArguments& operator=(const CommandLineArguments&); }; #endif // D_CommandLineArguments_H
null
334
cpp
blalor-cpputest
VirtualCall.h
include/CppUTest/VirtualCall.h
null
#ifndef D_VirtualCall_H #define D_VirtualCall_H #define send(obj,msg)\ ((obj)->msg(obj)) #define send1(obj,msg,arg0)\ ((obj)->msg((obj),(arg0))) #define send2(obj,msg,arg0,arg1)\ ((obj)->msg((obj),(arg0),(arg1))) #define send3(obj,msg,arg0,arg1,arg2)\ ((obj)->msg((obj),(arg0),(arg1),(arg2))) #define send4(obj,msg,arg0,arg1,arg2,arg3)\ ((obj)->msg((obj),(arg0),(arg1),(arg2),(arg3))) #define vBind(obj,msg,newMethod)\ (obj->msg=&newMethod) #define castToDestroyer(Class) (Class* (*)(Class*)) #endif
null
335
cpp
blalor-cpputest
TestHarness_c.h
include/CppUTest/TestHarness_c.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /****************************************************************************** * * TESTHARNESS_c.H * * Provides an interface for when working with pure C * * Remember to use extern "C" when including in a cpp file! * *******************************************************************************/ #ifndef D_TestHarness_c_h #define D_TestHarness_c_h #define CHECK_EQUAL_C_INT(expected,actual) \ CHECK_EQUAL_C_INT_LOCATION(expected,actual,__FILE__,__LINE__) #define CHECK_EQUAL_C_REAL(expected,actual,threshold) \ CHECK_EQUAL_C_REAL_LOCATION(expected,actual,threshold,__FILE__,__LINE__) #define CHECK_EQUAL_C_CHAR(expected,actual) \ CHECK_EQUAL_C_CHAR_LOCATION(expected,actual,__FILE__,__LINE__) #define CHECK_EQUAL_C_STRING(expected,actual) \ CHECK_EQUAL_C_STRING_LOCATION(expected,actual,__FILE__,__LINE__) #define FAIL_TEXT_C(text) \ FAIL_TEXT_C_LOCATION(text,__FILE__,__LINE__) #define FAIL_C() \ FAIL_C_LOCATION(__FILE__,__LINE__) #define CHECK_C(condition) \ CHECK_C_LOCATION(condition, #condition, __FILE__,__LINE__) /* CHECKS that can be used from C code */ extern void CHECK_EQUAL_C_INT_LOCATION(int expected, int actual, const char* fileName, int lineNumber); extern void CHECK_EQUAL_C_REAL_LOCATION(double expected, double actual, double threshold, const char* fileName, int lineNumber); extern void CHECK_EQUAL_C_CHAR_LOCATION(char expected, char actual, const char* fileName, int lineNumber); extern void CHECK_EQUAL_C_STRING_LOCATION(const char* expected, const char* actual, const char* fileName, int lineNumber); extern void FAIL_TEXT_C_LOCATION(const char* text, const char* fileName, int lineNumber); extern void FAIL_C_LOCATION(const char* fileName, int lineNumber); extern void CHECK_C_LOCATION(int condition, const char* conditionString, const char* fileName, int lineNumber); #include "StandardCLibrary.h" extern void* cpputest_malloc(size_t size); extern void* cpputest_calloc(size_t num, size_t size); extern void* cpputest_realloc(void* ptr, size_t size); extern void cpputest_free(void* buffer); extern void* cpputest_malloc_location(size_t size, const char* file, int line); extern void* cpputest_calloc_location(size_t num, size_t size, const char* file, int line); extern void* cpputest_realloc_location(void* memory, size_t size, const char* file, int line); extern void cpputest_free_location(void* buffer, const char* file, int line); void cpputest_malloc_set_out_of_memory(void); void cpputest_malloc_set_not_out_of_memory(void); void cpputest_malloc_set_out_of_memory_countdown(int); void cpputest_malloc_count_reset(void); int cpputest_malloc_get_count(void); /* * Small additional macro for unused arguments. This is common when stubbing, but in C you cannot remove the * name of the parameter (as in C++). */ #ifndef PUNUSED #if defined(__GNUC__) # define PUNUSED(x) PUNUSED_ ##x __attribute__((unused)) #else # define PUNUSED(x) x #endif #endif #endif
null
336
cpp
blalor-cpputest
MemoryLeakDetectorNewMacros.h
include/CppUTest/MemoryLeakDetectorNewMacros.h
null
/* * This file can be used to get extra debugging information about memory leaks in your production code. * It defines a preprocessor macro for operator new. This will pass additional information to the * operator new and this will give the line/file information of the memory leaks in your code. * * You can use this by including this file to all your production code. When using gcc, you can use * the -include file to do this for you. * * Warning: Using the new macro can cause a conflict with newly declared operator news. This can be * resolved by: * 1. #undef operator new before including this file * 2. Including the files that override operator new before this file. * This can be done by creating your own NewMacros.h file that includes your operator new overrides * and THEN this file. * * STL (or StdC++ lib) also does overrides for operator new. Therefore, you'd need to include the STL * files *before* this file too. * */ /* Warning for maintainers: * This macro code is duplicate from TestHarness.h. The reason for this is to make the two files * completely independent from each other. NewMacros file can be included in production code whereas * TestHarness.h is only included in test code. */ #include "StandardCLibrary.h" #ifndef CPPUTEST_USE_MEM_LEAK_DETECTION #ifdef CPPUTEST_MEM_LEAK_DETECTION_DISABLED #define CPPUTEST_USE_MEM_LEAK_DETECTION 0 #else #define CPPUTEST_USE_MEM_LEAK_DETECTION 1 #endif #endif #if CPPUTEST_USE_MEM_LEAK_DETECTION #ifndef CPPUTEST_USE_STD_CPP_LIB #ifdef CPPUTEST_STD_CPP_LIB_DISABLED #define CPPUTEST_USE_STD_CPP_LIB 0 #else #define CPPUTEST_USE_STD_CPP_LIB 1 #endif #endif /* This #ifndef prevents <new> from being included twice and enables the file to be included anywhere */ #ifndef CPPUTEST_USE_NEW_MACROS #if CPPUTEST_USE_STD_CPP_LIB #include <new> void* operator new(size_t size, const char* file, int line) throw (std::bad_alloc); void* operator new[](size_t size, const char* file, int line) throw (std::bad_alloc); void* operator new(size_t size) throw(std::bad_alloc); void* operator new[](size_t size) throw(std::bad_alloc); #else void* operator new(size_t size, const char* file, int line); void* operator new[](size_t size, const char* file, int line); void* operator new(size_t size); void* operator new[](size_t size); #endif #endif #define new new(__FILE__, __LINE__) #ifndef CPPUTEST_USE_NEW_MACROS extern "C" { #endif #include "MemoryLeakDetectorMallocMacros.h" #ifndef CPPUTEST_USE_NEW_MACROS } #endif #define CPPUTEST_USE_NEW_MACROS 1 #endif
null
337
cpp
blalor-cpputest
SimpleString.h
include/CppUTest/SimpleString.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /////////////////////////////////////////////////////////////////////////////// // // SIMPLESTRING.H // // One of the design goals of CppUnitLite is to compilation with very old C++ // compilers. For that reason, the simple string class that provides // only the operations needed in CppUnitLite. // /////////////////////////////////////////////////////////////////////////////// #ifndef D_SimpleString_h #define D_SimpleString_h #include "StandardCLibrary.h" class SimpleStringCollection; class MemoryLeakAllocator; class SimpleString { friend bool operator==(const SimpleString& left, const SimpleString& right); friend bool operator!=(const SimpleString& left, const SimpleString& right); public: SimpleString(const char *value = ""); SimpleString(const char *value, size_t repeatCount); SimpleString(const SimpleString& other); ~SimpleString(); SimpleString& operator=(const SimpleString& other); SimpleString operator+(const SimpleString&); SimpleString& operator+=(const SimpleString&); SimpleString& operator+=(const char*); bool contains(const SimpleString& other) const; bool containsNoCase(const SimpleString& other) const; bool startsWith(const SimpleString& other) const; bool endsWith(const SimpleString& other) const; void split(const SimpleString& split, SimpleStringCollection& outCollection) const; bool equalsNoCase(const SimpleString& str) const; size_t count(const SimpleString& str) const; void replace(char to, char with); void replace(const char* to, const char* with); SimpleString toLower() const; SimpleString subString(size_t beginPos, size_t amount) const; void copyToBuffer(char* buffer, size_t bufferSize) const; const char *asCharString() const; size_t size() const; bool isEmpty() const; static void padStringsToSameLength(SimpleString& str1, SimpleString& str2, char ch); static MemoryLeakAllocator* getStringAllocator(); static void setStringAllocator(MemoryLeakAllocator* allocator); static char* allocStringBuffer(size_t size); static void deallocStringBuffer(char* str); private: char *buffer_; static MemoryLeakAllocator* stringAllocator_; char* getEmptyString() const; }; class SimpleStringCollection { public: SimpleStringCollection(); ~SimpleStringCollection(); void allocate(size_t size); size_t size() const; SimpleString& operator[](size_t index); private: SimpleString* collection_; SimpleString empty_; size_t size_; void operator =(SimpleStringCollection&); SimpleStringCollection(SimpleStringCollection&); }; SimpleString StringFrom(bool value); SimpleString StringFrom(const void* value); SimpleString StringFrom(char value); SimpleString StringFrom(const char *value); SimpleString StringFromOrNull(const char * value); SimpleString StringFrom(long value); SimpleString StringFrom(int value); SimpleString HexStringFrom(long value); SimpleString StringFrom(double value, int precision = 6); SimpleString StringFrom(const SimpleString& other); SimpleString StringFromFormat(const char* format, ...); SimpleString VStringFromFormat(const char* format, va_list args); #if CPPUTEST_USE_STD_CPP_LIB #undef new #include <string> #if CPPUTEST_USE_NEW_MACROS #include "CppUTest/MemoryLeakDetectorNewMacros.h" #endif #include <stdint.h> SimpleString StringFrom(const std::string& other); SimpleString StringFrom(uint32_t); SimpleString StringFrom(uint16_t); SimpleString StringFrom(uint8_t); #endif #endif
null
338
cpp
blalor-cpputest
StandardCLibrary.h
include/CppUTest/StandardCLibrary.h
null
#ifndef STANDARDCLIBRARY_H_ #define STANDARDCLIBRARY_H_ #if CPPUTEST_STD_C_LIB_DISABLED #ifdef __KERNEL__ /* Unfinished and not working! Hacking hacking hacking. Why bother make the header files C++ safe! */ #define false kernel_false #define true kernel_true #define bool kernel_bool #define new kernel_new #define _Bool int #include <linux/acpi.h> #include <linux/types.h> #undef false #undef true #undef bool #undef new #else /* * #warning "These definitions in StandardCLibrary.h are pure (educated, from linux kernel) guesses at the moment. Replace with your platform includes." * Not on as warning are as errors :P */ typedef unsigned long size_t; typedef char* va_list; #define NULL (0) extern void* malloc(size_t); extern void free(void *); #define _bnd(X, bnd) (((sizeof (X)) + (bnd)) & (~(bnd))) #define va_start(ap, A) (void) ((ap) = (((char *) &(A)) + (_bnd (A,sizeof(int)-1)))) #define va_end(ap) (void) 0 #endif #else /* Needed for size_t */ #include <stddef.h> /* Needed for malloc */ #include <stdlib.h> /* Needed for ... */ #include <stdarg.h> #endif #endif
null
339
cpp
blalor-cpputest
TestResult.h
include/CppUTest/TestResult.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /////////////////////////////////////////////////////////////////////////////// // // TESTRESULT.H // // A TestResult is a collection of the history of some test runs. Right now // it just collects failures. Really it just prints the failures. // /////////////////////////////////////////////////////////////////////////////// #ifndef D_TestResult_h #define D_TestResult_h class TestFailure; class TestOutput; class Utest; class TestResult { public: TestResult(TestOutput&); virtual ~TestResult(); virtual void testsStarted(); virtual void testsEnded(); virtual void currentGroupStarted(Utest* test); virtual void currentGroupEnded(Utest* test); virtual void currentTestStarted(Utest* test); virtual void currentTestEnded(Utest* test); virtual void countTest(); virtual void countRun(); virtual void countCheck(); virtual void countFilteredOut(); virtual void countIgnored(); virtual void addFailure(const TestFailure& failure); virtual void print(const char* text); virtual void setProgressIndicator(const char*); int getTestCount() const { return testCount_; } int getRunCount() const { return runCount_; } int getCheckCount() const { return checkCount_; } int getFilteredOutCount() const { return filteredOutCount_; } int getIgnoredCount() const { return ignoredCount_; } int getFailureCount() const { return failureCount_; } long getTotalExecutionTime() const; void setTotalExecutionTime(long exTime); long getCurrentTestTotalExecutionTime() const; long getCurrentGroupTotalExecutionTime() const; private: TestOutput& output_; int testCount_; int runCount_; int checkCount_; int failureCount_; int filteredOutCount_; int ignoredCount_; long totalExecutionTime_; long timeStarted_; long currentTestTimeStarted_; long currentTestTotalExecutionTime_; long currentGroupTimeStarted_; long currentGroupTotalExecutionTime_; }; #endif
null
340
cpp
blalor-cpputest
CommandLineTestRunner.h
include/CppUTest/CommandLineTestRunner.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_CommandLineTestRunner_H #define D_CommandLineTestRunner_H #include "TestHarness.h" #include "TestOutput.h" #include "CommandLineArguments.h" /////////////////////////////////////////////////////////////////////////////// // // Main entry point for running a collection of unit tests // /////////////////////////////////////////////////////////////////////////////// class JUnitTestOutput; #define DEF_PLUGIN_MEM_LEAK "MemoryLeakPlugin" #define DEF_PLUGIN_SET_POINTER "SetPointerPlugin" class CommandLineTestRunner { public: enum OutputType { OUTPUT_NORMAL, OUTPUT_JUNIT }; static int RunAllTests(int ac, const char** av); static int RunAllTests(int ac, char** av); CommandLineTestRunner(int ac, const char** av, TestOutput*); virtual ~CommandLineTestRunner(); int runAllTestsMain(); private: TestOutput* output_; JUnitTestOutput* jUnitOutput_; CommandLineArguments* arguments_; bool parseArguments(TestPlugin*); int runAllTests(); void initializeTestRun(); bool isVerbose(); int getRepeatCount(); SimpleString getGroupFilter(); SimpleString getNameFilter(); }; #endif
null
341
cpp
blalor-cpputest
JUnitTestOutput.h
include/CppUTest/JUnitTestOutput.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_JUnitTestOutput_h #define D_JUnitTestOutput_h #include "TestOutput.h" #include "SimpleString.h" struct JUnitTestOutputImpl; struct JUnitTestCaseResultNode; class JUnitTestOutput: public TestOutput { public: JUnitTestOutput(); virtual ~JUnitTestOutput(); virtual void printTestsStarted(); virtual void printTestsEnded(const TestResult& result); virtual void printCurrentTestStarted(const Utest& test); virtual void printCurrentTestEnded(const TestResult& res); virtual void printCurrentGroupStarted(const Utest& test); virtual void printCurrentGroupEnded(const TestResult& res); virtual void verbose(); virtual void printBuffer(const char*); virtual void print(const char*); virtual void print(long); virtual void print(const TestFailure& failure); virtual void printTestRun(int number, int total); virtual void flush(); protected: JUnitTestOutputImpl* impl_; void resetTestGroupResult(); virtual void openFileForWrite(const SimpleString& fileName); virtual void writeTestGroupToFile(); virtual void writeToFile(const SimpleString& buffer); virtual void closeFile(); virtual void writeXmlHeader(); virtual void writeTestSuiteSummery(); virtual void writeProperties(); virtual void writeTestCases(); virtual void writeFailure(JUnitTestCaseResultNode* node); virtual void writeFileEnding(); }; #endif
null
342
cpp
blalor-cpputest
MemoryLeakWarningPlugin.h
include/CppUTest/MemoryLeakWarningPlugin.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_MemoryLeakWarningPlugin_h #define D_MemoryLeakWarningPlugin_h #include "TestPlugin.h" /////////////////////////////////////////////////////////////////////////////// // // MemoryLeakWarning.h // // MemoryLeakWarning defines the inteface to a platform specific // memory leak detection class. See Platforms directory for examples // /////////////////////////////////////////////////////////////////////////////// #define IGNORE_ALL_LEAKS_IN_TEST() MemoryLeakWarningPlugin::getFirstPlugin()->ignoreAllLeaksInTest(); #define EXPECT_N_LEAKS(n) MemoryLeakWarningPlugin::getFirstPlugin()->expectLeaksInTest(n); extern "C" { /* include for size_t definition */ #include "TestHarness_c.h" } #if CPPUTEST_USE_MEM_LEAK_DETECTION #undef new #if CPPUTEST_USE_STD_CPP_LIB #include <new> void* operator new(size_t size) throw(std::bad_alloc); void* operator new[](size_t size) throw(std::bad_alloc); void operator delete(void* mem) throw(); void operator delete[](void* mem) throw(); #else void* operator new(size_t size); void* operator new[](size_t size); void operator delete(void* mem); void operator delete[](void* mem); #endif #if CPPUTEST_USE_NEW_MACROS #include "MemoryLeakDetectorNewMacros.h" #endif #endif class MemoryLeakDetector; class MemoryLeakWarningPlugin: public TestPlugin { public: MemoryLeakWarningPlugin(const SimpleString& name, MemoryLeakDetector* localDetector = 0); virtual ~MemoryLeakWarningPlugin(); virtual void preTestAction(Utest& test, TestResult& result); virtual void postTestAction(Utest& test, TestResult& result); virtual const char* FinalReport(int toBeDeletedLeaks = 0); void ignoreAllLeaksInTest(); void expectLeaksInTest(int n); MemoryLeakDetector* getMemoryLeakDetector(); static MemoryLeakWarningPlugin* getFirstPlugin(); static MemoryLeakDetector* getGlobalDetector(); private: MemoryLeakDetector* memLeakDetector_; bool ignoreAllWarnings_; int expectedLeaks_; int failureCount_; static MemoryLeakWarningPlugin* firstPlugin_; }; #endif
null
343
cpp
blalor-cpputest
TestHarness.h
include/CppUTest/TestHarness.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_TestHarness_h #define D_TestHarness_h /* Memory leak detector macros: * * CPPUTEST_USE_MEM_LEAK_DETECTION pr CPPUTEST_MEM_LEAK_DETECTION_DISABLED * Controls the override of the global operator new/deleted and malloc/free. * Without this, there will be no memory leak detection in C/C++. */ #ifndef CPPUTEST_USE_MEM_LEAK_DETECTION #ifdef CPPUTEST_MEM_LEAK_DETECTION_DISABLED #define CPPUTEST_USE_MEM_LEAK_DETECTION 0 #else #define CPPUTEST_USE_MEM_LEAK_DETECTION 1 #endif #endif #ifndef CPPUTEST_USE_STD_CPP_LIB #ifdef CPPUTEST_STD_CPP_LIB_DISABLED #define CPPUTEST_USE_STD_CPP_LIB 0 #else #define CPPUTEST_USE_STD_CPP_LIB 1 #endif #endif /* original value was 9973 which works well with large programs. Now set to smaller since it takes * a lot of memory in embedded apps. Change it if you experience the memory leak detector to be slow. */ #define MEMORY_LEAK_HASH_TABLE_SIZE 73 /* * Lib C dependencies that are currently still left: * * stdarg.h -> We use formatting functions and va_list requires to include stdarg.h in SimpleString * stdlib.h -> The TestHarness_c.h includes this to try to avoid conflicts in its malloc #define. This dependency can * easily be removed by not enabling the MALLOC overrides. * * Lib C++ dependencies are all under the CPPUTEST_USE_STD_CPP_LIB. * The only dependency is to <new> which has the bad_alloc struct * */ #include "Utest.h" #include "UtestMacros.h" #include "SimpleString.h" #include "TestResult.h" #include "TestFailure.h" #include "TestPlugin.h" #include "MemoryLeakWarningPlugin.h" #endif
null
344
cpp
blalor-cpputest
TestTestingFixture.h
include/CppUTest/TestTestingFixture.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_TestTestingFixture_H #define D_TestTestingFixture_H class TestTestingFixture { public: TestTestingFixture() { output_ = new StringBufferTestOutput(); result_ = new TestResult(*output_); genTest_ = new ExecFunctionTest(); registry_ = new TestRegistry(); registry_->setCurrentRegistry(registry_); registry_->addTest(genTest_); } ; virtual ~TestTestingFixture() { registry_->setCurrentRegistry(0); delete registry_; delete result_; delete output_; delete genTest_; } void setTestFunction(void(*testFunction)()) { genTest_->testFunction_ = testFunction; } void setSetup(void(*setupFunction)()) { genTest_->setup_ = setupFunction; } void setTeardown(void(*teardownFunction)()) { genTest_->teardown_ = teardownFunction; } void runAllTests() { registry_->runAllTests(*result_); } int getFailureCount() { return result_->getFailureCount(); } void assertPrintContains(const SimpleString& contains) { assertPrintContains(output_, contains); } static void assertPrintContains(StringBufferTestOutput* output, const SimpleString& contains) { if (output->getOutput().contains(contains)) return; SimpleString message("\tActual <"); message += output->getOutput().asCharString(); message += ">\n"; message += "\tdid not contain <"; message += contains.asCharString(); message += ">\n"; FAIL(message.asCharString()); } TestRegistry* registry_; ExecFunctionTest* genTest_; StringBufferTestOutput* output_; TestResult * result_; }; #endif
null
345
cpp
blalor-cpputest
TestRegistry.h
include/CppUTest/TestRegistry.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /////////////////////////////////////////////////////////////////////////////// // // TESTREGISTRY.H // // TestRegistry is a collection of tests that can be run // /////////////////////////////////////////////////////////////////////////////// #ifndef D_TestRegistry_h #define D_TestRegistry_h #include "SimpleString.h" class Utest; class TestResult; class TestPlugin; class TestRegistry { public: TestRegistry(); virtual ~TestRegistry(); virtual void addTest(Utest *test); virtual void unDoLastAddTest(); virtual int countTests(); virtual void runAllTests(TestResult& result); virtual void nameFilter(SimpleString); virtual void groupFilter(SimpleString); virtual void installPlugin(TestPlugin* plugin); virtual void resetPlugins(); virtual TestPlugin* getFirstPlugin(); virtual TestPlugin* getPluginByName(const SimpleString& name); virtual void removePluginByName(const SimpleString& name); SimpleString getGroupFilter(); SimpleString getNameFilter(); virtual Utest* getFirstTest(); virtual Utest* getLastTest(); virtual Utest* getTestWithNext(Utest* test); static TestRegistry* getCurrentRegistry(); virtual void setCurrentRegistry(TestRegistry* registry); void cleanup(); private: bool testShouldRun(Utest* test, TestResult& result); bool endOfGroup(Utest* test); Utest * tests_; SimpleString* nameFilter_; SimpleString* groupFilter_; TestPlugin* firstPlugin_; static TestRegistry* currentRegistry_; }; #endif
null
346
cpp
blalor-cpputest
Utest.h
include/CppUTest/Utest.h
null
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // This file contains the Test class along with the macros which make effective // in the harness. #ifndef D_UTest_h #define D_UTest_h #include "SimpleString.h" /*! \brief UTest.h * \ingroup someGroup * * Something about UTest.h * * \see TEST_GROUP * \see TEST */ class TestResult; class TestPlugin; class TestFailure; extern bool doubles_equal(double d1, double d2, double threshold); class Utest { public: Utest(const char* groupName, const char* testName, const char* fileName, int lineNumber); virtual ~Utest(); virtual void run(TestResult& result); virtual void runOneTestWithPlugins(TestPlugin* plugin, TestResult& result); virtual SimpleString getFormattedName() const; virtual Utest* addTest(Utest* test); virtual Utest *getNext() const; virtual bool isNull() const; virtual int countTests(); bool shouldRun(const SimpleString& groupFilter, const SimpleString& nameFilter) const; const SimpleString getName() const; const SimpleString getGroup() const; const SimpleString getFile() const; int getLineNumber() const; const virtual char *getProgressIndicator() const; virtual void setup(); virtual void teardown(); virtual void testBody(); static TestResult *getTestResult(); static Utest *getCurrent(); virtual void assertTrue(bool condition, const char *checkString, const char *conditionString, const char *fileName, int lineNumber); virtual void assertCstrEqual(const char *expected, const char *actual, const char *fileName, int lineNumber); virtual void assertCstrNoCaseEqual(const char *expected, const char *actual, const char *fileName, int lineNumber); virtual void assertCstrContains(const char *expected, const char *actual, const char *fileName, int lineNumber); virtual void assertCstrNoCaseContains(const char *expected, const char *actual, const char *fileName, int lineNumber); virtual void assertLongsEqual(long expected, long actual, const char *fileName, int lineNumber); virtual void assertPointersEqual(const void *expected, const void *actual, const char *fileName, int lineNumber); virtual void assertDoublesEqual(double expected, double actual, double threshold, const char *fileName, int lineNumber); virtual void fail(const char *text, const char *fileName, int lineNumber); virtual void print(const char *text, const char *fileName, int lineNumber); virtual void print(const SimpleString & text, const char *fileName, int lineNumber); void setFileName(const char *fileName); void setLineNumber(int lineNumber); void setGroupName(const char *groupName); void setTestName(const char *testName); virtual void exitCurrentTest(); protected: virtual void runOneTest(TestPlugin *plugin, TestResult & result); virtual void executePlatformSpecificRunOneTest(TestPlugin *plugin, TestResult & result); virtual bool executePlatformSpecificSetup(); virtual void executePlatformSpecificTestBody(); virtual void executePlatformSpecificTeardown(); virtual void executePlatformSpecificExitCurrentTest(); Utest(); Utest(const char *groupName, const char *testName, const char *fileName, int lineNumber, Utest *nextTest); virtual SimpleString getMacroName() const; private: const char *group_; const char *name_; const char *file_; int lineNumber_; Utest *next_; void setTestResult(TestResult* result); void setCurrentTest(Utest* test); static Utest* currentTest_; static TestResult* testResult_; void failWith(const TestFailure& failure); }; //////////////////// NulLTest class NullTest: public Utest { public: explicit NullTest(); explicit NullTest(const char* fileName, int lineNumber); virtual ~NullTest(); void testBody() { } static NullTest& instance(); virtual int countTests(); virtual Utest*getNext() const; virtual bool isNull() const; private: NullTest(const NullTest&); NullTest& operator=(const NullTest&); }; //////////////////// ExecFunctionTest class ExecFunctionTest: public Utest { public: void (*setup_)(); void (*teardown_)(); void (*testFunction_)(); ExecFunctionTest(void(*set)() = 0, void(*tear)() = 0) : Utest("Generic", "Generic", "Generic", 1), setup_(set), teardown_( tear), testFunction_(0) { } void testBody() { if (testFunction_) testFunction_(); } virtual void setup() { if (setup_) setup_(); } virtual void teardown() { if (teardown_) teardown_(); } }; //////////////////// TestInstaller class TestInstaller { public: explicit TestInstaller(Utest*, const char* groupName, const char* testName, const char* fileName, int lineNumber); virtual ~TestInstaller(); void unDo(); private: TestInstaller(const TestInstaller&); TestInstaller& operator=(const TestInstaller&); }; #endif
null
347
cpp
blalor-cpputest
MemoryLeakDetectorMallocMacros.h
include/CppUTest/MemoryLeakDetectorMallocMacros.h
null
/* * This file can be used to get extra debugging information about memory leaks in your production code. * It defines a preprocessor macro for malloc. This will pass additional information to the * malloc and this will give the line/file information of the memory leaks in your code. * * You can use this by including this file to all your production code. When using gcc, you can use * the -include file to do this for you. * */ /* Warning for maintainers: * This macro code is duplicate from TestHarness.h. The reason for this is to make the two files * completely independent from each other. NewMacros file can be included in production code whereas * TestHarness.h is only included in test code. */ #ifndef CPPUTEST_USE_MEM_LEAK_DETECTION #ifdef CPPUTEST_MEM_LEAK_DETECTION_DISABLED #define CPPUTEST_USE_MEM_LEAK_DETECTION 0 #else #define CPPUTEST_USE_MEM_LEAK_DETECTION 1 #endif #endif #if CPPUTEST_USE_MEM_LEAK_DETECTION /* This prevents the declaration from done twice and makes sure the file only #defines malloc, so it can be included anywhere */ #ifndef CPPUTEST_USE_MALLOC_MACROS #include "StandardCLibrary.h" extern void* cpputest_malloc_location(size_t size, const char* file, int line); extern void* cpputest_calloc_location(size_t count, size_t size, const char* file, int line); extern void* cpputest_ralloc_location(void *, size_t, const char* file, int line); extern void cpputest_free_location(void* buffer, const char* file, int line); #endif /* NOTE on strdup! * * strdup was implemented earlier, however it is *not* an Standard C function but a POSIX function. * Because of that, it can lead to portability issues by providing more than is available on the local platform. * For that reason, strdup is *not* implemented as a macro. If you still want to use it, an easy implementation would be: * * size_t length = 1 + strlen(str); * char* result = (char*) cpputest_malloc_location(length, file, line); * memcpy(result, str, length); * return result; * */ #define malloc(a) cpputest_malloc_location(a, __FILE__, __LINE__) #define calloc(a, b) cpputest_calloc_location(a, b, __FILE__, __LINE__) #define realloc(a, b) cpputest_realloc_location(a, b, __FILE__, __LINE__) #define free(a) cpputest_free_location(a, __FILE__, __LINE__) #define CPPUTEST_USE_MALLOC_MACROS 1 #endif
null