Parser.pm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. =item B<spawn> - INTEGER (optional): Attempt to create a run based on the provided testsuite identified by the ID passed here. If plan/configs is passed, create it as a child of said plan with the listed configs. If the run exists, use it and disregard the provided testsuite ID.
  43. =back
  44. =back
  45. 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.
  46. In both this mode and step_results, the file name of the test is expected to correspond to the test name in TestRail.
  47. 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.
  48. =cut
  49. sub new {
  50. my ($class,$opts) = @_;
  51. our $self;
  52. #Load our callbacks
  53. $opts->{'callbacks'} = {
  54. 'test' => \&testCallback,
  55. 'comment' => \&commentCallback,
  56. 'unknown' => \&unknownCallback,
  57. 'EOF' => \&EOFCallback
  58. };
  59. my $tropts = {
  60. 'apiurl' => delete $opts->{'apiurl'},
  61. 'user' => delete $opts->{'user'},
  62. 'pass' => delete $opts->{'pass'},
  63. 'debug' => delete $opts->{'debug'},
  64. 'browser' => delete $opts->{'browser'},
  65. 'run' => delete $opts->{'run'},
  66. 'run_id' => delete $opts->{'run_id'},
  67. 'project' => delete $opts->{'project'},
  68. 'project_id' => delete $opts->{'project_id'},
  69. 'step_results' => delete $opts->{'step_results'},
  70. 'case_per_ok' => delete $opts->{'case_per_ok'},
  71. 'plan' => delete $opts->{'plan'},
  72. 'configs' => delete $opts->{'configs'} // [],
  73. 'spawn' => delete $opts->{'spawn'},
  74. #Stubs for extension by subclassers
  75. 'result_options' => delete $opts->{'result_options'},
  76. 'result_custom_options' => delete $opts->{'result_custom_options'}
  77. };
  78. #Allow natural confessing from constructor
  79. my $tr = TestRail::API->new($tropts->{'apiurl'},$tropts->{'user'},$tropts->{'pass'},$tropts->{'debug'});
  80. $tropts->{'testrail'} = $tr;
  81. $tr->{'browser'} = $tropts->{'browser'} if defined($tropts->{'browser'}); #allow mocks
  82. $tr->{'debug'} = 0; #Always suppress in production
  83. #Get project ID from name, if not provided
  84. if (!defined($tropts->{'project_id'})) {
  85. my $pname = $tropts->{'project'};
  86. $tropts->{'project'} = $tr->getProjectByName($pname);
  87. confess("Could not list projects! Shutting down.") if ($tropts->{'project'} == -500);
  88. if (!$tropts->{'project'}) {
  89. confess("No project (or project_id) provided, or that which was provided was invalid!");
  90. }
  91. } else {
  92. $tropts->{'project'} = $tr->getProjectByID($tropts->{'project_id'});
  93. confess("No such project with ID $tropts->{project_id}!") if !$tropts->{'project'};
  94. }
  95. $tropts->{'project_id'} = $tropts->{'project'}->{'id'};
  96. #Discover possible test statuses
  97. $tropts->{'statuses'} = $tr->getPossibleTestStatuses();
  98. my @ok = grep {$_->{'name'} eq 'passed'} @{$tropts->{'statuses'}};
  99. my @not_ok = grep {$_->{'name'} eq 'failed'} @{$tropts->{'statuses'}};
  100. my @skip = grep {$_->{'name'} eq 'skip'} @{$tropts->{'statuses'}};
  101. my @todof = grep {$_->{'name'} eq 'todo_fail'} @{$tropts->{'statuses'}};
  102. my @todop = grep {$_->{'name'} eq 'todo_pass'} @{$tropts->{'statuses'}};
  103. confess("No status with internal name 'passed' in TestRail!") unless scalar(@ok);
  104. confess("No status with internal name 'failed' in TestRail!") unless scalar(@not_ok);
  105. confess("No status with internal name 'skip' in TestRail!") unless scalar(@skip);
  106. confess("No status with internal name 'todo_fail' in TestRail!") unless scalar(@todof);
  107. confess("No status with internal name 'todo_pass' in TestRail!") unless scalar(@todop);
  108. $tropts->{'ok'} = $ok[0];
  109. $tropts->{'not_ok'} = $not_ok[0];
  110. $tropts->{'skip'} = $skip[0];
  111. $tropts->{'todo_fail'} = $todof[0];
  112. $tropts->{'todo_pass'} = $todop[0];
  113. #Grab run
  114. my $run_id = $tropts->{'run_id'};
  115. my ($run,$plan,$config_ids);
  116. #check if configs passed are defined for project. If we can't get all the IDs, something's hinky
  117. $config_ids = $tr->translateConfigNamesToIds($tropts->{'project_id'},$tropts->{'configs'});
  118. confess("Could not retrieve list of valid configurations for your project.") unless (reftype($config_ids) || 'undef') eq 'ARRAY';
  119. my @bogus_configs = grep {!defined($_)} @$config_ids;
  120. my $num_bogus = scalar(@bogus_configs);
  121. confess("Detected $num_bogus bad config names passed. Check available configurations for your project.") if $num_bogus;
  122. if ($tropts->{'run'}) {
  123. if ($tropts->{'plan'}) {
  124. #Attempt to find run, filtered by configurations
  125. $plan = $tr->getPlanByName($tropts->{'project_id'},$tropts->{'plan'});
  126. if ($plan) {
  127. $tropts->{'plan'} = $plan;
  128. $run = $tr->getChildRunByName($plan,$tropts->{'run'},$tropts->{'configs'}); #Find plan filtered by configs
  129. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  130. $tropts->{'run'} = $run;
  131. $tropts->{'run_id'} = $run->{'id'};
  132. }
  133. } else {
  134. confess("Could not find plan ".$tropts->{'plan'}." in provided project!");
  135. }
  136. } else {
  137. $run = $tr->getRunByName($tropts->{'project_id'},$tropts->{'run'});
  138. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  139. $tropts->{'run'} = $run;
  140. $tropts->{'run_id'} = $run->{'id'};
  141. }
  142. }
  143. } else {
  144. $tropts->{'run'} = $tr->getRunByID($run_id);
  145. }
  146. #If spawn was passed and we don't have a Run ID yet, go ahead and make it
  147. if ($tropts->{'spawn'} && !$tropts->{'run_id'}) {
  148. if ($tropts->{'plan'}) {
  149. $plan = $tr->createRunInPlan( $tropts->{'plan'}->{'id'}, $tropts->{'spawn'}, $tropts->{'run'}, undef, $config_ids );
  150. $run = $plan->{'runs'}->[0] if exists($plan->{'runs'}) && (reftype($plan->{'runs'}) || 'undef') eq 'ARRAY' && scalar(@{$plan->{'runs'}});
  151. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  152. $tropts->{'run'} = $run;
  153. $tropts->{'run_id'} = $run->{'id'};
  154. }
  155. } else {
  156. $run = $tr->createRun( $tropts->{'project_id'}, $tropts->{'spawn'}, $tropts->{'run'}, "Automatically created Run from TestRail::API" );
  157. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  158. $tropts->{'run'} = $run;
  159. $tropts->{'run_id'} = $run->{'id'};
  160. }
  161. }
  162. confess("Could not spawn run with requested parameters!") if !$tropts->{'run_id'};
  163. }
  164. confess("No run ID provided, and no run with specified name exists in provided project/plan!") if !$tropts->{'run_id'};
  165. $self = $class->SUPER::new($opts);
  166. if (defined($self->{'_iterator'}->{'command'}) && reftype($self->{'_iterator'}->{'command'}) eq 'ARRAY' ) {
  167. $self->{'file'} = $self->{'_iterator'}->{'command'}->[-1];
  168. print "PROCESSING RESULTS FROM TEST FILE: $self->{'file'}\n";
  169. $self->{'track_time'} = 1;
  170. } else {
  171. #Not running inside of prove in real-time, don't bother with tracking elapsed times.
  172. $self->{'track_time'} = 0;
  173. }
  174. #Make sure the step results field passed exists on the system
  175. $tropts->{'step_results'} = $tr->getTestResultFieldByName($tropts->{'step_results'},$tropts->{'project_id'}) if defined $tropts->{'step_results'};
  176. $self->{'tr_opts'} = $tropts;
  177. $self->{'errors'} = 0;
  178. #Start the shot clock
  179. $self->{'starttime'} = time();
  180. return $self;
  181. }
  182. =head1 PARSER CALLBACKS
  183. =head2 unknownCallback
  184. Called whenever we encounter an unknown line in TAP. Only useful for prove output, as we might pick a filename out of there.
  185. Stores said filename for future use if encountered.
  186. =cut
  187. # Look for file boundaries, etc.
  188. sub unknownCallback {
  189. my (@args) = @_;
  190. our $self;
  191. my $line = $args[0]->as_string;
  192. #try to pick out the filename if we are running this on TAP in files
  193. #old prove
  194. if ($line =~ /^Running\s(.*)/) {
  195. #TODO figure out which testsuite this implies
  196. $self->{'file'} = $1;
  197. print "PROCESSING RESULTS FROM TEST FILE: $self->{'file'}\n";
  198. }
  199. #RAW tap #XXX this regex could be improved
  200. if ($line =~ /(.*)\s\.\.\s*$/) {
  201. $self->{'file'} = $1 unless $line =~ /^[ok|not ok] - /; #a little more careful
  202. }
  203. print "$line\n" if ($line =~ /^error/i);
  204. }
  205. =head2 commentCallback
  206. Grabs comments preceding a test so that we can include that as the test's notes.
  207. Especially useful when merge=1 is passed to the constructor.
  208. =cut
  209. # Register the current suite or test desc for use by test callback, if the line begins with the special magic words
  210. sub commentCallback {
  211. my (@args) = @_;
  212. our $self;
  213. my $line = $args[0]->as_string;
  214. if ($line =~ m/^#TESTDESC:\s*/) {
  215. $self->{'tr_opts'}->{'test_desc'} = $line;
  216. $self->{'tr_opts'}->{'test_desc'} =~ s/^#TESTDESC:\s*//g;
  217. return;
  218. }
  219. #keep all comments before a test that aren't these special directives to save in NOTES field of reportTCResult
  220. $self->{'tr_opts'}->{'test_notes'} .= "$line\n";
  221. }
  222. =head2 testCallback
  223. If we are using step_results, append it to the step results array for use at EOF.
  224. If we are using case_per_ok, update TestRail per case.
  225. Otherwise, do nothing.
  226. =cut
  227. sub testCallback {
  228. my (@args) = @_;
  229. my $test = $args[0];
  230. our $self;
  231. if ( $self->{'track_time'} ) {
  232. #Test done. Record elapsed time.
  233. $self->{'tr_opts'}->{'result_options'}->{'elapsed'} = _compute_elapsed($self->{'starttime'},time());
  234. }
  235. #Don't do anything if we don't want to map TR case => ok or use step-by-step results
  236. if ( !($self->{'tr_opts'}->{'step_results'} || $self->{'tr_opts'}->{'case_per_ok'}) ) {
  237. 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'};
  238. return 1;
  239. }
  240. if ($self->{'tr_opts'}->{'step_results'} && $self->{'tr_opts'}->{'case_per_ok'}) {
  241. cluck("ERROR: step_options and case_per_ok options are mutually exclusive!");
  242. $self->{'errors'}++;
  243. return 0;
  244. }
  245. #Fail on unplanned tests
  246. if ($test->is_unplanned()) {
  247. cluck("ERROR: Unplanned test detected. Will not attempt to upload results.");
  248. $self->{'errors'}++;
  249. return 0;
  250. }
  251. #Default assumption is that case name is step text (case_per_ok), unless...
  252. my $line = $test->as_string;
  253. $line =~ s/^(ok|not ok)\s[0-9]*\s-\s//g;
  254. my $test_name = $line;
  255. my $run_id = $self->{'tr_opts'}->{'run_id'};
  256. print "Assuming test name is '$test_name'...\n" if $self->{'tr_opts'}->{'debug'} && !$self->{'tr_opts'}->{'step_results'};
  257. my $todo_reason;
  258. #Setup args to pass to function
  259. my $status = $self->{'tr_opts'}->{'not_ok'}->{'id'};
  260. if ($test->is_actual_ok()) {
  261. $status = $self->{'tr_opts'}->{'ok'}->{'id'};
  262. if ($test->has_skip()) {
  263. $status = $self->{'tr_opts'}->{'skip'}->{'id'};
  264. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  265. $test_name =~ s/^# skip //gi;
  266. }
  267. if ($test->has_todo()) {
  268. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'};
  269. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  270. $test_name =~ s/(^# todo & skip )//gi; #handle todo_skip
  271. $test_name =~ s/ # todo\s(.*)$//gi;
  272. $todo_reason = $1;
  273. }
  274. } else {
  275. if ($test->has_todo()) {
  276. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'};
  277. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  278. $test_name =~ s/^# todo & skip //gi; #handle todo_skip
  279. $test_name =~ s/# todo\s(.*)$//gi;
  280. $todo_reason = $1;
  281. }
  282. }
  283. #If this is a TODO, set the reason in the notes
  284. $self->{'tr_opts'}->{'test_notes'} .= "\nTODO reason: $todo_reason\n" if $todo_reason;
  285. #Setup step options and exit if that's the mode we be rollin'
  286. if ($self->{'tr_opts'}->{'step_results'}) {
  287. $self->{'tr_opts'}->{'result_custom_options'} = {} if !defined $self->{'tr_opts'}->{'result_custom_options'};
  288. $self->{'tr_opts'}->{'result_custom_options'}->{'step_results'} = [] if !defined $self->{'tr_opts'}->{'result_custom_options'}->{'step_results'};
  289. #XXX Obviously getting the 'expected' and 'actual' from the tap DIAGs would be ideal
  290. push(
  291. @{$self->{'tr_opts'}->{'result_custom_options'}->{'step_results'}},
  292. TestRail::API::buildStepResults($line,"Good result","Bad Result",$status)
  293. );
  294. print "Appended step results.\n" if $self->{'tr_opts'}->{'debug'};
  295. return 1;
  296. }
  297. #Optional args
  298. my $notes = $self->{'tr_opts'}->{'test_notes'};
  299. my $options = $self->{'tr_opts'}->{'result_options'};
  300. my $custom_options = $self->{'tr_opts'}->{'result_custom_options'};
  301. _set_result($run_id,$test_name,$status,$notes,$options,$custom_options);
  302. #Re-start the shot clock
  303. $self->{'starttime'} = time();
  304. #Blank out test description in anticipation of next test
  305. # also blank out notes
  306. $self->{'tr_opts'}->{'test_notes'} = undef;
  307. $self->{'tr_opts'}->{'test_desc'} = undef;
  308. }
  309. =head2 EOFCallback
  310. If we are running in step_results mode, send over all the step results to TestRail.
  311. If we are running in case_per_ok mode, do nothing.
  312. Otherwise, upload the overall results of the test to TestRail.
  313. =cut
  314. sub EOFCallback {
  315. our $self;
  316. if ( $self->{'track_time'} ) {
  317. #Test done. Record elapsed time.
  318. $self->{'tr_opts'}->{'result_options'}->{'elapsed'} = _compute_elapsed($self->{'starttime'},time());
  319. }
  320. if (!(!$self->{'tr_opts'}->{'step_results'} xor $self->{'tr_opts'}->{'case_per_ok'})) {
  321. print "Nothing left to do.\n";
  322. undef $self->{'tr_opts'} unless $self->{'tr_opts'}->{'debug'};
  323. return 1;
  324. }
  325. #Fail if the file is not set
  326. if (!defined($self->{'file'})) {
  327. cluck("ERROR: Cannot detect filename, will not be able to find a Test Case with that name");
  328. $self->{'errors'}++;
  329. return 0;
  330. }
  331. my $run_id = $self->{'tr_opts'}->{'run_id'};
  332. my $test_name = basename($self->{'file'});
  333. my $status = $self->{'tr_opts'}->{'ok'}->{'id'};
  334. $status = $self->{'tr_opts'}->{'not_ok'}->{'id'} if $self->has_problems();
  335. $status = $self->{'tr_opts'}->{'skip'}->{'id'} if $self->skip_all();
  336. #Optional args
  337. my $notes = $self->{'tr_opts'}->{'test_notes'};
  338. my $options = $self->{'tr_opts'}->{'result_options'};
  339. my $custom_options = $self->{'tr_opts'}->{'result_custom_options'};
  340. print "Setting results...\n";
  341. my $cres = _set_result($run_id,$test_name,$status,$notes,$options,$custom_options);
  342. undef $self->{'tr_opts'} unless $self->{'tr_opts'}->{'debug'};
  343. return $cres;
  344. }
  345. sub _set_result {
  346. my ($run_id,$test_name,$status,$notes,$options,$custom_options) = @_;
  347. our $self;
  348. my $tc;
  349. print "Test elapsed: ".$options->{'elapsed'}."\n" if $options->{'elapsed'};
  350. print "Attempting to find case by title '".$test_name."'...\n";
  351. $tc = $self->{'tr_opts'}->{'testrail'}->getTestByName($run_id,$test_name);
  352. if (!defined($tc) || (reftype($tc) || 'undef') ne 'HASH') {
  353. cluck("ERROR: Could not find test case: $tc");
  354. $self->{'errors'}++;
  355. return 0;
  356. }
  357. my $xid = $tc ? $tc->{'id'} : '???';
  358. my $cres;
  359. #Set test result
  360. if ($tc) {
  361. print "Reporting result of case $xid in run $self->{'tr_opts'}->{'run_id'} as status '$status'...";
  362. # createTestResults(test_id,status_id,comment,options,custom_options)
  363. $cres = $self->{'tr_opts'}->{'testrail'}->createTestResults($tc->{'id'},$status, $notes, $options, $custom_options);
  364. print "OK! (set to $status)\n" if (reftype($cres) || 'undef') eq 'HASH';
  365. }
  366. if (!$tc || ((reftype($cres) || 'undef') ne 'HASH') ) {
  367. print "Failed!\n";
  368. print "No Such test case in TestRail ($xid).\n";
  369. $self->{'errors'}++;
  370. }
  371. }
  372. #Compute the expected testrail date interval from 2 unix timestamps.
  373. sub _compute_elapsed {
  374. my ($begin,$end) = @_;
  375. my $secs_elapsed = $end - $begin;
  376. my $mins_elapsed = floor($secs_elapsed / 60);
  377. my $secs_remain = $secs_elapsed % 60;
  378. my $hours_elapsed = floor($mins_elapsed / 60);
  379. my $mins_remain = $mins_elapsed % 60;
  380. my $datestr = "";
  381. #You have bigger problems if your test takes days
  382. if ($hours_elapsed) {
  383. $datestr .= "$hours_elapsed"."h $mins_remain"."m";
  384. } else {
  385. $datestr .= "$mins_elapsed"."m";
  386. }
  387. if ($mins_elapsed) {
  388. $datestr .= " $secs_remain"."s";
  389. } else {
  390. $datestr .= " $secs_elapsed"."s";
  391. }
  392. undef $datestr if $datestr eq "0m 0s";
  393. return $datestr;
  394. }
  395. 1;
  396. __END__
  397. =head1 NOTES
  398. 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.
  399. =head1 SEE ALSO
  400. L<TestRail::API>
  401. L<TAP::Parser>
  402. =head1 SPECIAL THANKS
  403. Thanks to cPanel Inc, for graciously funding the creation of this module.