Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test deliberate compilation errors of template code

Please note that this is NOT a duplicate of How write a unit test for verifying compiling error? as I'm not concerned about testing the correctness of external libraries or the compiler itself.

It is typical in C++, particularly when dealing with templates, to employ techniques that prevent some particular piece of code from being compiled. As these can get convoluted, what is the best way to ensure that particular pieces of code do indeed generate compiler errors?

As the test shouldn't even get compiled, you can't rely on things such as boost-test, so I guess it should be integrated in the build system? How are these issues usually approached?

like image 497
UncleZeiv Avatar asked Sep 02 '11 10:09

UncleZeiv


People also ask

Does unit testing test compile errors?

As you seem to understand yourself, a unit test is not supposed to check for syntax errors, so I wouldn't advise testing for "type correctness" or anything of the kind. That's why there's a compiler. This bug had some unwanted effect in production.

What errors are commonly found during unit testing?

Unit testing considerations What errors are commonly found during Unit Testing? (1) Misunderstood or incorrect arithmetic precedence, (2) Mixed mode operations, (3) Incorrect initialization, (4) Precision inaccuracy, (5) Incorrect symbolic representation of an expression.

Who will identify the compilation error in a program?

You must be the boss. When you look at an error, the compiler or IDE shows you the line where it detects the error. But the error is not always on that line. For example, if you have omitted a semicolon on line 12 then the compiler might detect an error at line 13.


1 Answers

Do it in the similar way compiler tests are written. You will have a bit of testing code in some scripting language (shell, perl, tcl etc.) that will run compiler on given snippets of code and check whether the right ones compiled and the right ones did not.

  • gcc uses DejaGnu, which is built on top of expect, which is itself built on top of Tcl.
  • If you use shell script (probably easier, DejaGnu is probably overkill), you might want to look at shUnit2.
  • Perl's Test::Harness system should be mostly easy to use as is.
  • After all, it's not that much more work to run process from C++, so writing a function to try to call compiler on a given string and check whether it outputs error for line where you expect it would not be that hard and than you can integrate it into the other boost.test-based tests.
like image 177
Jan Hudec Avatar answered Sep 19 '22 13:09

Jan Hudec