Testing Scripts Randal L. Schwartz, [email protected]Version LT-1.05 on 13 Jun 2012 This document is copyright 2012 by Randal L. Schwartz, Stonehenge Consulting Services, Inc. This work is licensed under Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License http://creativecommons.org/licenses/by-nc-sa/3.0/ 1 Monday, June 25, 12
My YAPC::NA 2012 Lightning Talk (5 minutes) on testing scripts using Test::Trap and other tools.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
This document is copyright 2012 by Randal L. Schwartz, Stonehenge Consulting Services, Inc.This work is licensed under Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License
http://creativecommons.org/licenses/by-nc-sa/3.0/
1Monday, June 25, 12
• Problem:• Ya gotta test!
• Solution:• use Test::More and friends
• But:• What about scripts!
2Monday, June 25, 12
• Problem:• scripts are separate process• hard to mock things
• Solution:• Don’t use a separate process• Require your script in your .t
• But:• How will I invoke it then?
3Monday, June 25, 12
• Problem:• Loose code is effectively “main”
• Solution:• Bundle loose code into a run subroutine:
sub run { ... }• Also ensure true value at end of script
• But:• What will invoke “run” then?
4Monday, June 25, 12
• Problem:• Invoke “run” when run normally• Don’t invoke “run” via require
• Solution:• Use “caller”:
run(@ARGV) unless caller;• But:• What about namespace of .t file
5Monday, June 25, 12
• Problem:• Collision between script and .t names
• Solution:• Bring it into its own package:
BEGIN { package Program; require "your-script"; die $@ if $@;}
• But:• How to “invoke the program” from tests?
6Monday, June 25, 12
• Problem:• Simulate execution
• Solution:• Invoke run() with desired @ARGV:
subtest try_it => sub { Program::run(qw(--foo --bar abc));};
use Test::Trap::mine qw(:cwd);trap { chdir "/tmp"; Program::run() };
• See my blog, or might be core now• But:• Does this really work for all scripts
13Monday, June 25, 12
• Problem:• Script might need complex interaction• Maybe can’t edit code into run()• Code might fork
• Solution:• Yeah, traditional subprocesses• Perhaps combined with Expect
• But:• Test::Trap is amazingly useful!
14Monday, June 25, 12
Follow me
• Twitter: @merlyn• G+: Randal L. Schwartz• Personal blog: merlyn.posterous.com• http://blogs.perl.org/users/randal_l_schwartz/• merlyn, realmerlyn, or RandalSchwartz