added support for comparing doubles

This commit is contained in:
Shaden Smith 2015-08-11 12:03:50 -05:00 committed by Bas van den Berg
parent 5ea9f2dbf4
commit a1d99cc932
3 changed files with 53 additions and 0 deletions

View File

@ -26,6 +26,11 @@ CTEST(suite, test1) {
CTEST(suite, test2) {
ASSERT_EQUAL(1, 2);
}
CTEST(suite, test_dbl) {
ASSERT_DBL_NEAR(0.0001, 0.00011);
ASSERT_DBL_NEAR_TOL(0.0001, 0.00011, 1e-5);
}
```
NO further typing is needed! ctest does the rest.

32
ctest.h
View File

@ -123,6 +123,14 @@ void assert_false(int real, const char* caller, int line);
void assert_fail(const char* caller, int line);
#define ASSERT_FAIL() assert_fail(__FILE__, __LINE__)
void assert_dbl_near(double exp, double real, double tol, const char* caller, int line);
#define ASSERT_DBL_NEAR(exp, real) assert_dbl_near(exp, real, 1e-4, __FILE__, __LINE__)
#define ASSERT_DBL_NEAR_TOL(exp, real, tol) assert_dbl_near(exp, real, tol, __FILE__, __LINE__)
void assert_dbl_far(double exp, double real, double tol, const char* caller, int line);
#define ASSERT_DBL_FAR(exp, real) assert_dbl_far(exp, real, 1e-4, __FILE__, __LINE__)
#define ASSERT_DBL_FAR_TOL(exp, real, tol) assert_dbl_far(exp, real, tol, __FILE__, __LINE__)
#ifdef CTEST_MAIN
#include <setjmp.h>
@ -259,6 +267,30 @@ void assert_not_equal(long exp, long real, const char* caller, int line) {
}
}
void assert_dbl_near(double exp, double real, double tol, const char* caller, int line) {
double diff = exp - real;
double absdiff = diff;
/* avoid using fabs and linking with a math lib */
if(diff < 0) {
absdiff *= -1;
}
if (absdiff > tol) {
CTEST_ERR("%s:%d expected %0.3e, got %0.3e (diff %0.3e, tol %0.3e)", caller, line, exp, real, diff, tol);
}
}
void assert_dbl_far(double exp, double real, double tol, const char* caller, int line) {
double diff = exp - real;
double absdiff = diff;
/* avoid using fabs and linking with a math lib */
if(diff < 0) {
absdiff *= -1;
}
if (absdiff <= tol) {
CTEST_ERR("%s:%d expected %0.3e, got %0.3e (diff %0.3e, tol %0.3e)", caller, line, exp, real, diff, tol);
}
}
void assert_null(void* real, const char* caller, int line) {
if ((real) != NULL) {
CTEST_ERR("%s:%d should be NULL", caller, line);

View File

@ -169,3 +169,19 @@ CTEST(ctest, test_ctest_err) {
CTEST_ERR("error log");
}
CTEST(ctest, test_dbl_near) {
double a = 0.000111;
ASSERT_DBL_NEAR(0.0001, a);
}
CTEST(ctest, test_dbl_near_tol) {
double a = 0.000111;
ASSERT_DBL_NEAR_TOL(0.0001, a, 1e-5); /* will fail */
}
CTEST(ctest, test_dbl_far) {
double a = 1.1;
ASSERT_DBL_FAR(1., a);
ASSERT_DBL_FAR_TOL(1., a, 0.01);
}