Perl-Sensitive Sunglasses | |
PerlMonks |
Re: How to write testable command line script?by davido (Cardinal) |
on Nov 21, 2018 at 16:13 UTC ( [id://1226132]=note: print w/replies, xml ) | Need Help?? |
In answer to the question "How to write testable command line script?", you do so by separating the view from the model, and you do THAT by putting the business logic (the algorithms, in this case) in a module that can be loaded up by your tests. If the model is small and the view (how input is received and how output is rendered) is small, you can do both in the same file in the form of a Modulino (See Mastering Perl, or have a look at https://perlmaven.com/modulino-both-script-and-module). If your presentation is tightly coupled with your algorithms (your business logic) then the first step is to get tests around the full life cycle of the script, and then begin refactoring to achieve the level of decoupling needed to facilitate more thorough unit testing. It does appear that your current script at least has a main() subroutine, but I suspect that your problem in how you are invoking main() is that you are passing all the fields as a single string, whereas the script is expecting each field to be an element passed by @ARGV. But we haven't seen the target code so that's mostly a guess. If your code looks like this:
Then at least main accepts a parameter list. If it does not, then you probably are only working with @ARGV, so you'll need to set @ARGV before each test call, and not bother passing args to main(). But if main() does take args, you're partway there, but probably need to pass them as a list rather than a single string. Also, presumably your script prints the result to STDOUT. But your tests are looking in the return value of main for a string. That likely is broken. You'll probably need to assure that results are always returned by main, and that you are testing the results as a list rather than just a string. This is where separating the view and controller from the model is important: You actually need two views -- one for when this is invoked from the command line, and one for when main() is called directly, because when main() is called directly you probably don't need to be sending output to STDOUT. If you absolutely must put output on STDOUT rather than as a return value, you can test that using Test::Output or Capture::Tiny. Update: I see that you have started down the path, and are passing @ARGV to main, so you're partway there. Dave
In Section
Seekers of Perl Wisdom
|
|