I have started using CATCH for testing for all new projects of mine. However, I have problems using CATCH and Google Logging library - glog.
Apart from logging, the glog library provides useful assertion-like macros:
DCHECK, DCHECK_EQ, DCHECK_LT, ... which are compile out with -DNDEBUG, otherwise they are equivalent to:
CHECK, CHECK_EQ, CHECK_LT, ... which crash the program and print a nice message:
For example,
int x = 10; int y = 5;
CHECK_EQ(1, 2);
will cause the program to print this:
F1015 15:03:48.362149 391 t.cpp:12] Check failed: x == y (10 vs. 5)
I use these a lot for pre and post condition checking.
As you may have guessed, including both glog and CATCH headers into one translation unit (.cpp file) doesn't work. The reason is that CHECK and possibly other macros are being defined differently in both headers.
I really want to keep using the CHECK/DCHECK for post/pre condition checking. So, I am looking for ways to make these things work.
Has anyone had the same problem? If so, can you share the direction you took for resolving the problem?
My current idea is to disable CHECK/DCHECK macros in glog, and then make my own based equivalents of CHECK/DCHECK macros based CATCH excellent decomposition of operations into lhs/rhs parts.
I suppose it shouldn't be difficult. As a bonus in usability, I'd awesome to make a single CHECK macro having different meanings when compiled as a part of test case, and when used for deployment. For example,
//// header.hpp
#include <algorithm>
#include "catch.hpp"
template <typename Iter>
void is_sorted_non_empty(Iter first, Iter last){
CHECK(std::distance(first, last) > 0);
return std::is_sorted(first, last);
}
//// test.cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "header.hpp"
#include <vector>
TEST_CASE( "Factorials are computed", "[factorial]" ) {
std::vector v{1,2,3};
CHECK( is_sorted_non_empty(v.begin(), v.begin()) ); // the CHECK inside is_sorted_non_empty should fail
CHECK( is_sorted_non_empty(v.begin(), v.end()) ); // no problem
}
//// prod.cpp
#include "header.hpp"
#include <vector>
#include <iostream>
int main(){
std::vector v{1,2,3};
std::cout << "sorted? " << is_sorted_non_empty(v.begin(), v.end()) << std::endl;
std::cout << "this will crash " << is_sorted_non_empty(v.begin(), v.begin()) << std::endl;
}
Won't this be awesome?
Regards,
Andrii