06 Dec 2013 boost, C++11, program_options, TDD, Testing
I have been spending time recently writing command line apps in
C++11. Each time I wanted a way of handling command line arguments
flexibly. I chose to use the boost::program_options library. The
documentation is pretty good but there are some assumptions (aliased
namespace) and the example code is broken up with paragraphs of text
explaining what the code does.
I have been spending time recently writing command line apps in
C++11. Each time I wanted a way of handling command line arguments
flexibly. I chose to use the boost::program_options library. The
documentation is pretty good but there are some assumptions (aliased
namespace) and the example code is broken up with paragraphs of text
explaining what the code does.
When I start to explore an API to a library I start by writing
tests. After working with the program_options library on a few small
applications the same pattern came up each time so I thought I would
share the results as a complete app, although admittedly the app does
nothing other than accept command line parameters.
The application is also linked up to a continuous integration server
that triggers a build and test on each commit.
To keep the dependencies as low as possible the tests are written
using the boost unit testing framework.
The tests are somewhat artificial in that they test the command line
options results in an application state and not an observable
behavior but are perfectly valid test cases.
Basic use case
app -v --version -username [value] file file
The basic use case offers two variations of switch (-s –switch) a
numeric argument option and a list of files.
== Test: No parameter behavior
So the first test verifies that we can handle (detect) that no command
line parameters were supplied.
Test: Invalid argument
Not everyone is going to get the parameters right so we need to know
when something goes wrong.
Test: Accepting a switch
Accept switch arguments for binary options
Test: Accepting a value argument
Accept values on the command line
Test: Filename parameter list
Accept a list of filenames positionally at the end of the command line
Test: Main method to run the tests
Application bootstrap
Bootstrapping the app. Main methods need to be as small as possible
and responsible for wiring up the application and passing command line
parameters into the application.
Main application class
For anything more than this trivial application the application class
would contain the main application algorithm or defer processing to a
collection of other classes.
The command line processing classes
Class responsible for capturing runtime arguments.