Parser.pm 24 KB

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