I want to try versatile Criterion testing library. We have three files test.c and add.c and add.h . Compile with:
Code:
clang -lcriterion -Wall -Wextra -pedantic -std=c11 test.c add.c -o add
First begin by writing some tests:
test.c
Code:
#include <criterion/criterion.h>
#include <criterion/new/assert.h>
#include <limits.h>
#include "add.h"
TestSuite(suite1);
Test(suite1, low)
{
int r1 = add(0, 0);
cr_expect_eq(r1, 0);
int r2 = add(0, 1);
cr_expect_eq(r2, 1);
int r3 = add(-1, 1);
cr_expect_eq(r3, 0);
}
Test(suite1, random)
{
int r1 = add(1429, 15317);
cr_expect_eq(r1, 16746);
int r2 = add(4760214, 8989342);
cr_expect_eq(r2, 13749556);
}
Test(suite1, high)
{
int r3 = add(INT_MAX, INT_MAX);
cr_expect_eq(r3, 2 * INT_MAX);
}
add.c
Code:
#include "add.h"
int add(int x, int y)
{
return -1000;
}
Good news is , all the tests are failing:
Code:
[----] test.c:32: Assertion Failed
[----]
[----] The expression (r3) == (2 * 2147483647) is false.
[----]
[----] test.c:11: Assertion Failed
[----]
[----] The expression (r1) == (0) is false.
[----]
[----] test.c:14: Assertion Failed
[----]
[----] The expression (r2) == (1) is false.
[----]
[FAIL] suite1::high: (0.00s)
[----] test.c:17: Assertion Failed
[----]
[----] The expression (r3) == (0) is false.
[----]
[----] test.c:23: Assertion Failed
[----]
[----] The expression (r1) == (16746) is false.
[----]
[----] test.c:26: Assertion Failed
[----]
[----] The expression (r2) == (13749556) is false.
[----]
[FAIL] suite1::low: (0.00s)
[FAIL] suite1::random: (0.00s)
[====] Synthesis: Tested: 3 | Passing: 0 | Failing: 3 | Crashing: 0
Now try to pass the tests by writing better add function:
add.c
Code:
#include "add.h"
int add(int x, int y)
{
int r = x + y;
return r;
}
Results:
Code:
[====] Synthesis: Tested: 3 | Passing: 3 | Failing: 0 | Crashing: 0
There seems to be a warning from compiler:
Code:
test.c:32:24: warning: overflow in expression; result is -2 with type 'int' [-Winteger-overflow]
You may try:
add.c
Code:
#include <stdint.h>
#include "add.h"
int64_t add(int32_t x, int32_t y)
{
int64_t r = x + y;
return r;
}
And modify rest of the code accordingly.