Tag Archives: c++

C++ Pragmatics: Testing (Part 2, Mechanics)

Jelly fish

There are many tools for testing, and there are different kinds of testing at different granularities, for different phases of the development cycle.

For tests of the largest granularity, such as acceptance tests, the tools and methods are usually language neutral. For example, you can test a Ruby web application using webrat or watir, and you can use the same set of tools to test a C++ web server. In this section, I’m just going to focus on small tests, in particular, tests of individual methods and classes.

There are a number of test frameworks for C++. Boost has a test library, Qt has a unit test library, and Google also open-sourced its C++ testing framework. There are a few others. You could write tests without any of them, but the tools help to reduce repetition and make tests more concise. In my experience this is quite important, because the easier it is to write tests, the more motivated I am to write them.

The testing frameworks all use similar terminology. Usually a test source file contains one or more test cases, and a test case contains one or more tests. It’s customary to write one test case for each class, and one or more tests for each public method. Most of those tools are similar, and it doesn’t really matter which one you use. I like Google’s framework because it’s the least verbose and it’s also what I use at work. Here’s a quick example of one test in a test case for an RSS feed parser:

class FeedParserTest: public ::testing::Test {
  protected:
    void SetUp() {
        feed_.reset(new Feed);
    }

    RssFeedParser parser_;
    shared_ptr<Feed> feed_;
};

TEST_F(FeedParserTest, ParseSlashdot) {
    QFile rss(TEST_DATA_DIR "/slashdot.rss");
    ASSERT_TRUE(rss.exists());
    rss.open(QIODevice::ReadOnly);
    parser_.startNewFeed(feed_);
    while (rss.bytesAvailable() > 0) {
        parser_.append(rss.read(CHUNK_SIZE));
    }
    EXPECT_TRUE(parser_.finished());
    EXPECT_EQ("Slashdot", parser_.feed()->title());
    EXPECT_EQ("http://slashdot.org/", parser_.feed()->site_url());
}

Each test class inherit from testing::Test, and there are two virtual functions you could override to set up and tear down your test fixture. void SetUp() and void TearDown() are called before and after each test respectively. You can also define two static class functions static void SetUpTestCase() and static void TearDown() which are called before and after all tests in the test case respectively. In other words, they are only called once for the test case. Ideally, you should implement the test fixture in SetUp() and TearDown(), because you don’t want to introduce dependencies between the tests. For example, you don’t want to be in a situation where just rearranging the order of tests would break them. SetUpTestCase() and TearDownTestCase() are mainly used for expensive initialization such as reading large amounts of data from disk, which you don’t want to do for every single test.

The TEST_F() macro defines a test with fixture, which has access to the test class defined earlier. There is also a TEST() macro that defines a test without fixture which is essentially just a simple function. The framework provides two families of assertions that you can use in tests. The ASSERT_* family of assertions immediately abort the current test if the expected condition is not true. They are usually used when it doesn’t make sense to continue the test, for example, where there is a NULL pointer that you need to dereference later, or some critical data is missing. The EXPECT_* family of assertions cause the test fail if the condition does not hold, but they allow the test to continue, so that you can find all failing expectations in one run.

There is no need to write a main() function. The testing framework provides a standard main() that you can link with, which runs all all defined tests. The resulting test executable has a few command line options that you can use to filter tests or change output formats. Just run your test executable with the --help flag to see all available options.

(To be continued …)

C++ Pragmatics: Testing (Part 1)

Tree @ Reyes Point

The first time that I truly appreciated the benefit of automated software testing was when I served as the teaching assistant for CS323 at Yale University, taught by Professor Stanley Eisenstat. If you have read Joel on Software, either the book or the blog, you would have heard of Stan and CS323@Yale a few times.

The title of the course was Introduction to Systems Programming and Computer Organization. The student were taught computer systems, UNIX C programming, and some PERL. To quote Dan Andrei Iancu (from his homepage):

The turning point for many wannabe CS majors at Yale, Professor Eisenstat’s class can easily turn into a marathon of sleepless nights and endless frustration… However, the survivors can claim to have coded (among other things) a fully functional C shell, a Perl server, and an LZW compressor.

The students turned in their assignments by placing the source code under a specific path under their home directories on NFS. Stan gave me a sheet of very specific programming style criteria complete with how much weight to assign to each of the 25 or so items. I would read each solution and grade it for style — and for style only, because there is no way to reliably judge the correctness of a program just by reading it.

To check correctness, I wrote acceptance tests for the assignments. For each assignment, I had a PERL script to compile the students’ solutions and then ran them with STDIN and STDOUT redirected to my script with UNIX pipes. The script then went through each test case, feeding specified input and checking if the output was expected. Stan let me design the final project, which turned out to be a good exercise for writing requirements specification. I asked the students to design an old-school multi-user BBS system. The users would login with a Telnet client and can read, post, and reply with commands. I thought It would be a good practice for multi-threaded programming. Some of the programs turned in by students were quite impressive. I tested all solutions in a similar way, using a PERL script to simulate multiple users in the system and test various functionalities.

Interestingly, the students’ programs also served as tests for my scripts. I usually did the assignment myself and made sure my grading script could properly run my solutions and correctly parse the output, but it is hard to make sure that the script was robust enough to telerate minor differences. Sadly, I was not able to pass all the tests. One student wrote her solutions in Microsoft Word. Of course my script was never ready to parse .doc files. Talk about unexpected user behavior!

Enough history. I will start writing the technical content next time.

To be continued…

JSON++: A JSON parser for C++

I wrote a very simple JSON parser in C++ a while ago. It’s just a pair of header and source files, thus very easy to use (compile the .cc file and link with your source). Check it out here.

Here are a few examples:

string teststr(
        "{" 
        "  \"foo\" : 1," 
        "  \"bar\" : false," 
        "  \"person\" : {\"name\" : \"GWB\", \"age\" : 60}," 
        "  \"data\": [\"abcd\", 42]" 
        "}" 
               );
istringstream input(teststr);
Object o;
assert(o.parse(input));
assert(1 == o.get<long>("foo"));
assert(o.has<bool>("bar"));
assert(o.has<Object>("person"));
assert(o.get<Object>("person").has<long>("age"));
assert(o.has<Array>("data"));
assert(o.get<Array>("data").get<long>(1) == 42);
assert(o.get<Array>("data").get<string>(0) == "abcd");
assert(!o.has<long>("data"));

Caveat: It currently does not support floating-point numbers.

LINQ++: An embeded DSL for C++

LINQ have been the new hotness in Microsoft’s .Net platform. Well, you can have the same syntactic sugar in C++ without writing a new compiler. I wrote a small library (just a short header file right now) that can do some interesting things. (source available at github) The following snippets from the companion unit test shows a few:

// Count the number of people older than 30
cout << from(guests)
        .where(&_1 ->* &Person::age > 30)
        .count()

// combine the people older than 30 with the person with name
// "joe" into one table.
DataSet<vector<Person> > results =
        insert(
                from(guests)
                .where(&_1 ->* &Person::age > 30))
        .into(
                from(guests)
                .where(&_1 ->* &Person::name == "joe"));

// select the age column from the previous table.
shared_ptr<vector<int> > ages = results
                                .select<int>(&_1 ->* &Person::age)
                                .get();

It should work with all STL-compatible sequence containers and requires the boost library. You can chain the clauses to form complicated queries.

I wrote it up on the shuttle from work to home. Hopefully I can find some time to polish it up and make it actually useful.