libfsafe
0.1.1
eases writing fail-safe code (C++)
|
Usually, all you need is macros. The following ones exist:
The unit tests serve as compilable and runnable documentation and examples.
Heres the one that is intended as a short tutorial:
tests/Example.cxx
#include <tests/Example.hxx> #include <libsex/Exception.hxx> #include <libfsafe/checkpoint.hxx> #include <libfsafe/assert.hxx> #include <sstream> // main() is the entry point -- both for our example // "application" and this unit test. void tests::Example::main() { std::stringstream cout; try { // Real work starts now. initialize(); run(); cleanup(); // Real work finished. } catch (libsex::Exception& e) { e.backtrace(cout); } std::string exp = __FILE__ ":54: In 'c = calculate(a)':\n" __FILE__ ":64: Precondition 'ptr[1] < 42' violated."; CPPUNIT_ASSERT_EQUAL(exp, cout.str()); } void tests::Example::initialize() { // Some boring initialization stuff. } void tests::Example::cleanup() { // Boring cleanup here. } void tests::Example::run() { // The really important part of our code. int a[2]; a[0] = 41; a[1] = 42; // Note that we can't declare c in CHECKPOINT // because it would be wrapped in try-catch. int c; CHECKPOINT(c = calculate(a)); // Now do something with c. (void) c; } int tests::Example::calculate(int* ptr) { ASSERT_PRE(ptr != NULL); ASSERT_PRE(ptr[0] < 42); ASSERT_PRE(ptr[1] < 42); int result = ptr[0] + ptr[1]; ASSERT_POST(result <= 82); return result; }