I'm using Ookii.CommandLine (yay!) as well as some internal command line processing of the values after they've passed through Ookii.CommandLine.
I want to add some unit tests that will allow us to show that we correctly respond to invalid data on the command line, but I am hoping to do this by building the array of args from a single string, NOT by manually populating the args themselves. i.e. I want to create a bunch of unit tests to do this:
I want to do this because there is some crafty processing that is handled by cmd.exe when the app is run and I'd like to know that if the user intermixes quotes or other special characters in the argument list, we handle it correctly (or fail gracefully). Further, this will satisfy a security requirement that we attempted to address being 'hacked' by a malicious user into behaving badly through crazy command line arguments.
Does anyone know how to mimic the same processing done by cmd.exe so that I can get the arguments returned in args?
Command line processing is a bit more complex than this. Yes, CMD.EXE does some crafty processing that splits the command line into a string array. Unfortunately, so does PowerShell, but it does things differently. Their similar, but not the same. I think you have 3 options here.
Use a command line parser that parses the full command line and not just the args the shell gives you. This ensures the syntax is the same regardless of the shell, which is both a good and a bad thing.
Right unit tests that test the syntax of both shells, and hope we never get a mainstream third (or more) shell. This seems like the most difficult and brittle option.
Write unit tests that test the args, not the command line. You can create your own helper method to make it easier to write. Simplest would be a function that takes a params string array and returns the array, but that just saves you a few keystrokes. More robust would be to just write a Parse method that parses the string, similar to what you're asking for, but that doesn't care what syntax is used. Pick a simple syntax to parse and ignore what the various shells do. Heck, in most cases a simple Split on the space character would be good enough. More robust, just borrow a CSV parser which would allow you to represent everything in a single string with little effort.
I'd probably go for a CSV parser. Forget about worrying about the shell syntax, it's not really relevant if your command line parser is parsing an args array.
@wkempf:I was hoping not to have to roll my own, but you're probably right.
Thanks for the ideas!
Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.