Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

C/C++

Bulletproofing C++ Code


Step 3: Develop Unit and Regression Tests

Once you begin writing code or fixing issues in existing code, there's no excuse for neglecting to properly test the code you wrote, even if the rest of the code lacks such diligently created test cases. This is the time to apply Test Driven Development (TDD) or any other technique that keeps test cases at the front of—or at least tightly linked to—the development process.

Depending on the nature of the code change, functional-level (application-level) regression tests and/or unit-level regression tests may be appropriate. Each has its own benefits. The functional-level tests are preferred in cases when tests can feasibly be set up to represent a high-level requirement to implement—or a specific bug that should be addressed—and the tested program can produce sufficient output to effectively validate the code's behavior (via the direct outputs it generates, log messages, debug messages, and the like). Unit tests are appropriate when test setup is complicated because the error condition itself is not a common scenario, when the changed code is buried deep in the module hierarchy, or when it's difficult to validate the test outcome at the functional level (that is, the program lacks debugging facilities). This is frequently the case with corner-case conditions or error-handling functions. These are supposed to trigger in exceptional circumstances, which would be difficult to set up in a test harness.

For example, take a real-life problem discovered in the file-processing utility in Listing Two. One of the functions of this file utility is "normalization" of the file path. If the file foo.c is said to be in directory /a/b/c/../d, the utility transforms this into /a/b/d/foo.c. However, when a directory path starts with .. (dot dot), this part of the path is discarded as a result of the code annotated with the comment // BUG; thus ../../a/b/c is transformed into /a/b/c. Listing Three eliminates this problem.

void Path::normalize(PathInfo& input) 
{ 
  PathElements result; 
  PathElements::const_iterator it =            input.elements.begin(); 
  PathElements::const_iterator end =            input.elements.end(); 
  for (; it != end; ++it) { 
      if (*it == "..") { 
          if (result.empty()) {   // BUG
              result.push_back(*it); 
          } else { 
              result.pop_back(); 
          } 
      } else if (*it != ".") { 
          result.push_back(*it); 
      } 
  } 
  input.elements.swap(result); 
} 
Listing Two

void Path::normalize(PathInfo& input) 
  PathElements result; 
  PathElements::const_iterator it  =            input.elements.begin(); 
  PathElements::const_iterator end =            input.elements.end(); 
  for (; it != end; ++it) { 
     if (*it == "..") { 
       if (result.empty() 
          || result.back() == "..") { // BUG fixed
            result.push_back(*it); 
       } else { 
            result.pop_back(); 
       } 
     } else if (*it != ".") { 
        result.push_back(*it); 
    } 
  } 
  input.elements.swap(result); 
}
Listing Three

Additionally, tests have to be created to verify the fix. When considering tests to validate the fix, the choice of tests is influenced by the fact that this function is part of a common library, and both the defect and fix are completely contained within the function. Rather than create a functional test for the file utility, it's actually easier to create a unit test for the fix using an appropriately crafted string for a file path:

void PathTest::testGetNormalized() 
{ 
  Path test
      ("../../a/../b/c/./d/../e"); 
  Path result = 
      test.getNormalized(); 
  CPPTEST_ASSERT_CSTR_EQUAL
      ("../../b/c/e", 
    prepareNormalizedPathString
      (result.toString()).c_str()); 
} 

This unit test can be complemented by the functional test of the file utility, as long as it can reliably capture the utility's output for the specific file and verify that it is correct.

No matter what type of tests you create for a new code fragment, they must be added to the established regression suite and be verified on a regular basis. This assures that if subsequent changes break this functionality, the problem will not go unnoticed.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.