From 244dcf9408c6d6721528c015a148fa733eec4d15 Mon Sep 17 00:00:00 2001 From: "Michael D. Lowis" Date: Tue, 21 Feb 2017 17:20:20 -0500 Subject: [PATCH] added mocked out exit function for testing of exit codes without terminating the test process --- Makefile | 3 +++ atf.h | 23 ++++++++++++++++++++++- tests.c | 10 ++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 619de45..febe4e2 100644 --- a/Makefile +++ b/Makefile @@ -5,6 +5,9 @@ DISTGZ = ${DISTTAR}.gz DISTFILES = atf.h LICENSE.md Makefile README.md tests.c tests: tests.c + @echo "============================================" + @echo "NOTE: It is expected that 3 tests will fail." + @echo "============================================" $(CC) -I. -o $@ $^ -./$@ diff --git a/atf.h b/atf.h index b6b5fbb..a486e79 100755 --- a/atf.h +++ b/atf.h @@ -22,6 +22,8 @@ #include #include +#include +#include extern char* Curr_Test; void atf_init(int argc, char** argv); @@ -35,6 +37,9 @@ int atf_print_results(void); #define CHECK(expr) \ if(atf_test_assert((expr), #expr, __FILE__, __LINE__)) break + +#define CHECK_EXITCODE(code) \ + CHECK(ExitCode == code) #define TEST_SUITE(name) \ void name(void) @@ -50,6 +55,9 @@ int atf_print_results(void); #define PRINT_TEST_RESULTS \ atf_print_results + +#define EXPECT_EXIT \ + if ((ExitExpected = true, 0 == setjmp(ExitPad))) /* Function Definitions *****************************************************************************/ @@ -65,6 +73,9 @@ char* Curr_File = NULL; unsigned int Curr_Line = 0; static unsigned int Total = 0; static unsigned int Failed = 0; +bool ExitExpected; +int ExitCode; +jmp_buf ExitPad; #ifndef NO_SIGNALS static void handle_signal(int sig) { @@ -86,7 +97,7 @@ static void handle_signal(int sig) { fprintf(stderr,"%s:%d:0:%s:CRASH (signal: %d - %s)\n", Curr_File, Curr_Line, Curr_Test, sig, sig_name); Failed++; (void)atf_print_results(); - exit(1); + _Exit(1); } #endif @@ -136,6 +147,16 @@ int atf_print_results(void) { return Failed; } +void exit(int code) { + if (ExitExpected) { + ExitCode = code; + ExitExpected = false; + longjmp(ExitPad, 1); + } else { + assert(!"Unexpected exit. Something went wrong"); + } +} + #undef INCLUDE_DEFS #endif diff --git a/tests.c b/tests.c index ce0efab..dc18c50 100644 --- a/tests.c +++ b/tests.c @@ -24,6 +24,16 @@ int main(int argc, char** argv) { } TEST_SUITE(External_Suite) { + TEST(CHECK_EXITCODE should pass if exit called with correct code) { + EXPECT_EXIT { exit(42); } + CHECK_EXITCODE(42); + } + + TEST(CHECK_EXITCODE should fail if exit called with incorrect code) { + EXPECT_EXIT { exit(42); } + CHECK_EXITCODE(41); + } + TEST(Should_handle_SIGABRT) { raise(SIGABRT); } -- 2.51.0