Parser.pm 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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 strftime};
  10. use Clone qw{clone};
  11. use TestRail::API;
  12. use TestRail::Utils;
  13. use Scalar::Util qw{reftype};
  14. use File::Basename qw{basename};
  15. our $self;
  16. =head1 DESCRIPTION
  17. A TAP parser which will upload your test results to a TestRail install.
  18. Has several options as to how you might want to upload said results.
  19. Subclass of L<TAP::Parser>, see that for usage past the constructor.
  20. You should probably use L<App::Prove::Plugin::TestRail> or the bundled program testrail-report for day-to-day usage...
  21. unless you need to subclass this. In that case a couple of options have been exposed for your convenience.
  22. =cut
  23. =head1 CONSTRUCTOR
  24. =head2 B<new(OPTIONS)>
  25. Get the TAP Parser ready to talk to TestRail, and register a bunch of callbacks to upload test results.
  26. =over 4
  27. =item B<OPTIONS> - HASHREF -- Keys are as follows:
  28. =over 4
  29. =item B<apiurl> - STRING: Full URI to your TestRail installation.
  30. =item B<user> - STRING: Name of your TestRail user.
  31. =item B<pass> - STRING: Said user's password, or one of their valid API keys (TestRail 4.2 and above).
  32. =item B<debug> - BOOLEAN: Print a bunch of extra messages
  33. =item B<browser> - OBJECT: Something like an LWP::UserAgent. Useful for mocking.
  34. =item B<run> - STRING: name of desired run.
  35. =item B<plan> - STRING (semi-optional): Name of test plan to use, if your run provided is a child of said plan.
  36. =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.
  37. =item B<project> - STRING (optional): name of project containing your desired run. Required if project_id not passed.
  38. =item B<project_id> - INTEGER (optional): ID of project containing your desired run. Required if project not passed.
  39. =item B<step_results> - STRING (optional): 'internal name' of the 'step_results' type field available for your project. Mutually exclusive with case_per_ok
  40. =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.
  41. =item B<result_options> - HASHREF (optional): Extra options to set with your result. See L<TestRail::API>'s createTestResults function for more information.
  42. =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.
  43. =item B<testsuite> - STRING (optional): Attempt to create a run based on the testsuite identified by the name passed here. If plan/configs are passed, create it as a child of said plan with the listed configs. If the run exists, use it and disregard this option. If the containing plan does not exist, create it too. Mutually exclusive with 'testsuite_id'.
  44. =item B<testsuite_id> - INTEGER (optional): Attempt to create a run based on the testsuite identified by the ID passed here. If plan/configs are passed, create it as a child of said plan with the listed configs. If the run exists, use it and disregard this option. If the plan does not exist, create it too. Mutually exclusive with 'testsuite'.
  45. =item B<sections> - ARRAYREF (optional): Restrict a spawned run to cases in these particular sections.
  46. =item B<autoclose> - BOOLEAN (optional): If no cases in the run/plan are marked 'untested' or 'retest', go ahead and close the run. Default false.
  47. =item B<encoding> - STRING (optional): Character encoding of TAP to be parsed and the various inputs parameters for the parser. Defaults to UTF-8, see L<Encode::Supported> for a list of supported encodings.
  48. =back
  49. =back
  50. 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.
  51. In both this mode and step_results, the file name of the test is expected to correspond to the test name in TestRail.
  52. 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.
  53. The constructor will terminate if the statuses 'pass', 'fail', 'retest', 'skip', 'todo_pass', and 'todo_fail' are not registered as result internal names in your TestRail install.
  54. If you are not in case_per_ok mode, the global status of the case will be set according to the following rules:
  55. 1. If there are no issues whatsoever besides TODO failing tests & skips, mark as PASS
  56. 2. If there are any non-skipped or TODOed fails OR a bad plan (extra/missing tests), mark as FAIL
  57. 3. If there are only SKIPs (e.g. plan => skip_all), mark as SKIP
  58. 4. If the only issues with the test are TODO tests that pass, mark as TODO PASS (to denote these TODOs for removal).
  59. 5. If no tests are run at all, mark as 'retest'. This is making the assumption that such failures are due to test environment being setup improperly;
  60. which can be remediated and retested.
  61. Step results will always be whatever status is relevant to the particular step.
  62. =cut
  63. sub new {
  64. my ($class,$opts) = @_;
  65. our $self;
  66. $opts = clone $opts; #Convenience, if we are passing over and over again...
  67. #Load our callbacks
  68. $opts->{'callbacks'} = {
  69. 'test' => \&testCallback,
  70. 'comment' => \&commentCallback,
  71. 'unknown' => \&unknownCallback,
  72. 'EOF' => \&EOFCallback
  73. };
  74. my $tropts = {
  75. 'apiurl' => delete $opts->{'apiurl'},
  76. 'user' => delete $opts->{'user'},
  77. 'pass' => delete $opts->{'pass'},
  78. 'debug' => delete $opts->{'debug'},
  79. 'browser' => delete $opts->{'browser'},
  80. 'run' => delete $opts->{'run'},
  81. 'project' => delete $opts->{'project'},
  82. 'project_id' => delete $opts->{'project_id'},
  83. 'step_results' => delete $opts->{'step_results'},
  84. 'case_per_ok' => delete $opts->{'case_per_ok'},
  85. 'plan' => delete $opts->{'plan'},
  86. 'configs' => delete $opts->{'configs'} // [],
  87. 'testsuite_id' => delete $opts->{'testsuite_id'},
  88. 'testsuite' => delete $opts->{'testsuite'},
  89. 'encoding' => delete $opts->{'encoding'},
  90. 'sections' => delete $opts->{'sections'},
  91. 'autoclose' => delete $opts->{'autoclose'},
  92. #Stubs for extension by subclassers
  93. 'result_options' => delete $opts->{'result_options'},
  94. 'result_custom_options' => delete $opts->{'result_custom_options'}
  95. };
  96. confess("plan passed, but no run passed!") if !$tropts->{'run'} && $tropts->{'plan'};
  97. confess("case_per_ok and step_results options are mutually exclusive") if ($tropts->{'case_per_ok'} && $tropts->{'step_results'});
  98. #Allow natural confessing from constructor
  99. my $tr = TestRail::API->new($tropts->{'apiurl'},$tropts->{'user'},$tropts->{'pass'},$tropts->{'encoding'},$tropts->{'debug'});
  100. $tropts->{'testrail'} = $tr;
  101. $tr->{'browser'} = $tropts->{'browser'} if defined($tropts->{'browser'}); #allow mocks
  102. $tr->{'debug'} = 0; #Always suppress in production
  103. #Get project ID from name, if not provided
  104. if (!defined($tropts->{'project_id'})) {
  105. my $pname = $tropts->{'project'};
  106. $tropts->{'project'} = $tr->getProjectByName($pname);
  107. confess("Could not list projects! Shutting down.") if ($tropts->{'project'} == -500);
  108. if (!$tropts->{'project'}) {
  109. confess("No project (or project_id) provided, or that which was provided was invalid!");
  110. }
  111. } else {
  112. $tropts->{'project'} = $tr->getProjectByID($tropts->{'project_id'});
  113. confess("No such project with ID $tropts->{project_id}!") if !$tropts->{'project'};
  114. }
  115. $tropts->{'project_id'} = $tropts->{'project'}->{'id'};
  116. #Discover possible test statuses
  117. $tropts->{'statuses'} = $tr->getPossibleTestStatuses();
  118. my @ok = grep {$_->{'name'} eq 'passed'} @{$tropts->{'statuses'}};
  119. my @not_ok = grep {$_->{'name'} eq 'failed'} @{$tropts->{'statuses'}};
  120. my @skip = grep {$_->{'name'} eq 'skip'} @{$tropts->{'statuses'}};
  121. my @todof = grep {$_->{'name'} eq 'todo_fail'} @{$tropts->{'statuses'}};
  122. my @todop = grep {$_->{'name'} eq 'todo_pass'} @{$tropts->{'statuses'}};
  123. my @retest = grep {$_->{'name'} eq 'retest'} @{$tropts->{'statuses'}};
  124. confess("No status with internal name 'passed' in TestRail!") unless scalar(@ok);
  125. confess("No status with internal name 'failed' in TestRail!") unless scalar(@not_ok);
  126. confess("No status with internal name 'skip' in TestRail!") unless scalar(@skip);
  127. confess("No status with internal name 'todo_fail' in TestRail!") unless scalar(@todof);
  128. confess("No status with internal name 'todo_pass' in TestRail!") unless scalar(@todop);
  129. confess("No status with internal name 'retest' in TestRail!") unless scalar(@retest);
  130. $tropts->{'ok'} = $ok[0];
  131. $tropts->{'not_ok'} = $not_ok[0];
  132. $tropts->{'skip'} = $skip[0];
  133. $tropts->{'todo_fail'} = $todof[0];
  134. $tropts->{'todo_pass'} = $todop[0];
  135. $tropts->{'retest'} = $retest[0];
  136. confess "testsuite and testsuite_id are mutually exclusive" if ( $tropts->{'testsuite_id'} && $tropts->{'testsuite'});
  137. #Grab testsuite by name if needed
  138. if ($tropts->{'testsuite'}) {
  139. my $ts = $tr->getTestSuiteByName($tropts->{'project_id'},$tropts->{'testsuite'});
  140. confess("No such testsuite '".$tropts->{'testsuite'}."' found!") unless $ts;
  141. $tropts->{'testsuite_id'} = $ts->{'id'};
  142. }
  143. #Grab run
  144. my ($run,$plan,$config_ids);
  145. #check if configs passed are defined for project. If we can't get all the IDs, something's hinky
  146. @$config_ids = $tr->translateConfigNamesToIds($tropts->{'project_id'},@{$tropts->{'configs'}});
  147. confess("Could not retrieve list of valid configurations for your project.") unless (reftype($config_ids) || 'undef') eq 'ARRAY';
  148. my @bogus_configs = grep {!defined($_)} @$config_ids;
  149. my $num_bogus = scalar(@bogus_configs);
  150. confess("Detected $num_bogus bad config names passed. Check available configurations for your project.") if $num_bogus;
  151. if ($tropts->{'plan'}) {
  152. #Attempt to find run, filtered by configurations
  153. $plan = $tr->getPlanByName($tropts->{'project_id'},$tropts->{'plan'});
  154. confess("Test plan provided is completed, and spawning was not indicated") if (ref $plan eq 'HASH') && $plan->{'is_completed'} && (!$tropts->{'testsuite_id'});
  155. if ($plan && !$plan->{'is_completed'}) {
  156. $tropts->{'plan'} = $plan;
  157. $run = $tr->getChildRunByName($plan,$tropts->{'run'},$tropts->{'configs'}); #Find plan filtered by configs
  158. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  159. $tropts->{'run'} = $run;
  160. $tropts->{'run_id'} = $run->{'id'};
  161. }
  162. } else {
  163. #Try to make it if spawn is passed
  164. $tropts->{'plan'} = $tr->createPlan($tropts->{'project_id'},$tropts->{'plan'},"Test plan created by TestRail::API") if $tropts->{'testsuite_id'};
  165. confess("Could not find plan ".$tropts->{'plan'}." in provided project, and spawning failed (or was not indicated)!") if !$tropts->{'plan'};
  166. }
  167. } else {
  168. $run = $tr->getRunByName($tropts->{'project_id'},$tropts->{'run'});
  169. confess("Test run provided is completed, and spawning was not indicated") if (ref $run eq 'HASH') && $run->{'is_completed'} && (!$tropts->{'testsuite_id'});
  170. if (defined($run) && (reftype($run) || 'undef') eq 'HASH' && !$run->{'is_completed'}) {
  171. $tropts->{'run'} = $run;
  172. $tropts->{'run_id'} = $run->{'id'};
  173. }
  174. }
  175. #If spawn was passed and we don't have a Run ID yet, go ahead and make it
  176. if ($tropts->{'testsuite_id'} && !$tropts->{'run_id'}) {
  177. print "# Spawning run\n";
  178. my $cases = [];
  179. if ($tropts->{'sections'}) {
  180. print "# with specified sections\n";
  181. #Then translate the sections into an array of case IDs.
  182. confess("Sections passed to spawn must be ARRAYREF") unless (reftype($tropts->{'sections'}) || 'undef') eq 'ARRAY';
  183. @{$tropts->{'sections'}} = $tr->sectionNamesToIds($tropts->{'project_id'},$tropts->{'testsuite_id'},@{$tropts->{'sections'}});
  184. foreach my $section (@{$tropts->{'sections'}}) {
  185. my $section_cases = $tr->getCases($tropts->{'project_id'},$tropts->{'testsuite_id'},{ 'section_id' => $section });
  186. push(@$cases,@$section_cases) if (reftype($section_cases) || 'undef') eq 'ARRAY';
  187. }
  188. }
  189. if (scalar(@$cases)) {
  190. @$cases = map {$_->{'id'}} @$cases;
  191. } else {
  192. $cases = undef;
  193. }
  194. if ($tropts->{'plan'}) {
  195. print "# inside of plan\n";
  196. $plan = $tr->createRunInPlan( $tropts->{'plan'}->{'id'}, $tropts->{'testsuite_id'}, $tropts->{'run'}, undef, $config_ids, $cases );
  197. $run = $plan->{'runs'}->[0] if exists($plan->{'runs'}) && (reftype($plan->{'runs'}) || 'undef') eq 'ARRAY' && scalar(@{$plan->{'runs'}});
  198. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  199. $tropts->{'run'} = $run;
  200. $tropts->{'run_id'} = $run->{'id'};
  201. }
  202. } else {
  203. $run = $tr->createRun( $tropts->{'project_id'}, $tropts->{'testsuite_id'}, $tropts->{'run'}, "Automatically created Run from TestRail::API", undef, undef, $cases );
  204. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  205. $tropts->{'run'} = $run;
  206. $tropts->{'run_id'} = $run->{'id'};
  207. }
  208. }
  209. confess("Could not spawn run with requested parameters!") if !$tropts->{'run_id'};
  210. print "# Success!\n"
  211. }
  212. confess("No run ID provided, and no run with specified name exists in provided project/plan!") if !$tropts->{'run_id'};
  213. $self = $class->SUPER::new($opts);
  214. if (defined($self->{'_iterator'}->{'command'}) && reftype($self->{'_iterator'}->{'command'}) eq 'ARRAY' ) {
  215. $self->{'file'} = $self->{'_iterator'}->{'command'}->[-1];
  216. print "# PROCESSING RESULTS FROM TEST FILE: $self->{'file'}\n";
  217. $self->{'track_time'} = 1;
  218. } else {
  219. #Not running inside of prove in real-time, don't bother with tracking elapsed times.
  220. $self->{'track_time'} = 0;
  221. }
  222. #Make sure the step results field passed exists on the system
  223. $tropts->{'step_results'} = $tr->getTestResultFieldByName($tropts->{'step_results'},$tropts->{'project_id'}) if defined $tropts->{'step_results'};
  224. $self->{'tr_opts'} = $tropts;
  225. $self->{'errors'} = 0;
  226. #Start the shot clock
  227. $self->{'starttime'} = time();
  228. #Make sure we get the time it took to get to each step from the last correctly
  229. $self->{'lasttime'} = $self->{'starttime'};
  230. $self->{'raw_output'} = "";
  231. return $self;
  232. }
  233. =head1 PARSER CALLBACKS
  234. =head2 unknownCallback
  235. Called whenever we encounter an unknown line in TAP. Only useful for prove output, as we might pick a filename out of there.
  236. Stores said filename for future use if encountered.
  237. =cut
  238. # Look for file boundaries, etc.
  239. sub unknownCallback {
  240. my (@args) = @_;
  241. our $self;
  242. my $line = $args[0]->as_string;
  243. $self->{'raw_output'} .= "$line\n";
  244. #try to pick out the filename if we are running this on TAP in files
  245. my $file = TestRail::Utils::getFilenameFromTapLine($line);
  246. $self->{'file'} = $file if $file;
  247. }
  248. =head2 commentCallback
  249. Grabs comments preceding a test so that we can include that as the test's notes.
  250. Especially useful when merge=1 is passed to the constructor.
  251. =cut
  252. # Register the current suite or test desc for use by test callback, if the line begins with the special magic words
  253. sub commentCallback {
  254. my (@args) = @_;
  255. our $self;
  256. my $line = $args[0]->as_string;
  257. $self->{'raw_output'} .= "$line\n";
  258. if ($line =~ m/^#TESTDESC:\s*/) {
  259. $self->{'tr_opts'}->{'test_desc'} = $line;
  260. $self->{'tr_opts'}->{'test_desc'} =~ s/^#TESTDESC:\s*//g;
  261. return;
  262. }
  263. #keep all comments before a test that aren't these special directives to save in NOTES field of reportTCResult
  264. $self->{'tr_opts'}->{'test_notes'} .= "$line\n";
  265. }
  266. =head2 testCallback
  267. If we are using step_results, append it to the step results array for use at EOF.
  268. If we are using case_per_ok, update TestRail per case.
  269. Otherwise, do nothing.
  270. =cut
  271. sub testCallback {
  272. my (@args) = @_;
  273. my $test = $args[0];
  274. our $self;
  275. if ( $self->{'track_time'} ) {
  276. #Test done. Record elapsed time.
  277. my $tm = time();
  278. $self->{'tr_opts'}->{'result_options'}->{'elapsed'} = _compute_elapsed($self->{'lasttime'},$tm);
  279. $self->{'elapse_display'} = defined($self->{'tr_opts'}->{'result_options'}->{'elapsed'}) ? $self->{'tr_opts'}->{'result_options'}->{'elapsed'} : "0s";
  280. $self->{'lasttime'} = $tm;
  281. }
  282. #Default assumption is that case name is step text (case_per_ok), unless...
  283. my $line = $test->as_string;
  284. my $tline = $line;
  285. $tline = "[".strftime("%H:%M:%S %b %e %Y",localtime($self->{'lasttime'}))." ($self->{elapse_display})] $line" if $self->{'track_time'};
  286. $self->{'raw_output'} .= "$tline\n";
  287. #Don't do anything if we don't want to map TR case => ok or use step-by-step results
  288. if ( !($self->{'tr_opts'}->{'step_results'} || $self->{'tr_opts'}->{'case_per_ok'}) ) {
  289. print "# Neither step_results or case_per_ok set. No action to be taken, except on a whole test basis.\n" if $self->{'tr_opts'}->{'debug'};
  290. return 1;
  291. }
  292. if ($self->{'tr_opts'}->{'step_results'} && $self->{'tr_opts'}->{'case_per_ok'}) {
  293. cluck("ERROR: step_options and case_per_ok options are mutually exclusive!");
  294. $self->{'errors'}++;
  295. return 0;
  296. }
  297. #Fail on unplanned tests
  298. if ($test->is_unplanned()) {
  299. cluck("ERROR: Unplanned test detected. Will not attempt to upload results.");
  300. $self->{'errors'}++;
  301. return 0;
  302. }
  303. $line =~ s/^(ok|not ok)\s[0-9]*\s-\s//g;
  304. my $test_name = $line;
  305. my $run_id = $self->{'tr_opts'}->{'run_id'};
  306. print "# Assuming test name is '$test_name'...\n" if $self->{'tr_opts'}->{'debug'} && !$self->{'tr_opts'}->{'step_results'};
  307. my $todo_reason;
  308. #Setup args to pass to function
  309. my $status = $self->{'tr_opts'}->{'not_ok'}->{'id'};
  310. if ($test->is_actual_ok()) {
  311. $status = $self->{'tr_opts'}->{'ok'}->{'id'};
  312. if ($test->has_skip()) {
  313. $status = $self->{'tr_opts'}->{'skip'}->{'id'};
  314. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  315. $test_name =~ s/^# skip //gi;
  316. }
  317. if ($test->has_todo()) {
  318. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'};
  319. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  320. $test_name =~ s/(^# todo & skip )//gi; #handle todo_skip
  321. $test_name =~ s/ # todo\s(.*)$//gi;
  322. $todo_reason = $1;
  323. }
  324. } else {
  325. if ($test->has_todo()) {
  326. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'};
  327. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  328. $test_name =~ s/^# todo & skip //gi; #handle todo_skip
  329. $test_name =~ s/# todo\s(.*)$//gi;
  330. $todo_reason = $1;
  331. }
  332. }
  333. #If this is a TODO, set the reason in the notes
  334. $self->{'tr_opts'}->{'test_notes'} .= "\nTODO reason: $todo_reason\n" if $todo_reason;
  335. #Setup step options and exit if that's the mode we be rollin'
  336. if ($self->{'tr_opts'}->{'step_results'}) {
  337. $self->{'tr_opts'}->{'result_custom_options'} = {} if !defined $self->{'tr_opts'}->{'result_custom_options'};
  338. $self->{'tr_opts'}->{'result_custom_options'}->{'step_results'} = [] if !defined $self->{'tr_opts'}->{'result_custom_options'}->{'step_results'};
  339. #TimeStamp every particular step
  340. $line = "[".strftime("%H:%M:%S %b %e %Y",localtime($self->{'lasttime'}))." ($self->{elapse_display})] $line" if $self->{'track_time'};
  341. #XXX Obviously getting the 'expected' and 'actual' from the tap DIAGs would be ideal
  342. push(
  343. @{$self->{'tr_opts'}->{'result_custom_options'}->{'step_results'}},
  344. TestRail::API::buildStepResults($line,"Good result","Bad Result",$status)
  345. );
  346. print "# Appended step results.\n" if $self->{'tr_opts'}->{'debug'};
  347. return 1;
  348. }
  349. #Optional args
  350. my $notes = $self->{'tr_opts'}->{'test_notes'};
  351. my $options = $self->{'tr_opts'}->{'result_options'};
  352. my $custom_options = $self->{'tr_opts'}->{'result_custom_options'};
  353. _set_result($run_id,$test_name,$status,$notes,$options,$custom_options);
  354. #Re-start the shot clock
  355. $self->{'starttime'} = time();
  356. #Blank out test description in anticipation of next test
  357. # also blank out notes
  358. $self->{'tr_opts'}->{'test_notes'} = undef;
  359. $self->{'tr_opts'}->{'test_desc'} = undef;
  360. }
  361. =head2 EOFCallback
  362. If we are running in step_results mode, send over all the step results to TestRail.
  363. If we are running in case_per_ok mode, do nothing.
  364. Otherwise, upload the overall results of the test to TestRail.
  365. =cut
  366. sub EOFCallback {
  367. our $self;
  368. if ( $self->{'track_time'} ) {
  369. #Test done. Record elapsed time.
  370. $self->{'tr_opts'}->{'result_options'}->{'elapsed'} = _compute_elapsed($self->{'starttime'},time());
  371. }
  372. if ($self->{'tr_opts'}->{'case_per_ok'}) {
  373. print "# Nothing left to do.\n";
  374. $self->_test_closure();
  375. undef $self->{'tr_opts'} unless $self->{'tr_opts'}->{'debug'};
  376. return 1;
  377. }
  378. #Fail if the file is not set
  379. if (!defined($self->{'file'})) {
  380. cluck("ERROR: Cannot detect filename, will not be able to find a Test Case with that name");
  381. $self->{'errors'}++;
  382. return 0;
  383. }
  384. my $run_id = $self->{'tr_opts'}->{'run_id'};
  385. my $test_name = basename($self->{'file'});
  386. my $status = $self->{'tr_opts'}->{'ok'}->{'id'};
  387. $status = $self->{'tr_opts'}->{'not_ok'}->{'id'} if $self->has_problems();
  388. $status = $self->{'tr_opts'}->{'retest'}->{'id'} if !$self->tests_run(); #No tests were run, env fail
  389. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'} if $self->todo_passed() && !$self->failed(); #If no fails, but a TODO pass, mark as TODO PASS
  390. $status = $self->{'tr_opts'}->{'skip'}->{'id'} if $self->skip_all(); #Skip all, whee
  391. #Optional args
  392. my $notes = $self->{'tr_opts'}->{'test_notes'};
  393. $notes = $self->{'raw_output'};
  394. my $options = $self->{'tr_opts'}->{'result_options'};
  395. my $custom_options = $self->{'tr_opts'}->{'result_custom_options'};
  396. print "# Setting results...\n";
  397. my $cres = _set_result($run_id,$test_name,$status,$notes,$options,$custom_options);
  398. $self->_test_closure();
  399. $self->{'global_status'} = $status;
  400. undef $self->{'tr_opts'} unless $self->{'tr_opts'}->{'debug'};
  401. return $cres;
  402. }
  403. sub _set_result {
  404. my ($run_id,$test_name,$status,$notes,$options,$custom_options) = @_;
  405. our $self;
  406. my $tc;
  407. print "# Test elapsed: ".$options->{'elapsed'}."\n" if $options->{'elapsed'};
  408. print "# Attempting to find case by title '".$test_name." in run $run_id'...\n";
  409. $tc = $self->{'tr_opts'}->{'testrail'}->getTestByName($run_id,$test_name);
  410. if (!defined($tc) || (reftype($tc) || 'undef') ne 'HASH') {
  411. cluck("ERROR: Could not find test case: $tc");
  412. $self->{'errors'}++;
  413. return 0;
  414. }
  415. my $xid = $tc ? $tc->{'id'} : '???';
  416. my $cres;
  417. #Set test result
  418. if ($tc) {
  419. print "# Reporting result of case $xid in run $self->{'tr_opts'}->{'run_id'} as status '$status'...";
  420. # createTestResults(test_id,status_id,comment,options,custom_options)
  421. $cres = $self->{'tr_opts'}->{'testrail'}->createTestResults($tc->{'id'},$status, $notes, $options, $custom_options);
  422. print "# OK! (set to $status)\n" if (reftype($cres) || 'undef') eq 'HASH';
  423. }
  424. if (!$tc || ((reftype($cres) || 'undef') ne 'HASH') ) {
  425. print "# Failed!\n";
  426. print "# No Such test case in TestRail ($xid).\n";
  427. $self->{'errors'}++;
  428. }
  429. }
  430. #Compute the expected testrail date interval from 2 unix timestamps.
  431. sub _compute_elapsed {
  432. my ($begin,$end) = @_;
  433. my $secs_elapsed = $end - $begin;
  434. my $mins_elapsed = floor($secs_elapsed / 60);
  435. my $secs_remain = $secs_elapsed % 60;
  436. my $hours_elapsed = floor($mins_elapsed / 60);
  437. my $mins_remain = $mins_elapsed % 60;
  438. my $datestr = "";
  439. #You have bigger problems if your test takes days
  440. if ($hours_elapsed) {
  441. $datestr .= "$hours_elapsed"."h $mins_remain"."m";
  442. } else {
  443. $datestr .= "$mins_elapsed"."m";
  444. }
  445. if ($mins_elapsed) {
  446. $datestr .= " $secs_remain"."s";
  447. } else {
  448. $datestr .= " $secs_elapsed"."s";
  449. }
  450. undef $datestr if $datestr eq "0m 0s";
  451. return $datestr;
  452. }
  453. sub _test_closure {
  454. my ($self) = @_;
  455. return unless $self->{'tr_opts'}->{'autoclose'};
  456. my $is_plan = $self->{'tr_opts'}->{'plan'} ? 1 : 0;
  457. my $id = $self->{'tr_opts'}->{'plan'} ? $self->{'tr_opts'}->{'plan'}->{'id'} : $self->{'tr_opts'}->{'run'};
  458. if ($is_plan) {
  459. my $plan_summary = $self->{'tr_opts'}->{'testrail'}->getPlanSummary($id);
  460. return if ( $plan_summary->{'totals'}->{'Untested'} + $plan_summary->{'totals'}->{'Retest'} );
  461. print "# No more outstanding cases detected. Closing Plan.\n";
  462. $self->{'plan_closed'} = 1;
  463. return $self->{'tr_opts'}->{'testrail'}->closePlan($id);
  464. }
  465. my ($run_summary) = $self->{'tr_opts'}->{'testrail'}->getRunSummary($id);
  466. return if ( $run_summary->{'run_status'}->{'Untested'} + $run_summary->{'run_status'}->{'Retest'} );
  467. print "# No more outstanding cases detected. Closing Run.\n";
  468. $self->{'run_closed'} = 1;
  469. return $self->{'tr_opts'}->{'testrail'}->closeRun($self->{'tr_opts'}->{'run_id'});
  470. }
  471. 1;
  472. __END__
  473. =head1 NOTES
  474. 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.
  475. =head1 SEE ALSO
  476. L<TestRail::API>
  477. L<TAP::Parser>
  478. =head1 SPECIAL THANKS
  479. Thanks to cPanel Inc, for graciously funding the creation of this module.