Parser.pm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. # ABSTRACT: Upload your TAP results to TestRail
  2. # PODNAME: Test::Rail::Parser
  3. package Test::Rail::Parser;
  4. use strict;
  5. use warnings;
  6. use utf8;
  7. use parent qw/TAP::Parser/;
  8. use Carp qw{cluck confess};
  9. use POSIX qw{floor};
  10. use TestRail::API;
  11. use Scalar::Util qw{reftype};
  12. use File::Basename qw{basename};
  13. our $self;
  14. =head1 DESCRIPTION
  15. A TAP parser which will upload your test results to a TestRail install.
  16. Has several options as to how you might want to upload said results.
  17. Subclass of L<TAP::Parser>, see that for usage past the constructor.
  18. You should probably use L<App::Prove::Plugin::TestRail> or the bundled program testrail-report for day-to-day usage...
  19. unless you need to subclass this. In that case a couple of options have been exposed for your convenience.
  20. =cut
  21. =head1 CONSTRUCTOR
  22. =head2 B<new(OPTIONS)>
  23. Get the TAP Parser ready to talk to TestRail, and register a bunch of callbacks to upload test results.
  24. =over 4
  25. =item B<OPTIONS> - HASHREF -- Keys are as follows:
  26. =over 4
  27. =item B<apiurl> - STRING: Full URI to your TestRail installation.
  28. =item B<user> - STRING: Name of your TestRail user.
  29. =item B<pass> - STRING: Said user's password.
  30. =item B<debug> - BOOLEAN: Print a bunch of extra messages
  31. =item B<browser> - OBJECT: Something like an LWP::UserAgent. Useful for mocking with L<Test::LWP::UserAgent::TestRailMock>.
  32. =item B<run> - STRING (semi-optional): name of desired run. Required if run_id not passed.
  33. =item B<run_id> - INTEGER (semi-optional): ID of desired run. Required if run not passed.
  34. =item B<plan> - STRING (semi-optional): Name of test plan to use, if your run provided is a child of said plan. Only relevant when run_id not passed.
  35. =item B<configs> - ARRAYREF (optional): Configurations to filter runs in plan by. Runs can have the same name, yet with differing configurations in a plan; this handles that odd case.
  36. =item B<project> - STRING (optional): name of project containing your desired run. Required if project_id not passed.
  37. =item B<project_id> - INTEGER (optional): ID of project containing your desired run. Required if project not passed.
  38. =item B<step_results> - STRING (optional): 'internal name' of the 'step_results' type field available for your project. Mutually exclusive with case_per_ok
  39. =item B<case_per_ok> - BOOLEAN (optional): Consider test files to correspond to section names, and test steps (OKs) to correspond to tests in TestRail. Mutually exclusive with step_results.
  40. =item B<result_options> - HASHREF (optional): Extra options to set with your result. See L<TestRail::API>'s createTestResults function for more information.
  41. =item B<custom_options> - HASHREF (optional): Custom options to set with your result. See L<TestRail::API>'s createTestResults function for more information. step_results will be set here, if the option is passed.
  42. =back
  43. =back
  44. It is worth noting that if neither step_results or case_per_ok is passed, that the test will be passed if it has no problems of any sort, failed otherwise.
  45. In both this mode and step_results, the file name of the test is expected to correspond to the test name in TestRail.
  46. This module also attempts to calculate the elapsed time to run each test if it is run by a prove plugin rather than on raw TAP.
  47. =cut
  48. sub new {
  49. my ($class,$opts) = @_;
  50. our $self;
  51. #Load our callbacks
  52. $opts->{'callbacks'} = {
  53. 'test' => \&testCallback,
  54. 'comment' => \&commentCallback,
  55. 'unknown' => \&unknownCallback,
  56. 'EOF' => \&EOFCallback
  57. };
  58. my $tropts = {
  59. 'apiurl' => delete $opts->{'apiurl'},
  60. 'user' => delete $opts->{'user'},
  61. 'pass' => delete $opts->{'pass'},
  62. 'debug' => delete $opts->{'debug'},
  63. 'browser' => delete $opts->{'browser'},
  64. 'run' => delete $opts->{'run'},
  65. 'run_id' => delete $opts->{'run_id'},
  66. 'project' => delete $opts->{'project'},
  67. 'project_id' => delete $opts->{'project_id'},
  68. 'step_results' => delete $opts->{'step_results'},
  69. 'case_per_ok' => delete $opts->{'case_per_ok'},
  70. 'plan' => delete $opts->{'plan'},
  71. 'configs' => delete $opts->{'configs'},
  72. #Stubs for extension by subclassers
  73. 'result_options' => delete $opts->{'result_options'},
  74. 'result_custom_options' => delete $opts->{'result_custom_options'}
  75. };
  76. #Allow natural confessing from constructor
  77. my $tr = TestRail::API->new($tropts->{'apiurl'},$tropts->{'user'},$tropts->{'pass'},$tropts->{'debug'});
  78. $tropts->{'testrail'} = $tr;
  79. $tr->{'browser'} = $tropts->{'browser'} if defined($tropts->{'browser'}); #allow mocks
  80. $tr->{'debug'} = 0; #Always suppress in production
  81. #Get project ID from name, if not provided
  82. if (!defined($tropts->{'project_id'})) {
  83. my $pname = $tropts->{'project'};
  84. $tropts->{'project'} = $tr->getProjectByName($pname);
  85. confess("Could not list projects! Shutting down.") if ($tropts->{'project'} == -500);
  86. if (!$tropts->{'project'}) {
  87. confess("No project (or project_id) provided, or that which was provided was invalid!");
  88. }
  89. } else {
  90. $tropts->{'project'} = $tr->getProjectByID($tropts->{'project_id'});
  91. confess("No such project with ID $tropts->{project_id}!") if !$tropts->{'project'};
  92. }
  93. $tropts->{'project_id'} = $tropts->{'project'}->{'id'};
  94. #Discover possible test statuses
  95. $tropts->{'statuses'} = $tr->getPossibleTestStatuses();
  96. my @ok = grep {$_->{'name'} eq 'passed'} @{$tropts->{'statuses'}};
  97. my @not_ok = grep {$_->{'name'} eq 'failed'} @{$tropts->{'statuses'}};
  98. my @skip = grep {$_->{'name'} eq 'skip'} @{$tropts->{'statuses'}};
  99. my @todof = grep {$_->{'name'} eq 'todo_fail'} @{$tropts->{'statuses'}};
  100. my @todop = grep {$_->{'name'} eq 'todo_pass'} @{$tropts->{'statuses'}};
  101. confess("No status with internal name 'passed' in TestRail!") unless scalar(@ok);
  102. confess("No status with internal name 'failed' in TestRail!") unless scalar(@not_ok);
  103. confess("No status with internal name 'skip' in TestRail!") unless scalar(@skip);
  104. confess("No status with internal name 'todo_fail' in TestRail!") unless scalar(@todof);
  105. confess("No status with internal name 'todo_pass' in TestRail!") unless scalar(@todop);
  106. $tropts->{'ok'} = $ok[0];
  107. $tropts->{'not_ok'} = $not_ok[0];
  108. $tropts->{'skip'} = $skip[0];
  109. $tropts->{'todo_fail'} = $todof[0];
  110. $tropts->{'todo_pass'} = $todop[0];
  111. #Grab run
  112. my $run_id = $tropts->{'run_id'};
  113. my $run;
  114. #TODO check if configs passed are defined for project
  115. if ($tropts->{'run'}) {
  116. if ($tropts->{'plan'}) {
  117. #Attempt to find run, filtered by configurations
  118. my $plan = $tr->getPlanByName($tropts->{'project_id'},$tropts->{'plan'});
  119. if ($plan) {
  120. $tropts->{'plan'} = $plan; #XXX Save for later just in case?
  121. $run = $tr->getChildRunByName($plan,$tropts->{'run'},$tropts->{'configs'}); #Find plan filtered by configs
  122. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  123. $tropts->{'run'} = $run;
  124. $tropts->{'run_id'} = $run->{'id'};
  125. }
  126. } else {
  127. confess("Could not find plan ".$tropts->{'plan'}." in provided project!");
  128. }
  129. } else {
  130. $run = $tr->getRunByName($tropts->{'project_id'},$tropts->{'run'});
  131. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  132. $tropts->{'run'} = $run;
  133. $tropts->{'run_id'} = $run->{'id'};
  134. }
  135. }
  136. } else {
  137. $tropts->{'run'} = $tr->getRunByID($run_id);
  138. }
  139. confess("No run ID provided, and no run with specified name exists in provided project/plan!") if !$tropts->{'run_id'};
  140. $self = $class->SUPER::new($opts);
  141. if (defined($self->{'_iterator'}->{'command'}) && reftype($self->{'_iterator'}->{'command'}) eq 'ARRAY' ) {
  142. $self->{'file'} = $self->{'_iterator'}->{'command'}->[-1];
  143. print "PROCESSING RESULTS FROM TEST FILE: $self->{'file'}\n";
  144. $self->{'track_time'} = 1;
  145. } else {
  146. #Not running inside of prove in real-time, don't bother with tracking elapsed times.
  147. $self->{'track_time'} = 0;
  148. }
  149. #Make sure the step results field passed exists on the system
  150. $tropts->{'step_results'} = $tr->getTestResultFieldByName($tropts->{'step_results'},$tropts->{'project_id'}) if defined $tropts->{'step_results'};
  151. $self->{'tr_opts'} = $tropts;
  152. $self->{'errors'} = 0;
  153. #Start the shot clock
  154. $self->{'starttime'} = time();
  155. return $self;
  156. }
  157. =head1 PARSER CALLBACKS
  158. =head2 unknownCallback
  159. Called whenever we encounter an unknown line in TAP. Only useful for prove output, as we might pick a filename out of there.
  160. Stores said filename for future use if encountered.
  161. =cut
  162. # Look for file boundaries, etc.
  163. sub unknownCallback {
  164. my (@args) = @_;
  165. our $self;
  166. my $line = $args[0]->as_string;
  167. #try to pick out the filename if we are running this on TAP in files
  168. #old prove
  169. if ($line =~ /^Running\s(.*)/) {
  170. #TODO figure out which testsuite this implies
  171. $self->{'file'} = $1;
  172. print "PROCESSING RESULTS FROM TEST FILE: $self->{'file'}\n";
  173. }
  174. #RAW tap #XXX this regex could be improved
  175. if ($line =~ /(.*)\s\.\.\s*$/) {
  176. $self->{'file'} = $1 unless $line =~ /^[ok|not ok] - /; #a little more careful
  177. }
  178. print "$line\n" if ($line =~ /^error/i);
  179. }
  180. =head2 commentCallback
  181. Grabs comments preceding a test so that we can include that as the test's notes.
  182. Especially useful when merge=1 is passed to the constructor.
  183. =cut
  184. # Register the current suite or test desc for use by test callback, if the line begins with the special magic words
  185. sub commentCallback {
  186. my (@args) = @_;
  187. our $self;
  188. my $line = $args[0]->as_string;
  189. if ($line =~ m/^#TESTDESC:\s*/) {
  190. $self->{'tr_opts'}->{'test_desc'} = $line;
  191. $self->{'tr_opts'}->{'test_desc'} =~ s/^#TESTDESC:\s*//g;
  192. return;
  193. }
  194. #keep all comments before a test that aren't these special directives to save in NOTES field of reportTCResult
  195. $self->{'tr_opts'}->{'test_notes'} .= "$line\n";
  196. }
  197. =head2 testCallback
  198. If we are using step_results, append it to the step results array for use at EOF.
  199. If we are using case_per_ok, update TestRail per case.
  200. Otherwise, do nothing.
  201. =cut
  202. sub testCallback {
  203. my (@args) = @_;
  204. my $test = $args[0];
  205. our $self;
  206. if ( $self->{'track_time'} ) {
  207. #Test done. Record elapsed time.
  208. $self->{'tr_opts'}->{'result_options'}->{'elapsed'} = _compute_elapsed($self->{'starttime'},time());
  209. }
  210. #Don't do anything if we don't want to map TR case => ok or use step-by-step results
  211. if ( !($self->{'tr_opts'}->{'step_results'} || $self->{'tr_opts'}->{'case_per_ok'}) ) {
  212. print "Neither step_results of case_per_ok set. No action to be taken, except on a whole test basis.\n" if $self->{'tr_opts'}->{'debug'};
  213. return 1;
  214. }
  215. if ($self->{'tr_opts'}->{'step_results'} && $self->{'tr_opts'}->{'case_per_ok'}) {
  216. cluck("ERROR: step_options and case_per_ok options are mutually exclusive!");
  217. $self->{'errors'}++;
  218. return 0;
  219. }
  220. #Fail on unplanned tests
  221. if ($test->is_unplanned()) {
  222. cluck("ERROR: Unplanned test detected. Will not attempt to upload results.");
  223. $self->{'errors'}++;
  224. return 0;
  225. }
  226. #Default assumption is that case name is step text (case_per_ok), unless...
  227. my $line = $test->as_string;
  228. $line =~ s/^(ok|not ok)\s[0-9]*\s-\s//g;
  229. my $test_name = $line;
  230. my $run_id = $self->{'tr_opts'}->{'run_id'};
  231. print "Assuming test name is '$test_name'...\n" if $self->{'tr_opts'}->{'debug'} && !$self->{'tr_opts'}->{'step_results'};
  232. my $todo_reason;
  233. #Setup args to pass to function
  234. my $status = $self->{'tr_opts'}->{'not_ok'}->{'id'};
  235. if ($test->is_actual_ok()) {
  236. $status = $self->{'tr_opts'}->{'ok'}->{'id'};
  237. if ($test->has_skip()) {
  238. $status = $self->{'tr_opts'}->{'skip'}->{'id'};
  239. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  240. $test_name =~ s/^# skip //gi;
  241. }
  242. if ($test->has_todo()) {
  243. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'};
  244. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  245. $test_name =~ s/(^# todo & skip )//gi; #handle todo_skip
  246. $test_name =~ s/ # todo\s(.*)$//gi;
  247. $todo_reason = $1;
  248. }
  249. } else {
  250. if ($test->has_todo()) {
  251. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'};
  252. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  253. $test_name =~ s/^# todo & skip //gi; #handle todo_skip
  254. $test_name =~ s/# todo\s(.*)$//gi;
  255. $todo_reason = $1;
  256. }
  257. }
  258. #If this is a TODO, set the reason in the notes
  259. $self->{'tr_opts'}->{'test_notes'} .= "\nTODO reason: $todo_reason\n" if $todo_reason;
  260. #Setup step options and exit if that's the mode we be rollin'
  261. if ($self->{'tr_opts'}->{'step_results'}) {
  262. $self->{'tr_opts'}->{'result_custom_options'} = {} if !defined $self->{'tr_opts'}->{'result_custom_options'};
  263. $self->{'tr_opts'}->{'result_custom_options'}->{'step_results'} = [] if !defined $self->{'tr_opts'}->{'result_custom_options'}->{'step_results'};
  264. #XXX Obviously getting the 'expected' and 'actual' from the tap DIAGs would be ideal
  265. push(
  266. @{$self->{'tr_opts'}->{'result_custom_options'}->{'step_results'}},
  267. TestRail::API::buildStepResults($line,"Good result","Bad Result",$status)
  268. );
  269. print "Appended step results.\n" if $self->{'tr_opts'}->{'debug'};
  270. return 1;
  271. }
  272. #Optional args
  273. my $notes = $self->{'tr_opts'}->{'test_notes'};
  274. my $options = $self->{'tr_opts'}->{'result_options'};
  275. my $custom_options = $self->{'tr_opts'}->{'result_custom_options'};
  276. _set_result($run_id,$test_name,$status,$notes,$options,$custom_options);
  277. #Re-start the shot clock
  278. $self->{'starttime'} = time();
  279. #Blank out test description in anticipation of next test
  280. # also blank out notes
  281. $self->{'tr_opts'}->{'test_notes'} = undef;
  282. $self->{'tr_opts'}->{'test_desc'} = undef;
  283. }
  284. =head2 EOFCallback
  285. If we are running in step_results mode, send over all the step results to TestRail.
  286. If we are running in case_per_ok mode, do nothing.
  287. Otherwise, upload the overall results of the test to TestRail.
  288. =cut
  289. sub EOFCallback {
  290. our $self;
  291. if ( $self->{'track_time'} ) {
  292. #Test done. Record elapsed time.
  293. $self->{'tr_opts'}->{'result_options'}->{'elapsed'} = _compute_elapsed($self->{'starttime'},time());
  294. }
  295. if (!(!$self->{'tr_opts'}->{'step_results'} xor $self->{'tr_opts'}->{'case_per_ok'})) {
  296. print "Nothing left to do.\n";
  297. undef $self->{'tr_opts'} unless $self->{'tr_opts'}->{'debug'};
  298. return 1;
  299. }
  300. #Fail if the file is not set
  301. if (!defined($self->{'file'})) {
  302. cluck("ERROR: Cannot detect filename, will not be able to find a Test Case with that name");
  303. $self->{'errors'}++;
  304. return 0;
  305. }
  306. my $run_id = $self->{'tr_opts'}->{'run_id'};
  307. my $test_name = basename($self->{'file'});
  308. my $status = $self->{'tr_opts'}->{'ok'}->{'id'};
  309. $status = $self->{'tr_opts'}->{'not_ok'}->{'id'} if $self->has_problems();
  310. $status = $self->{'tr_opts'}->{'skip'}->{'id'} if $self->skip_all();
  311. #Optional args
  312. my $notes = $self->{'tr_opts'}->{'test_notes'};
  313. my $options = $self->{'tr_opts'}->{'result_options'};
  314. my $custom_options = $self->{'tr_opts'}->{'result_custom_options'};
  315. print "Setting results...\n";
  316. my $cres = _set_result($run_id,$test_name,$status,$notes,$options,$custom_options);
  317. undef $self->{'tr_opts'} unless $self->{'tr_opts'}->{'debug'};
  318. return $cres;
  319. }
  320. sub _set_result {
  321. my ($run_id,$test_name,$status,$notes,$options,$custom_options) = @_;
  322. our $self;
  323. my $tc;
  324. print "Test elapsed: ".$options->{'elapsed'}."\n" if $options->{'elapsed'};
  325. print "Attempting to find case by title '".$test_name."'...\n";
  326. $tc = $self->{'tr_opts'}->{'testrail'}->getTestByName($run_id,$test_name);
  327. if (!defined($tc) || (reftype($tc) || 'undef') ne 'HASH') {
  328. cluck("ERROR: Could not find test case: $tc");
  329. $self->{'errors'}++;
  330. return 0;
  331. }
  332. my $xid = $tc ? $tc->{'id'} : '???';
  333. my $cres;
  334. #Set test result
  335. if ($tc) {
  336. print "Reporting result of case $xid in run $self->{'tr_opts'}->{'run_id'} as status '$status'...";
  337. # createTestResults(test_id,status_id,comment,options,custom_options)
  338. $cres = $self->{'tr_opts'}->{'testrail'}->createTestResults($tc->{'id'},$status, $notes, $options, $custom_options);
  339. print "OK! (set to $status)\n" if (reftype($cres) || 'undef') eq 'HASH';
  340. }
  341. if (!$tc || ((reftype($cres) || 'undef') ne 'HASH') ) {
  342. print "Failed!\n";
  343. print "No Such test case in TestRail ($xid).\n";
  344. $self->{'errors'}++;
  345. }
  346. }
  347. #Compute the expected testrail date interval from 2 unix timestamps.
  348. sub _compute_elapsed {
  349. my ($begin,$end) = @_;
  350. my $secs_elapsed = $end - $begin;
  351. my $mins_elapsed = floor($secs_elapsed / 60);
  352. my $secs_remain = $secs_elapsed % 60;
  353. my $hours_elapsed = floor($mins_elapsed / 60);
  354. my $mins_remain = $mins_elapsed % 60;
  355. my $datestr = "";
  356. #You have bigger problems if your test takes days
  357. if ($hours_elapsed) {
  358. $datestr .= "$hours_elapsed"."h $mins_remain"."m";
  359. } else {
  360. $datestr .= "$mins_elapsed"."m";
  361. }
  362. if ($mins_elapsed) {
  363. $datestr .= " $secs_remain"."s";
  364. } else {
  365. $datestr .= " $secs_elapsed"."s";
  366. }
  367. undef $datestr if $datestr eq "0m 0s";
  368. return $datestr;
  369. }
  370. 1;
  371. __END__
  372. =head1 NOTES
  373. When using SKIP: {} (or TODO skip) blocks, you may want to consider naming your skip reasons the same as your test names when running in test_per_ok mode.
  374. =head1 SEE ALSO
  375. L<TestRail::API>
  376. L<TAP::Parser>
  377. =head1 SPECIAL THANKS
  378. Thanks to cPanel Inc, for graciously funding the creation of this module.