Parser.pm 20 KB

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