[修改] 增加freeRTOS

1. 版本FreeRTOSv202212.01,命名为kernel;
This commit is contained in:
2023-05-06 16:43:01 +00:00
commit a345df017b
20944 changed files with 11094377 additions and 0 deletions

View File

@ -0,0 +1,26 @@
Eclipse error parsers
=====================
These are a godsend for extracting & quickly navigating to
warnings & error messages from console output. Unforunately
I don't know how to write an Eclipse plugin so you'll have
to add them manually.
To add a console parser to Eclipse, go to Window --> Preferences
--> C/C++ --> Build --> Settings. Click on the 'Error Parsers'
tab and then click the 'Add...' button. See the table below for
the parser fields to add.
Eclipse will only parse the console output during a build, so
running your unit tests must be part of your build process.
Either add this to your make/rakefile, or add it as a post-
build step in your Eclipse project settings.
Unity unit test error parsers
-----------------------------
Severity Pattern File Line Description
-------------------------------------------------------------------------------
Error (\.+)(.*?):(\d+):(.*?):FAIL: (.*) $2 $3 $5
Warning (\.+)(.*?):(\d+):(.*?):IGNORE: (.*) $2 $3 $5
Warning (\.+)(.*?):(\d+):(.*?):IGNORE\s*$ $2 $3 Ignored test

View File

@ -0,0 +1,29 @@
# Unity Fixtures
This Framework is an optional add-on to Unity. By including unity_framework.h in place of unity.h,
you may now work with Unity in a manner similar to CppUTest. This framework adds the concepts of
test groups and gives finer control of your tests over the command line.
This framework is primarily supplied for those working through James Grenning's book on Embedded
Test Driven Development, or those coming to Unity from CppUTest. We should note that using this
framework glosses over some of the features of Unity, and makes it more difficult
to integrate with other testing tools like Ceedling and CMock.
# Dependency Notification
Fixtures, by default, uses the Memory addon as well. This is to make it simple for those trying to
follow along with James' book. Using them together is completely optional. You may choose to use
Fixtures without Memory handling by defining `UNITY_FIXTURE_NO_EXTRAS`. It will then stop automatically
pulling in extras and leave you to do it as desired.
# Usage information
By default the test executables produced by Unity Fixtures run all tests once, but the behavior can
be configured with command-line flags. Run the test executable with the `--help` flag for more
information.
It's possible to add a custom line at the end of the help message, typically to point to
project-specific or company-specific unit test documentation. Define `UNITY_CUSTOM_HELP_MSG` to
provide a custom message, e.g.:
#define UNITY_CUSTOM_HELP_MSG "If any test fails see https://example.com/troubleshooting"

View File

@ -0,0 +1,310 @@
/* Copyright (c) 2010 James Grenning and Contributed to Unity Project
* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#include "unity_fixture.h"
#include "unity_internals.h"
#include <string.h>
struct UNITY_FIXTURE_T UnityFixture;
/* If you decide to use the function pointer approach.
* Build with -D UNITY_OUTPUT_CHAR=outputChar and include <stdio.h>
* int (*outputChar)(int) = putchar; */
void setUp(void) { /*does nothing*/ }
void tearDown(void) { /*does nothing*/ }
static void announceTestRun(unsigned int runNumber)
{
UnityPrint("Unity test run ");
UnityPrintNumberUnsigned(runNumber+1);
UnityPrint(" of ");
UnityPrintNumberUnsigned(UnityFixture.RepeatCount);
UNITY_PRINT_EOL();
}
int UnityMain(int argc, const char* argv[], void (*runAllTests)(void))
{
int result = UnityGetCommandLineOptions(argc, argv);
unsigned int r;
if (result != 0)
return result;
for (r = 0; r < UnityFixture.RepeatCount; r++)
{
UnityBegin(argv[0]);
announceTestRun(r);
runAllTests();
if (!UnityFixture.Verbose) UNITY_PRINT_EOL();
UnityEnd();
}
return (int)Unity.TestFailures;
}
static int selected(const char* filter, const char* name)
{
if (filter == 0)
return 1;
return strstr(name, filter) ? 1 : 0;
}
static int testSelected(const char* test)
{
return selected(UnityFixture.NameFilter, test);
}
static int groupSelected(const char* group)
{
return selected(UnityFixture.GroupFilter, group);
}
void UnityTestRunner(unityfunction* setup,
unityfunction* testBody,
unityfunction* teardown,
const char* printableName,
const char* group,
const char* name,
const char* file,
unsigned int line)
{
if (testSelected(name) && groupSelected(group))
{
Unity.TestFile = file;
Unity.CurrentTestName = printableName;
Unity.CurrentTestLineNumber = line;
if (UnityFixture.Verbose)
{
UnityPrint(printableName);
#ifndef UNITY_REPEAT_TEST_NAME
Unity.CurrentTestName = NULL;
#endif
}
else if (UnityFixture.Silent)
{
/* Do Nothing */
}
else
{
UNITY_OUTPUT_CHAR('.');
}
Unity.NumberOfTests++;
UnityPointer_Init();
UNITY_EXEC_TIME_START();
if (TEST_PROTECT())
{
setup();
testBody();
}
if (TEST_PROTECT())
{
teardown();
}
if (TEST_PROTECT())
{
UnityPointer_UndoAllSets();
}
UnityConcludeFixtureTest();
}
}
void UnityIgnoreTest(const char* printableName, const char* group, const char* name)
{
if (testSelected(name) && groupSelected(group))
{
Unity.NumberOfTests++;
Unity.TestIgnores++;
if (UnityFixture.Verbose)
{
UnityPrint(printableName);
UNITY_PRINT_EOL();
}
else if (UnityFixture.Silent)
{
/* Do Nothing */
}
else
{
UNITY_OUTPUT_CHAR('!');
}
}
}
/*-------------------------------------------------------- */
/*Automatic pointer restoration functions */
struct PointerPair
{
void** pointer;
void* old_value;
};
static struct PointerPair pointer_store[UNITY_MAX_POINTERS];
static int pointer_index = 0;
void UnityPointer_Init(void)
{
pointer_index = 0;
}
void UnityPointer_Set(void** pointer, void* newValue, UNITY_LINE_TYPE line)
{
if (pointer_index >= UNITY_MAX_POINTERS)
{
UNITY_TEST_FAIL(line, "Too many pointers set");
}
else
{
pointer_store[pointer_index].pointer = pointer;
pointer_store[pointer_index].old_value = *pointer;
*pointer = newValue;
pointer_index++;
}
}
void UnityPointer_UndoAllSets(void)
{
while (pointer_index > 0)
{
pointer_index--;
*(pointer_store[pointer_index].pointer) =
pointer_store[pointer_index].old_value;
}
}
int UnityGetCommandLineOptions(int argc, const char* argv[])
{
int i;
UnityFixture.Verbose = 0;
UnityFixture.Silent = 0;
UnityFixture.GroupFilter = 0;
UnityFixture.NameFilter = 0;
UnityFixture.RepeatCount = 1;
if (argc == 1)
return 0;
for (i = 1; i < argc; )
{
if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0)
{
/* Usage */
UnityPrint("Runs a series of unit tests.");
UNITY_PRINT_EOL();
UNITY_PRINT_EOL();
UnityPrint("When no flag is specified, all tests are run.");
UNITY_PRINT_EOL();
UNITY_PRINT_EOL();
UnityPrint("Optional flags:");
UNITY_PRINT_EOL();
UnityPrint(" -v Verbose output: show all tests executed even if they pass");
UNITY_PRINT_EOL();
UnityPrint(" -s Silent mode: minimal output showing only test failures");
UNITY_PRINT_EOL();
UnityPrint(" -g NAME Only run tests in groups that contain the string NAME");
UNITY_PRINT_EOL();
UnityPrint(" -n NAME Only run tests whose name contains the string NAME");
UNITY_PRINT_EOL();
UnityPrint(" -r NUMBER Repeatedly run all tests NUMBER times");
UNITY_PRINT_EOL();
UnityPrint(" -h, --help Display this help message");
UNITY_PRINT_EOL();
UNITY_PRINT_EOL();
#ifdef UNITY_CUSTOM_HELP_MSG
/* User-defined help message, e.g. to point to project-specific documentation */
UnityPrint(UNITY_CUSTOM_HELP_MSG);
UNITY_PRINT_EOL();
#else
/* Default help suffix if a custom one is not defined */
UnityPrint("More information about Unity: https://www.throwtheswitch.org/unity");
UNITY_PRINT_EOL();
#endif
return 1; /* Exit without running the tests */
}
else if (strcmp(argv[i], "-v") == 0)
{
UnityFixture.Verbose = 1;
i++;
}
else if (strcmp(argv[i], "-s") == 0)
{
UnityFixture.Silent = 1;
i++;
}
else if (strcmp(argv[i], "-g") == 0)
{
i++;
if (i >= argc)
return 1;
UnityFixture.GroupFilter = argv[i];
i++;
}
else if (strcmp(argv[i], "-n") == 0)
{
i++;
if (i >= argc)
return 1;
UnityFixture.NameFilter = argv[i];
i++;
}
else if (strcmp(argv[i], "-r") == 0)
{
UnityFixture.RepeatCount = 2;
i++;
if (i < argc)
{
if (*(argv[i]) >= '0' && *(argv[i]) <= '9')
{
unsigned int digit = 0;
UnityFixture.RepeatCount = 0;
while (argv[i][digit] >= '0' && argv[i][digit] <= '9')
{
UnityFixture.RepeatCount *= 10;
UnityFixture.RepeatCount += (unsigned int)argv[i][digit++] - '0';
}
i++;
}
}
}
else
{
/* ignore unknown parameter */
i++;
}
}
return 0;
}
void UnityConcludeFixtureTest(void)
{
if (Unity.CurrentTestIgnored)
{
Unity.TestIgnores++;
UNITY_PRINT_EOL();
}
else if (!Unity.CurrentTestFailed)
{
if (UnityFixture.Verbose)
{
UnityPrint(" ");
UnityPrint(UnityStrPass);
UNITY_EXEC_TIME_STOP();
UNITY_PRINT_EXEC_TIME();
UNITY_PRINT_EOL();
}
}
else /* Unity.CurrentTestFailed */
{
Unity.TestFailures++;
UNITY_PRINT_EOL();
}
Unity.CurrentTestFailed = 0;
Unity.CurrentTestIgnored = 0;
}

View File

@ -0,0 +1,83 @@
/* Copyright (c) 2010 James Grenning and Contributed to Unity Project
* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#ifndef UNITY_FIXTURE_H_
#define UNITY_FIXTURE_H_
#include "unity.h"
#include "unity_internals.h"
#include "unity_fixture_internals.h"
#ifndef UNITY_FIXTURE_NO_EXTRAS
#include "unity_memory.h"
#endif
int UnityMain(int argc, const char* argv[], void (*runAllTests)(void));
#define TEST_GROUP(group)\
static const char* TEST_GROUP_##group = #group
#define TEST_SETUP(group) void TEST_##group##_SETUP(void);\
void TEST_##group##_SETUP(void)
#define TEST_TEAR_DOWN(group) void TEST_##group##_TEAR_DOWN(void);\
void TEST_##group##_TEAR_DOWN(void)
#define TEST(group, name) \
void TEST_##group##_##name##_(void);\
void TEST_##group##_##name##_run(void);\
void TEST_##group##_##name##_run(void)\
{\
UnityTestRunner(TEST_##group##_SETUP,\
TEST_##group##_##name##_,\
TEST_##group##_TEAR_DOWN,\
"TEST(" #group ", " #name ")",\
TEST_GROUP_##group, #name,\
__FILE__, __LINE__);\
}\
void TEST_##group##_##name##_(void)
#define IGNORE_TEST(group, name) \
void TEST_##group##_##name##_(void);\
void TEST_##group##_##name##_run(void);\
void TEST_##group##_##name##_run(void)\
{\
UnityIgnoreTest("IGNORE_TEST(" #group ", " #name ")", TEST_GROUP_##group, #name);\
}\
void TEST_##group##_##name##_(void)
/* Call this for each test, insider the group runner */
#define RUN_TEST_CASE(group, name) \
{ void TEST_##group##_##name##_run(void);\
TEST_##group##_##name##_run(); }
/* This goes at the bottom of each test file or in a separate c file */
#define TEST_GROUP_RUNNER(group)\
void TEST_##group##_GROUP_RUNNER(void);\
void TEST_##group##_GROUP_RUNNER(void)
/* Call this from main */
#define RUN_TEST_GROUP(group)\
{ void TEST_##group##_GROUP_RUNNER(void);\
TEST_##group##_GROUP_RUNNER(); }
/* CppUTest Compatibility Macros */
#ifndef UNITY_EXCLUDE_CPPUTEST_ASSERTS
/* Sets a pointer and automatically restores it to its old value after teardown */
#define UT_PTR_SET(ptr, newPointerValue) UnityPointer_Set((void**)&(ptr), (void*)(newPointerValue), __LINE__)
#define TEST_ASSERT_POINTERS_EQUAL(expected, actual) TEST_ASSERT_EQUAL_PTR((expected), (actual))
#define TEST_ASSERT_BYTES_EQUAL(expected, actual) TEST_ASSERT_EQUAL_HEX8(0xff & (expected), 0xff & (actual))
#define FAIL(message) TEST_FAIL_MESSAGE((message))
#define CHECK(condition) TEST_ASSERT_TRUE((condition))
#define LONGS_EQUAL(expected, actual) TEST_ASSERT_EQUAL_INT((expected), (actual))
#define STRCMP_EQUAL(expected, actual) TEST_ASSERT_EQUAL_STRING((expected), (actual))
#define DOUBLES_EQUAL(expected, actual, delta) TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual))
#endif
#endif /* UNITY_FIXTURE_H_ */

View File

@ -0,0 +1,50 @@
/* Copyright (c) 2010 James Grenning and Contributed to Unity Project
* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#ifndef UNITY_FIXTURE_INTERNALS_H_
#define UNITY_FIXTURE_INTERNALS_H_
#ifdef __cplusplus
extern "C"
{
#endif
struct UNITY_FIXTURE_T
{
int Verbose;
int Silent;
unsigned int RepeatCount;
const char* NameFilter;
const char* GroupFilter;
};
extern struct UNITY_FIXTURE_T UnityFixture;
typedef void unityfunction(void);
void UnityTestRunner(unityfunction* setup,
unityfunction* testBody,
unityfunction* teardown,
const char* printableName,
const char* group,
const char* name,
const char* file, unsigned int line);
void UnityIgnoreTest(const char* printableName, const char* group, const char* name);
int UnityGetCommandLineOptions(int argc, const char* argv[]);
void UnityConcludeFixtureTest(void);
void UnityPointer_Set(void** pointer, void* newValue, UNITY_LINE_TYPE line);
void UnityPointer_UndoAllSets(void);
void UnityPointer_Init(void);
#ifndef UNITY_MAX_POINTERS
#define UNITY_MAX_POINTERS 5
#endif
#ifdef __cplusplus
}
#endif
#endif /* UNITY_FIXTURE_INTERNALS_H_ */

View File

@ -0,0 +1,72 @@
CC = gcc
ifeq ($(shell uname -s), Darwin)
CC = clang
endif
#DEBUG = -O0 -g
CFLAGS += -std=c99 -pedantic -Wall -Wextra -Werror -DUNITY_FIXTURE_NO_EXTRAS
CFLAGS += $(DEBUG)
SRC = ../src/unity_fixture.c \
../../../src/unity.c \
unity_fixture_Test.c \
unity_fixture_TestRunner.c \
main/AllTests.c
INC_DIR = -I../src -I../../../src/
BUILD_DIR = ../build
TARGET = ../build/fixture_tests.exe
all: default noStdlibMalloc 32bits
default: $(BUILD_DIR)
$(CC) $(CFLAGS) $(DEFINES) $(SRC) $(INC_DIR) -o $(TARGET) -D UNITY_SUPPORT_64
@ echo "default build"
./$(TARGET)
32bits: $(BUILD_DIR)
$(CC) $(CFLAGS) $(DEFINES) $(SRC) $(INC_DIR) -o $(TARGET) -m32
@ echo "32bits build"
./$(TARGET)
noStdlibMalloc: $(BUILD_DIR)
$(CC) $(CFLAGS) $(DEFINES) $(SRC) $(INC_DIR) -o $(TARGET) -D UNITY_EXCLUDE_STDLIB_MALLOC
@ echo "build with noStdlibMalloc"
./$(TARGET)
C89: CFLAGS += -D UNITY_EXCLUDE_STDINT_H # C89 did not have type 'long long', <stdint.h>
C89: $(BUILD_DIR)
$(CC) $(CFLAGS) $(DEFINES) $(SRC) $(INC_DIR) -o $(TARGET) -std=c89 && ./$(TARGET)
$(CC) $(CFLAGS) $(DEFINES) $(SRC) $(INC_DIR) -o $(TARGET) -D UNITY_EXCLUDE_STDLIB_MALLOC -std=c89
./$(TARGET)
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
clean:
rm -f $(TARGET) $(BUILD_DIR)/*.gc*
cov: $(BUILD_DIR)
cd $(BUILD_DIR) && \
$(CC) $(DEFINES) $(foreach i, $(SRC), ../test/$(i)) $(INC_DIR) -o $(TARGET) -fprofile-arcs -ftest-coverage
rm -f $(BUILD_DIR)/*.gcda
./$(TARGET) > /dev/null ; ./$(TARGET) -v > /dev/null
cd $(BUILD_DIR) && \
gcov unity_fixture.c | head -3
grep '###' $(BUILD_DIR)/unity_fixture.c.gcov -C2 || true # Show uncovered lines
# These extended flags DO get included before any target build runs
CFLAGS += -Wbad-function-cast
CFLAGS += -Wcast-qual
CFLAGS += -Wconversion
CFLAGS += -Wformat=2
CFLAGS += -Wmissing-prototypes
CFLAGS += -Wold-style-definition
CFLAGS += -Wpointer-arith
CFLAGS += -Wshadow
CFLAGS += -Wstrict-overflow=5
CFLAGS += -Wstrict-prototypes
CFLAGS += -Wswitch-default
CFLAGS += -Wundef
CFLAGS += -Wno-error=undef # Warning only, this should not stop the build
CFLAGS += -Wunreachable-code
CFLAGS += -Wunused
CFLAGS += -fstrict-aliasing

View File

@ -0,0 +1,20 @@
/* Copyright (c) 2010 James Grenning and Contributed to Unity Project
* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#include "unity_fixture.h"
static void runAllTests(void)
{
RUN_TEST_GROUP(UnityFixture);
RUN_TEST_GROUP(UnityCommandOptions);
}
int main(int argc, const char* argv[])
{
return UnityMain(argc, argv, runAllTests);
}

View File

@ -0,0 +1,39 @@
/* Copyright (c) 2010 James Grenning and Contributed to Unity Project
* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#include "unity_fixture.h"
static int data = -1;
TEST_GROUP(mygroup);
TEST_SETUP(mygroup)
{
data = 0;
}
TEST_TEAR_DOWN(mygroup)
{
data = -1;
}
TEST(mygroup, test1)
{
TEST_ASSERT_EQUAL_INT(0, data);
}
TEST(mygroup, test2)
{
TEST_ASSERT_EQUAL_INT(0, data);
data = 5;
}
TEST(mygroup, test3)
{
data = 7;
TEST_ASSERT_EQUAL_INT(7, data);
}

View File

@ -0,0 +1,245 @@
/* Copyright (c) 2010 James Grenning and Contributed to Unity Project
* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#include "unity_fixture.h"
#include <stdlib.h>
#include <string.h>
TEST_GROUP(UnityFixture);
TEST_SETUP(UnityFixture)
{
}
TEST_TEAR_DOWN(UnityFixture)
{
}
static int* pointer1 = 0;
static int* pointer2 = (int*)2;
static int* pointer3 = (int*)3;
static int int1;
static int int2;
static int int3;
static int int4;
TEST(UnityFixture, PointerSetting)
{
TEST_ASSERT_POINTERS_EQUAL(pointer1, 0);
UT_PTR_SET(pointer1, &int1);
UT_PTR_SET(pointer2, &int2);
UT_PTR_SET(pointer3, &int3);
TEST_ASSERT_POINTERS_EQUAL(pointer1, &int1);
TEST_ASSERT_POINTERS_EQUAL(pointer2, &int2);
TEST_ASSERT_POINTERS_EQUAL(pointer3, &int3);
UT_PTR_SET(pointer1, &int4);
UnityPointer_UndoAllSets();
TEST_ASSERT_POINTERS_EQUAL(pointer1, 0);
TEST_ASSERT_POINTERS_EQUAL(pointer2, (int*)2);
TEST_ASSERT_POINTERS_EQUAL(pointer3, (int*)3);
}
static char *p1;
static char *p2;
TEST(UnityFixture, PointerSet)
{
char c1;
char c2;
char newC1;
char newC2;
p1 = &c1;
p2 = &c2;
UnityPointer_Init();
UT_PTR_SET(p1, &newC1);
UT_PTR_SET(p2, &newC2);
TEST_ASSERT_POINTERS_EQUAL(&newC1, p1);
TEST_ASSERT_POINTERS_EQUAL(&newC2, p2);
UnityPointer_UndoAllSets();
TEST_ASSERT_POINTERS_EQUAL(&c1, p1);
TEST_ASSERT_POINTERS_EQUAL(&c2, p2);
}
TEST(UnityFixture, FreeNULLSafety)
{
free(NULL);
}
TEST(UnityFixture, ConcludeTestIncrementsFailCount)
{
UNITY_UINT savedFails = Unity.TestFailures;
UNITY_UINT savedIgnores = Unity.TestIgnores;
Unity.CurrentTestFailed = 1;
UnityConcludeFixtureTest(); /* Resets TestFailed for this test to pass */
Unity.CurrentTestIgnored = 1;
UnityConcludeFixtureTest(); /* Resets TestIgnored */
TEST_ASSERT_EQUAL(savedFails + 1, Unity.TestFailures);
TEST_ASSERT_EQUAL(savedIgnores + 1, Unity.TestIgnores);
Unity.TestFailures = savedFails;
Unity.TestIgnores = savedIgnores;
}
/*------------------------------------------------------------ */
TEST_GROUP(UnityCommandOptions);
static int savedVerbose;
static unsigned int savedRepeat;
static const char* savedName;
static const char* savedGroup;
TEST_SETUP(UnityCommandOptions)
{
savedVerbose = UnityFixture.Verbose;
savedRepeat = UnityFixture.RepeatCount;
savedName = UnityFixture.NameFilter;
savedGroup = UnityFixture.GroupFilter;
}
TEST_TEAR_DOWN(UnityCommandOptions)
{
UnityFixture.Verbose = savedVerbose;
UnityFixture.RepeatCount= savedRepeat;
UnityFixture.NameFilter = savedName;
UnityFixture.GroupFilter = savedGroup;
}
static const char* noOptions[] = {
"testrunner.exe"
};
TEST(UnityCommandOptions, DefaultOptions)
{
UnityGetCommandLineOptions(1, noOptions);
TEST_ASSERT_EQUAL(0, UnityFixture.Verbose);
TEST_ASSERT_POINTERS_EQUAL(0, UnityFixture.GroupFilter);
TEST_ASSERT_POINTERS_EQUAL(0, UnityFixture.NameFilter);
TEST_ASSERT_EQUAL(1, UnityFixture.RepeatCount);
}
static const char* verbose[] = {
"testrunner.exe",
"-v"
};
TEST(UnityCommandOptions, OptionVerbose)
{
TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(2, verbose));
TEST_ASSERT_EQUAL(1, UnityFixture.Verbose);
}
static const char* group[] = {
"testrunner.exe",
"-g", "groupname"
};
TEST(UnityCommandOptions, OptionSelectTestByGroup)
{
TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(3, group));
STRCMP_EQUAL("groupname", UnityFixture.GroupFilter);
}
static const char* name[] = {
"testrunner.exe",
"-n", "testname"
};
TEST(UnityCommandOptions, OptionSelectTestByName)
{
TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(3, name));
STRCMP_EQUAL("testname", UnityFixture.NameFilter);
}
static const char* repeat[] = {
"testrunner.exe",
"-r", "99"
};
TEST(UnityCommandOptions, OptionSelectRepeatTestsDefaultCount)
{
TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(2, repeat));
TEST_ASSERT_EQUAL(2, UnityFixture.RepeatCount);
}
TEST(UnityCommandOptions, OptionSelectRepeatTestsSpecificCount)
{
TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(3, repeat));
TEST_ASSERT_EQUAL(99, UnityFixture.RepeatCount);
}
static const char* multiple[] = {
"testrunner.exe",
"-v",
"-g", "groupname",
"-n", "testname",
"-r", "98"
};
TEST(UnityCommandOptions, MultipleOptions)
{
TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(8, multiple));
TEST_ASSERT_EQUAL(1, UnityFixture.Verbose);
STRCMP_EQUAL("groupname", UnityFixture.GroupFilter);
STRCMP_EQUAL("testname", UnityFixture.NameFilter);
TEST_ASSERT_EQUAL(98, UnityFixture.RepeatCount);
}
static const char* dashRNotLast[] = {
"testrunner.exe",
"-v",
"-g", "gggg",
"-r",
"-n", "tttt",
};
TEST(UnityCommandOptions, MultipleOptionsDashRNotLastAndNoValueSpecified)
{
TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(7, dashRNotLast));
TEST_ASSERT_EQUAL(1, UnityFixture.Verbose);
STRCMP_EQUAL("gggg", UnityFixture.GroupFilter);
STRCMP_EQUAL("tttt", UnityFixture.NameFilter);
TEST_ASSERT_EQUAL(2, UnityFixture.RepeatCount);
}
static const char* unknownCommand[] = {
"testrunner.exe",
"-v",
"-g", "groupname",
"-n", "testname",
"-r", "98",
"-z"
};
TEST(UnityCommandOptions, UnknownCommandIsIgnored)
{
TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(9, unknownCommand));
TEST_ASSERT_EQUAL(1, UnityFixture.Verbose);
STRCMP_EQUAL("groupname", UnityFixture.GroupFilter);
STRCMP_EQUAL("testname", UnityFixture.NameFilter);
TEST_ASSERT_EQUAL(98, UnityFixture.RepeatCount);
}
TEST(UnityCommandOptions, GroupOrNameFilterWithoutStringFails)
{
TEST_ASSERT_EQUAL(1, UnityGetCommandLineOptions(3, unknownCommand));
TEST_ASSERT_EQUAL(1, UnityGetCommandLineOptions(5, unknownCommand));
TEST_ASSERT_EQUAL(1, UnityMain(3, unknownCommand, NULL));
}
TEST(UnityCommandOptions, GroupFilterReallyFilters)
{
UNITY_UINT saved = Unity.NumberOfTests;
TEST_ASSERT_EQUAL(0, UnityGetCommandLineOptions(4, unknownCommand));
UnityIgnoreTest(NULL, "non-matching", NULL);
TEST_ASSERT_EQUAL(saved, Unity.NumberOfTests);
}
IGNORE_TEST(UnityCommandOptions, TestShouldBeIgnored)
{
TEST_FAIL_MESSAGE("This test should not run!");
}

View File

@ -0,0 +1,32 @@
/* Copyright (c) 2010 James Grenning and Contributed to Unity Project
* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#include "unity_fixture.h"
TEST_GROUP_RUNNER(UnityFixture)
{
RUN_TEST_CASE(UnityFixture, PointerSetting);
RUN_TEST_CASE(UnityFixture, PointerSet);
RUN_TEST_CASE(UnityFixture, FreeNULLSafety);
RUN_TEST_CASE(UnityFixture, ConcludeTestIncrementsFailCount);
}
TEST_GROUP_RUNNER(UnityCommandOptions)
{
RUN_TEST_CASE(UnityCommandOptions, DefaultOptions);
RUN_TEST_CASE(UnityCommandOptions, OptionVerbose);
RUN_TEST_CASE(UnityCommandOptions, OptionSelectTestByGroup);
RUN_TEST_CASE(UnityCommandOptions, OptionSelectTestByName);
RUN_TEST_CASE(UnityCommandOptions, OptionSelectRepeatTestsDefaultCount);
RUN_TEST_CASE(UnityCommandOptions, OptionSelectRepeatTestsSpecificCount);
RUN_TEST_CASE(UnityCommandOptions, MultipleOptions);
RUN_TEST_CASE(UnityCommandOptions, MultipleOptionsDashRNotLastAndNoValueSpecified);
RUN_TEST_CASE(UnityCommandOptions, UnknownCommandIsIgnored);
RUN_TEST_CASE(UnityCommandOptions, GroupOrNameFilterWithoutStringFails);
RUN_TEST_CASE(UnityCommandOptions, GroupFilterReallyFilters);
RUN_TEST_CASE(UnityCommandOptions, TestShouldBeIgnored);
}

View File

@ -0,0 +1,49 @@
# Unity Memory
This Framework is an optional add-on to Unity. By including unity.h and then
unity_memory.h, you have the added ability to track malloc and free calls. This
addon requires that the stdlib functions be overridden by its own defines. These
defines will still malloc / realloc / free etc, but will also track the calls
in order to ensure that you don't have any memory leaks in your programs.
Note that this is only useful in situations where a unit is in charge of both
the allocation and deallocation of memory. When it is not symmetric, unit testing
can report a number of false failures. A more advanced runtime tool is required to
track complete system memory handling.
# Module API
## `UnityMalloc_StartTest` and `UnityMalloc_EndTest`
These must be called at the beginning and end of each test. For simplicity, they can
be added to `setUp` and `tearDown` in order to do their job. When using the test
runner generator scripts, these will be automatically added to the runner whenever
unity_memory.h is included.
## `UnityMalloc_MakeMallocFailAfterCount`
This can be called from the tests themselves. Passing this function a number will
force the reference counter to start keeping track of malloc calls. During that test,
if the number of malloc calls exceeds the number given, malloc will immediately
start returning `NULL`. This allows you to test error conditions. Think of it as a
simplified mock.
# Configuration
## `UNITY_MALLOC` and `UNITY_FREE`
By default, this module tries to use the real stdlib `malloc` and `free` internally.
If you would prefer it to use something else, like FreeRTOS's `pvPortMalloc` and
`pvPortFree`, then you can use these defines to make it so.
## `UNITY_EXCLUDE_STDLIB_MALLOC`
If you would like this library to ignore stdlib or other heap engines completely, and
manage the memory on its own, then define this. All memory will be handled internally
(and at likely lower overhead). Note that this is not a very featureful memory manager,
but is sufficient for most testing purposes.
## `UNITY_INTERNAL_HEAP_SIZE_BYTES`
When using the built-in memory manager (see `UNITY_EXCLUDE_STDLIB_MALLOC`) this define
allows you to set the heap size this library will use to manage the memory.

View File

@ -0,0 +1,202 @@
/* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#include "unity.h"
#include "unity_memory.h"
#include <string.h>
#define MALLOC_DONT_FAIL -1
static int malloc_count;
static int malloc_fail_countdown = MALLOC_DONT_FAIL;
void UnityMalloc_StartTest(void)
{
malloc_count = 0;
malloc_fail_countdown = MALLOC_DONT_FAIL;
}
void UnityMalloc_EndTest(void)
{
malloc_fail_countdown = MALLOC_DONT_FAIL;
if (malloc_count != 0)
{
UNITY_TEST_FAIL(Unity.CurrentTestLineNumber, "This test leaks!");
}
}
void UnityMalloc_MakeMallocFailAfterCount(int countdown)
{
malloc_fail_countdown = countdown;
}
/* These definitions are always included from unity_fixture_malloc_overrides.h */
/* We undef to use them or avoid conflict with <stdlib.h> per the C standard */
#undef malloc
#undef free
#undef calloc
#undef realloc
#ifdef UNITY_EXCLUDE_STDLIB_MALLOC
static unsigned char unity_heap[UNITY_INTERNAL_HEAP_SIZE_BYTES];
static size_t heap_index;
#else
#include <stdlib.h>
#endif
typedef struct GuardBytes
{
size_t size;
size_t guard_space;
} Guard;
#define UNITY_MALLOC_ALIGNMENT (UNITY_POINTER_WIDTH / 8)
static const char end[] = "END";
static size_t unity_size_round_up(size_t size)
{
size_t rounded_size;
rounded_size = ((size + UNITY_MALLOC_ALIGNMENT - 1) / UNITY_MALLOC_ALIGNMENT) * UNITY_MALLOC_ALIGNMENT;
return rounded_size;
}
void* unity_malloc(size_t size)
{
char* mem;
Guard* guard;
size_t total_size;
total_size = sizeof(Guard) + unity_size_round_up(size + sizeof(end));
if (malloc_fail_countdown != MALLOC_DONT_FAIL)
{
if (malloc_fail_countdown == 0)
return NULL;
malloc_fail_countdown--;
}
if (size == 0) return NULL;
#ifdef UNITY_EXCLUDE_STDLIB_MALLOC
if (heap_index + total_size > UNITY_INTERNAL_HEAP_SIZE_BYTES)
{
guard = NULL;
}
else
{
/* We know we can get away with this cast because we aligned memory already */
guard = (Guard*)(void*)(&unity_heap[heap_index]);
heap_index += total_size;
}
#else
guard = (Guard*)UNITY_MALLOC(total_size);
#endif
if (guard == NULL) return NULL;
malloc_count++;
guard->size = size;
guard->guard_space = 0;
mem = (char*)&(guard[1]);
memcpy(&mem[size], end, sizeof(end));
return (void*)mem;
}
static int isOverrun(void* mem)
{
Guard* guard = (Guard*)mem;
char* memAsChar = (char*)mem;
guard--;
return guard->guard_space != 0 || strcmp(&memAsChar[guard->size], end) != 0;
}
static void release_memory(void* mem)
{
Guard* guard = (Guard*)mem;
guard--;
malloc_count--;
#ifdef UNITY_EXCLUDE_STDLIB_MALLOC
{
size_t block_size;
block_size = unity_size_round_up(guard->size + sizeof(end));
if (mem == unity_heap + heap_index - block_size)
{
heap_index -= (sizeof(Guard) + block_size);
}
}
#else
UNITY_FREE(guard);
#endif
}
void unity_free(void* mem)
{
int overrun;
if (mem == NULL)
{
return;
}
overrun = isOverrun(mem);
release_memory(mem);
if (overrun)
{
UNITY_TEST_FAIL(Unity.CurrentTestLineNumber, "Buffer overrun detected during free()");
}
}
void* unity_calloc(size_t num, size_t size)
{
void* mem = unity_malloc(num * size);
if (mem == NULL) return NULL;
memset(mem, 0, num * size);
return mem;
}
void* unity_realloc(void* oldMem, size_t size)
{
Guard* guard = (Guard*)oldMem;
void* newMem;
if (oldMem == NULL) return unity_malloc(size);
guard--;
if (isOverrun(oldMem))
{
release_memory(oldMem);
UNITY_TEST_FAIL(Unity.CurrentTestLineNumber, "Buffer overrun detected during realloc()");
}
if (size == 0)
{
release_memory(oldMem);
return NULL;
}
if (guard->size >= size) return oldMem;
#ifdef UNITY_EXCLUDE_STDLIB_MALLOC /* Optimization if memory is expandable */
{
size_t old_total_size = unity_size_round_up(guard->size + sizeof(end));
if ((oldMem == unity_heap + heap_index - old_total_size) &&
((heap_index - old_total_size + unity_size_round_up(size + sizeof(end))) <= UNITY_INTERNAL_HEAP_SIZE_BYTES))
{
release_memory(oldMem); /* Not thread-safe, like unity_heap generally */
return unity_malloc(size); /* No memcpy since data is in place */
}
}
#endif
newMem = unity_malloc(size);
if (newMem == NULL) return NULL; /* Do not release old memory */
memcpy(newMem, oldMem, guard->size);
release_memory(oldMem);
return newMem;
}

View File

@ -0,0 +1,60 @@
/* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#ifndef UNITY_MEMORY_OVERRIDES_H_
#define UNITY_MEMORY_OVERRIDES_H_
#ifdef __cplusplus
extern "C"
{
#endif
#include <stddef.h>
#ifdef UNITY_EXCLUDE_STDLIB_MALLOC
/* Define this macro to remove the use of stdlib.h, malloc, and free.
* Many embedded systems do not have a heap or malloc/free by default.
* This internal unity_malloc() provides allocated memory deterministically from
* the end of an array only, unity_free() only releases from end-of-array,
* blocks are not coalesced, and memory not freed in LIFO order is stranded. */
#ifndef UNITY_INTERNAL_HEAP_SIZE_BYTES
#define UNITY_INTERNAL_HEAP_SIZE_BYTES 256
#endif
#endif
/* These functions are used by Unity to allocate and release memory
* on the heap and can be overridden with platform-specific implementations.
* For example, when using FreeRTOS UNITY_MALLOC becomes pvPortMalloc()
* and UNITY_FREE becomes vPortFree(). */
#if !defined(UNITY_MALLOC) || !defined(UNITY_FREE)
#include <stdlib.h>
#define UNITY_MALLOC(size) malloc(size)
#define UNITY_FREE(ptr) free(ptr)
#else
extern void* UNITY_MALLOC(size_t size);
extern void UNITY_FREE(void* ptr);
#endif
#define malloc unity_malloc
#define calloc unity_calloc
#define realloc unity_realloc
#define free unity_free
void* unity_malloc(size_t size);
void* unity_calloc(size_t num, size_t size);
void* unity_realloc(void * oldMem, size_t size);
void unity_free(void * mem);
/* You must compile with malloc replacement, as defined in unity_fixture_malloc_overrides.h */
void UnityMalloc_StartTest(void);
void UnityMalloc_EndTest(void);
void UnityMalloc_MakeMallocFailAfterCount(int countdown);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,78 @@
CC = gcc
ifeq ($(shell uname -s), Darwin)
CC = clang
endif
#DEBUG = -O0 -g
CFLAGS += -std=c99 -pedantic -Wall -Wextra -Werror
CFLAGS += $(DEBUG)
DEFINES = -D UNITY_OUTPUT_CHAR=UnityOutputCharSpy_OutputChar
ifeq ($(OS),Windows_NT)
DEFINES += -D UNITY_OUTPUT_CHAR_HEADER_DECLARATION=UnityOutputCharSpy_OutputChar(int)
else
DEFINES += -D UNITY_OUTPUT_CHAR_HEADER_DECLARATION=UnityOutputCharSpy_OutputChar\(int\)
endif
SRC = ../src/unity_memory.c \
../../../src/unity.c \
unity_memory_Test.c \
unity_memory_TestRunner.c \
unity_output_Spy.c \
INC_DIR = -I../src -I../../../src/
BUILD_DIR = ../build
TARGET = ../build/memory_tests.exe
all: default noStdlibMalloc 32bits
default: $(BUILD_DIR)
$(CC) $(CFLAGS) $(DEFINES) $(SRC) $(INC_DIR) -o $(TARGET) -D UNITY_SUPPORT_64
@ echo "default build"
./$(TARGET)
32bits: $(BUILD_DIR)
$(CC) $(CFLAGS) $(DEFINES) $(SRC) $(INC_DIR) -o $(TARGET) -m32
@ echo "32bits build"
./$(TARGET)
noStdlibMalloc: $(BUILD_DIR)
$(CC) $(CFLAGS) $(DEFINES) $(SRC) $(INC_DIR) -o $(TARGET) -D UNITY_EXCLUDE_STDLIB_MALLOC
@ echo "build with noStdlibMalloc"
./$(TARGET)
C89: CFLAGS += -D UNITY_EXCLUDE_STDINT_H # C89 did not have type 'long long', <stdint.h>
C89: $(BUILD_DIR)
$(CC) $(CFLAGS) $(DEFINES) $(SRC) $(INC_DIR) -o $(TARGET) -std=c89 && ./$(TARGET)
$(CC) $(CFLAGS) $(DEFINES) $(SRC) $(INC_DIR) -o $(TARGET) -D UNITY_EXCLUDE_STDLIB_MALLOC -std=c89
./$(TARGET)
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
clean:
rm -f $(TARGET) $(BUILD_DIR)/*.gc*
cov: $(BUILD_DIR)
cd $(BUILD_DIR) && \
$(CC) $(DEFINES) $(foreach i, $(SRC), ../test/$(i)) $(INC_DIR) -o $(TARGET) -fprofile-arcs -ftest-coverage
rm -f $(BUILD_DIR)/*.gcda
./$(TARGET) > /dev/null ; ./$(TARGET) -v > /dev/null
cd $(BUILD_DIR) && \
gcov unity_memory.c | head -3
grep '###' $(BUILD_DIR)/unity_memory.c.gcov -C2 || true # Show uncovered lines
# These extended flags DO get included before any target build runs
CFLAGS += -Wbad-function-cast
CFLAGS += -Wcast-qual
CFLAGS += -Wconversion
CFLAGS += -Wformat=2
CFLAGS += -Wmissing-prototypes
CFLAGS += -Wold-style-definition
CFLAGS += -Wpointer-arith
CFLAGS += -Wshadow
CFLAGS += -Wstrict-overflow=5
CFLAGS += -Wstrict-prototypes
CFLAGS += -Wswitch-default
CFLAGS += -Wundef
CFLAGS += -Wno-error=undef # Warning only, this should not stop the build
CFLAGS += -Wunreachable-code
CFLAGS += -Wunused
CFLAGS += -fstrict-aliasing

View File

@ -0,0 +1,325 @@
/* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#include "unity.h"
#include "unity_memory.h"
#include "unity_output_Spy.h"
#include <stdlib.h>
#include <string.h>
/* This test module includes the following tests: */
void test_ForceMallocFail(void);
void test_ReallocSmallerIsUnchanged(void);
void test_ReallocSameIsUnchanged(void);
void test_ReallocLargerNeeded(void);
void test_ReallocNullPointerIsLikeMalloc(void);
void test_ReallocSizeZeroFreesMemAndReturnsNullPointer(void);
void test_CallocFillsWithZero(void);
void test_FreeNULLSafety(void);
void test_DetectsLeak(void);
void test_BufferOverrunFoundDuringFree(void);
void test_BufferOverrunFoundDuringRealloc(void);
void test_BufferGuardWriteFoundDuringFree(void);
void test_BufferGuardWriteFoundDuringRealloc(void);
void test_MallocPastBufferFails(void);
void test_CallocPastBufferFails(void);
void test_MallocThenReallocGrowsMemoryInPlace(void);
void test_ReallocFailDoesNotFreeMem(void);
/* It makes use of the following features */
void setUp(void);
void tearDown(void);
/* Let's Go! */
void setUp(void)
{
#ifdef UNITY_EXCLUDE_STDLIB_MALLOC
UnityOutputCharSpy_Create(200);
#else
UnityOutputCharSpy_Create(1000);
#endif
UnityMalloc_StartTest();
}
void tearDown(void)
{
UnityMalloc_EndTest();
UnityOutputCharSpy_Destroy();
}
void test_ForceMallocFail(void)
{
void* m;
void* mfails;
UnityMalloc_MakeMallocFailAfterCount(1);
m = malloc(10);
TEST_ASSERT_NOT_NULL(m);
mfails = malloc(10);
TEST_ASSERT_EQUAL_PTR(0, mfails);
free(m);
}
void test_ReallocSmallerIsUnchanged(void)
{
void* m1 = malloc(10);
void* m2 = realloc(m1, 5);
TEST_ASSERT_NOT_NULL(m1);
TEST_ASSERT_EQUAL_PTR(m1, m2);
free(m2);
}
void test_ReallocSameIsUnchanged(void)
{
void* m1 = malloc(10);
void* m2 = realloc(m1, 10);
TEST_ASSERT_NOT_NULL(m1);
TEST_ASSERT_EQUAL_PTR(m1, m2);
free(m2);
}
void test_ReallocLargerNeeded(void)
{
void* m2;
void* m1 = malloc(10);
TEST_ASSERT_NOT_NULL(m1);
strcpy((char*)m1, "123456789");
m2 = realloc(m1, 15);
TEST_ASSERT_EQUAL_STRING("123456789", m2);
free(m2);
}
void test_ReallocNullPointerIsLikeMalloc(void)
{
void* m = realloc(0, 15);
TEST_ASSERT_NOT_NULL(m);
free(m);
}
void test_ReallocSizeZeroFreesMemAndReturnsNullPointer(void)
{
void* m1 = malloc(10);
void* m2 = realloc(m1, 0);
TEST_ASSERT_EQUAL_PTR(0, m2);
}
void test_CallocFillsWithZero(void)
{
void* m = calloc(3, sizeof(char));
char* s = (char*)m;
TEST_ASSERT_NOT_NULL(m);
TEST_ASSERT_EQUAL_HEX8(0, s[0]);
TEST_ASSERT_EQUAL_HEX8(0, s[1]);
TEST_ASSERT_EQUAL_HEX8(0, s[2]);
free(m);
}
void test_FreeNULLSafety(void)
{
free(NULL);
}
/*------------------------------------------------------------ */
#define EXPECT_ABORT_BEGIN \
{ \
jmp_buf TestAbortFrame; \
memcpy(TestAbortFrame, Unity.AbortFrame, sizeof(jmp_buf)); \
if (TEST_PROTECT()) \
{
#define EXPECT_ABORT_END \
} \
memcpy(Unity.AbortFrame, TestAbortFrame, sizeof(jmp_buf)); \
}
/* This tricky set of defines lets us see if we are using the Spy, returns 1 if true */
#ifdef __STDC_VERSION__
#ifdef UNITY_SUPPORT_VARIADIC_MACROS
#define USING_SPY_AS(a) EXPAND_AND_USE_2ND(ASSIGN_VALUE(a), 0)
#define ASSIGN_VALUE(a) VAL_##a
#define VAL_UnityOutputCharSpy_OutputChar 0, 1
#define EXPAND_AND_USE_2ND(a, b) SECOND_PARAM(a, b, throwaway)
#define SECOND_PARAM(a, b, ...) b
#if USING_SPY_AS(UNITY_OUTPUT_CHAR)
#define USING_OUTPUT_SPY /* UNITY_OUTPUT_CHAR = UnityOutputCharSpy_OutputChar */
#endif
#endif /* UNITY_SUPPORT_VARIADIC_MACROS */
#else /* __STDC_VERSION__ else */
#define UnityOutputCharSpy_OutputChar 42
#if UNITY_OUTPUT_CHAR == UnityOutputCharSpy_OutputChar /* Works if no -Wundef -Werror */
#define USING_OUTPUT_SPY
#endif
#undef UnityOutputCharSpy_OutputChar
#endif /* __STDC_VERSION__ */
void test_DetectsLeak(void)
{
#ifdef USING_OUTPUT_SPY
void* m = malloc(10);
TEST_ASSERT_NOT_NULL(m);
UnityOutputCharSpy_Enable(1);
EXPECT_ABORT_BEGIN
UnityMalloc_EndTest();
EXPECT_ABORT_END
UnityOutputCharSpy_Enable(0);
Unity.CurrentTestFailed = 0;
TEST_ASSERT_NOT_NULL(strstr(UnityOutputCharSpy_Get(), "This test leaks!"));
free(m);
#else
TEST_IGNORE_MESSAGE("Enable USING_OUTPUT_SPY To Run This Test");
#endif
}
void test_BufferOverrunFoundDuringFree(void)
{
#ifdef USING_OUTPUT_SPY
void* m = malloc(10);
char* s = (char*)m;
TEST_ASSERT_NOT_NULL(m);
s[10] = (char)0xFF;
UnityOutputCharSpy_Enable(1);
EXPECT_ABORT_BEGIN
free(m);
EXPECT_ABORT_END
UnityOutputCharSpy_Enable(0);
Unity.CurrentTestFailed = 0;
TEST_ASSERT_NOT_NULL(strstr(UnityOutputCharSpy_Get(), "Buffer overrun detected during free()"));
#else
TEST_IGNORE_MESSAGE("Enable USING_OUTPUT_SPY To Run This Test");
#endif
}
void test_BufferOverrunFoundDuringRealloc(void)
{
#ifdef USING_OUTPUT_SPY
void* m = malloc(10);
char* s = (char*)m;
TEST_ASSERT_NOT_NULL(m);
s[10] = (char)0xFF;
UnityOutputCharSpy_Enable(1);
EXPECT_ABORT_BEGIN
m = realloc(m, 100);
EXPECT_ABORT_END
UnityOutputCharSpy_Enable(0);
Unity.CurrentTestFailed = 0;
TEST_ASSERT_NOT_NULL(strstr(UnityOutputCharSpy_Get(), "Buffer overrun detected during realloc()"));
#else
TEST_IGNORE_MESSAGE("Enable USING_OUTPUT_SPY To Run This Test");
#endif
}
void test_BufferGuardWriteFoundDuringFree(void)
{
#ifdef USING_OUTPUT_SPY
void* m = malloc(10);
char* s = (char*)m;
TEST_ASSERT_NOT_NULL(m);
s[-1] = (char)0x00; /* Will not detect 0 */
s[-2] = (char)0x01;
UnityOutputCharSpy_Enable(1);
EXPECT_ABORT_BEGIN
free(m);
EXPECT_ABORT_END
UnityOutputCharSpy_Enable(0);
Unity.CurrentTestFailed = 0;
TEST_ASSERT_NOT_NULL(strstr(UnityOutputCharSpy_Get(), "Buffer overrun detected during free()"));
#else
TEST_IGNORE_MESSAGE("Enable USING_OUTPUT_SPY To Run This Test");
#endif
}
void test_BufferGuardWriteFoundDuringRealloc(void)
{
#ifdef USING_OUTPUT_SPY
void* m = malloc(10);
char* s = (char*)m;
TEST_ASSERT_NOT_NULL(m);
s[-1] = (char)0x0A;
UnityOutputCharSpy_Enable(1);
EXPECT_ABORT_BEGIN
m = realloc(m, 100);
EXPECT_ABORT_END
UnityOutputCharSpy_Enable(0);
Unity.CurrentTestFailed = 0;
TEST_ASSERT_NOT_NULL(strstr(UnityOutputCharSpy_Get(), "Buffer overrun detected during realloc()"));
#else
TEST_IGNORE_MESSAGE("Enable USING_OUTPUT_SPY To Run This Test");
#endif
}
/*------------------------------------------------------------ */
#define TEST_ASSERT_MEMORY_ALL_FREE_LIFO_ORDER(first_mem_ptr, ptr) \
ptr = malloc(10); free(ptr); \
TEST_ASSERT_EQUAL_PTR_MESSAGE(first_mem_ptr, ptr, "Memory was stranded, free in LIFO order");
void test_MallocPastBufferFails(void)
{
#ifdef UNITY_EXCLUDE_STDLIB_MALLOC
void* m = malloc(UNITY_INTERNAL_HEAP_SIZE_BYTES/2 + 1);
void* n = malloc(UNITY_INTERNAL_HEAP_SIZE_BYTES/2);
free(m);
TEST_ASSERT_NOT_NULL(m);
TEST_ASSERT_NULL(n);
TEST_ASSERT_MEMORY_ALL_FREE_LIFO_ORDER(m, n);
#else
TEST_IGNORE_MESSAGE("Enable UNITY_EXCLUDE_STDLIB_MALLOC to Run This Test");
#endif
}
void test_CallocPastBufferFails(void)
{
#ifdef UNITY_EXCLUDE_STDLIB_MALLOC
void* m = calloc(1, UNITY_INTERNAL_HEAP_SIZE_BYTES/2 + 1);
void* n = calloc(1, UNITY_INTERNAL_HEAP_SIZE_BYTES/2);
free(m);
TEST_ASSERT_NOT_NULL(m);
TEST_ASSERT_NULL(n);
TEST_ASSERT_MEMORY_ALL_FREE_LIFO_ORDER(m, n);
#else
TEST_IGNORE_MESSAGE("Enable UNITY_EXCLUDE_STDLIB_MALLOC to Run This Test");
#endif
}
void test_MallocThenReallocGrowsMemoryInPlace(void)
{
#ifdef UNITY_EXCLUDE_STDLIB_MALLOC
void* m = malloc(UNITY_INTERNAL_HEAP_SIZE_BYTES/2 + 1);
void* n = realloc(m, UNITY_INTERNAL_HEAP_SIZE_BYTES/2 + 9);
free(n);
TEST_ASSERT_NOT_NULL(m);
TEST_ASSERT_EQUAL(m, n);
TEST_ASSERT_MEMORY_ALL_FREE_LIFO_ORDER(m, n);
#else
TEST_IGNORE_MESSAGE("Enable UNITY_EXCLUDE_STDLIB_MALLOC to Run This Test");
#endif
}
void test_ReallocFailDoesNotFreeMem(void)
{
#ifdef UNITY_EXCLUDE_STDLIB_MALLOC
void* m = malloc(UNITY_INTERNAL_HEAP_SIZE_BYTES/2);
void* n1 = malloc(10);
void* out_of_mem = realloc(n1, UNITY_INTERNAL_HEAP_SIZE_BYTES/2 + 1);
void* n2 = malloc(10);
free(n2);
if (out_of_mem == NULL) free(n1);
free(m);
TEST_ASSERT_NOT_NULL(m); /* Got a real memory location */
TEST_ASSERT_NULL(out_of_mem); /* The realloc should have failed */
TEST_ASSERT_NOT_EQUAL(n2, n1); /* If n1 != n2 then realloc did not free n1 */
TEST_ASSERT_MEMORY_ALL_FREE_LIFO_ORDER(m, n2);
#else
TEST_IGNORE_MESSAGE("Enable UNITY_EXCLUDE_STDLIB_MALLOC to Run This Test");
#endif
}

View File

@ -0,0 +1,49 @@
/* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#include "unity.h"
#include "unity_memory.h"
extern void test_ForceMallocFail(void);
extern void test_ReallocSmallerIsUnchanged(void);
extern void test_ReallocSameIsUnchanged(void);
extern void test_ReallocLargerNeeded(void);
extern void test_ReallocNullPointerIsLikeMalloc(void);
extern void test_ReallocSizeZeroFreesMemAndReturnsNullPointer(void);
extern void test_CallocFillsWithZero(void);
extern void test_FreeNULLSafety(void);
extern void test_DetectsLeak(void);
extern void test_BufferOverrunFoundDuringFree(void);
extern void test_BufferOverrunFoundDuringRealloc(void);
extern void test_BufferGuardWriteFoundDuringFree(void);
extern void test_BufferGuardWriteFoundDuringRealloc(void);
extern void test_MallocPastBufferFails(void);
extern void test_CallocPastBufferFails(void);
extern void test_MallocThenReallocGrowsMemoryInPlace(void);
extern void test_ReallocFailDoesNotFreeMem(void);
int main(void)
{
UnityBegin("unity_memory_Test.c");
RUN_TEST(test_ForceMallocFail);
RUN_TEST(test_ReallocSmallerIsUnchanged);
RUN_TEST(test_ReallocSameIsUnchanged);
RUN_TEST(test_ReallocLargerNeeded);
RUN_TEST(test_ReallocNullPointerIsLikeMalloc);
RUN_TEST(test_ReallocSizeZeroFreesMemAndReturnsNullPointer);
RUN_TEST(test_CallocFillsWithZero);
RUN_TEST(test_FreeNULLSafety);
RUN_TEST(test_DetectsLeak);
RUN_TEST(test_BufferOverrunFoundDuringFree);
RUN_TEST(test_BufferOverrunFoundDuringRealloc);
RUN_TEST(test_BufferGuardWriteFoundDuringFree);
RUN_TEST(test_BufferGuardWriteFoundDuringRealloc);
RUN_TEST(test_MallocPastBufferFails);
RUN_TEST(test_CallocPastBufferFails);
RUN_TEST(test_MallocThenReallocGrowsMemoryInPlace);
RUN_TEST(test_ReallocFailDoesNotFreeMem);
return UnityEnd();
}

View File

@ -0,0 +1,56 @@
/* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#include "unity.h"
#include "unity_output_Spy.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static int size;
static int count;
static char* buffer;
static int spy_enable;
void UnityOutputCharSpy_Create(int s)
{
size = (s > 0) ? s : 0;
count = 0;
spy_enable = 0;
buffer = malloc((size_t)size);
TEST_ASSERT_NOT_NULL_MESSAGE(buffer, "Internal malloc failed in Spy Create():" __FILE__);
memset(buffer, 0, (size_t)size);
}
void UnityOutputCharSpy_Destroy(void)
{
size = 0;
free(buffer);
}
void UnityOutputCharSpy_OutputChar(int c)
{
if (spy_enable)
{
if (count < (size-1))
buffer[count++] = (char)c;
}
else
{
putchar(c);
}
}
const char * UnityOutputCharSpy_Get(void)
{
return buffer;
}
void UnityOutputCharSpy_Enable(int enable)
{
spy_enable = enable;
}

View File

@ -0,0 +1,16 @@
/* ==========================================
* Unity Project - A Test Framework for C
* Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
* [Released under MIT License. Please refer to license.txt for details]
* ========================================== */
#ifndef UNITY_OUTPUT_SPY_H
#define UNITY_OUTPUT_SPY_H
void UnityOutputCharSpy_Create(int s);
void UnityOutputCharSpy_Destroy(void);
void UnityOutputCharSpy_OutputChar(int c);
const char * UnityOutputCharSpy_Get(void);
void UnityOutputCharSpy_Enable(int enable);
#endif