Parser.pm 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. =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.
  33. =item B<run> - STRING: name of desired run.
  34. =item B<plan> - STRING (semi-optional): Name of test plan to use, if your run provided is a child of said plan.
  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<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'.
  43. =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'.
  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. =head1 TAP Extensions
  62. =head2 Forcing status reported
  63. A line that begins like so:
  64. % mark_status=
  65. Will allow you to force the status of a test case to whatever is on the right hand side of the = expression.
  66. Example (force test to retest in event of tool failure):
  67. my $failed = do_something_possibly_causing_tool_failure();
  68. print "% mark_status=retest" if $failed;
  69. Bogus statuses will cluck, but otherwise be ignored. Valid statuses are any of the required internal names in your TestRail install (see above).
  70. Multiple instances of this will ignore all but the latest valid status.
  71. =cut
  72. sub new {
  73. my ($class,$opts) = @_;
  74. $opts = clone $opts; #Convenience, if we are passing over and over again...
  75. #Load our callbacks
  76. $opts->{'callbacks'} = {
  77. 'test' => \&testCallback,
  78. 'comment' => \&commentCallback,
  79. 'unknown' => \&unknownCallback,
  80. 'EOF' => \&EOFCallback
  81. };
  82. my $tropts = {
  83. 'apiurl' => delete $opts->{'apiurl'},
  84. 'user' => delete $opts->{'user'},
  85. 'pass' => delete $opts->{'pass'},
  86. 'debug' => delete $opts->{'debug'},
  87. 'browser' => delete $opts->{'browser'},
  88. 'run' => delete $opts->{'run'},
  89. 'project' => delete $opts->{'project'},
  90. 'project_id' => delete $opts->{'project_id'},
  91. 'step_results' => delete $opts->{'step_results'},
  92. 'case_per_ok' => delete $opts->{'case_per_ok'},
  93. 'plan' => delete $opts->{'plan'},
  94. 'configs' => delete $opts->{'configs'} // [],
  95. 'testsuite_id' => delete $opts->{'testsuite_id'},
  96. 'testsuite' => delete $opts->{'testsuite'},
  97. 'encoding' => delete $opts->{'encoding'},
  98. 'sections' => delete $opts->{'sections'},
  99. 'autoclose' => delete $opts->{'autoclose'},
  100. #Stubs for extension by subclassers
  101. 'result_options' => delete $opts->{'result_options'},
  102. 'result_custom_options' => delete $opts->{'result_custom_options'}
  103. };
  104. confess("plan passed, but no run passed!") if !$tropts->{'run'} && $tropts->{'plan'};
  105. confess("case_per_ok and step_results options are mutually exclusive") if ($tropts->{'case_per_ok'} && $tropts->{'step_results'});
  106. #Allow natural confessing from constructor
  107. my $tr = TestRail::API->new($tropts->{'apiurl'},$tropts->{'user'},$tropts->{'pass'},$tropts->{'encoding'},$tropts->{'debug'});
  108. $tropts->{'testrail'} = $tr;
  109. $tr->{'browser'} = $tropts->{'browser'} if defined($tropts->{'browser'}); #allow mocks
  110. $tr->{'debug'} = 0; #Always suppress in production
  111. #Get project ID from name, if not provided
  112. if (!defined($tropts->{'project_id'})) {
  113. my $pname = $tropts->{'project'};
  114. $tropts->{'project'} = $tr->getProjectByName($pname);
  115. confess("Could not list projects! Shutting down.") if ($tropts->{'project'} == -500);
  116. if (!$tropts->{'project'}) {
  117. confess("No project (or project_id) provided, or that which was provided was invalid!");
  118. }
  119. } else {
  120. $tropts->{'project'} = $tr->getProjectByID($tropts->{'project_id'});
  121. confess("No such project with ID $tropts->{project_id}!") if !$tropts->{'project'};
  122. }
  123. $tropts->{'project_id'} = $tropts->{'project'}->{'id'};
  124. #Discover possible test statuses
  125. $tropts->{'statuses'} = $tr->getPossibleTestStatuses();
  126. my @ok = grep {$_->{'name'} eq 'passed'} @{$tropts->{'statuses'}};
  127. my @not_ok = grep {$_->{'name'} eq 'failed'} @{$tropts->{'statuses'}};
  128. my @skip = grep {$_->{'name'} eq 'skip'} @{$tropts->{'statuses'}};
  129. my @todof = grep {$_->{'name'} eq 'todo_fail'} @{$tropts->{'statuses'}};
  130. my @todop = grep {$_->{'name'} eq 'todo_pass'} @{$tropts->{'statuses'}};
  131. my @retest = grep {$_->{'name'} eq 'retest'} @{$tropts->{'statuses'}};
  132. confess("No status with internal name 'passed' in TestRail!") unless scalar(@ok);
  133. confess("No status with internal name 'failed' in TestRail!") unless scalar(@not_ok);
  134. confess("No status with internal name 'skip' in TestRail!") unless scalar(@skip);
  135. confess("No status with internal name 'todo_fail' in TestRail!") unless scalar(@todof);
  136. confess("No status with internal name 'todo_pass' in TestRail!") unless scalar(@todop);
  137. confess("No status with internal name 'retest' in TestRail!") unless scalar(@retest);
  138. $tropts->{'ok'} = $ok[0];
  139. $tropts->{'not_ok'} = $not_ok[0];
  140. $tropts->{'skip'} = $skip[0];
  141. $tropts->{'todo_fail'} = $todof[0];
  142. $tropts->{'todo_pass'} = $todop[0];
  143. $tropts->{'retest'} = $retest[0];
  144. confess "testsuite and testsuite_id are mutually exclusive" if ( $tropts->{'testsuite_id'} && $tropts->{'testsuite'});
  145. #Grab testsuite by name if needed
  146. if ($tropts->{'testsuite'}) {
  147. my $ts = $tr->getTestSuiteByName($tropts->{'project_id'},$tropts->{'testsuite'});
  148. confess("No such testsuite '".$tropts->{'testsuite'}."' found!") unless $ts;
  149. $tropts->{'testsuite_id'} = $ts->{'id'};
  150. }
  151. #Grab run
  152. my ($run,$plan,$config_ids);
  153. #check if configs passed are defined for project. If we can't get all the IDs, something's hinky
  154. @$config_ids = $tr->translateConfigNamesToIds($tropts->{'project_id'},@{$tropts->{'configs'}});
  155. confess("Could not retrieve list of valid configurations for your project.") unless (reftype($config_ids) || 'undef') eq 'ARRAY';
  156. my @bogus_configs = grep {!defined($_)} @$config_ids;
  157. my $num_bogus = scalar(@bogus_configs);
  158. confess("Detected $num_bogus bad config names passed. Check available configurations for your project.") if $num_bogus;
  159. if ($tropts->{'plan'}) {
  160. #Attempt to find run, filtered by configurations
  161. $plan = $tr->getPlanByName($tropts->{'project_id'},$tropts->{'plan'});
  162. confess("Test plan provided is completed, and spawning was not indicated") if (ref $plan eq 'HASH') && $plan->{'is_completed'} && (!$tropts->{'testsuite_id'});
  163. if ($plan && !$plan->{'is_completed'}) {
  164. $tropts->{'plan'} = $plan;
  165. $run = $tr->getChildRunByName($plan,$tropts->{'run'},$tropts->{'configs'}); #Find plan filtered by configs
  166. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  167. $tropts->{'run'} = $run;
  168. $tropts->{'run_id'} = $run->{'id'};
  169. }
  170. } else {
  171. #Try to make it if spawn is passed
  172. $tropts->{'plan'} = $tr->createPlan($tropts->{'project_id'},$tropts->{'plan'},"Test plan created by TestRail::API") if $tropts->{'testsuite_id'};
  173. confess("Could not find plan ".$tropts->{'plan'}." in provided project, and spawning failed (or was not indicated)!") if !$tropts->{'plan'};
  174. }
  175. } else {
  176. $run = $tr->getRunByName($tropts->{'project_id'},$tropts->{'run'});
  177. confess("Test run provided is completed, and spawning was not indicated") if (ref $run eq 'HASH') && $run->{'is_completed'} && (!$tropts->{'testsuite_id'});
  178. if (defined($run) && (reftype($run) || 'undef') eq 'HASH' && !$run->{'is_completed'}) {
  179. $tropts->{'run'} = $run;
  180. $tropts->{'run_id'} = $run->{'id'};
  181. }
  182. }
  183. #If spawn was passed and we don't have a Run ID yet, go ahead and make it
  184. if ($tropts->{'testsuite_id'} && !$tropts->{'run_id'}) {
  185. print "# Spawning run\n";
  186. my $cases = [];
  187. if ($tropts->{'sections'}) {
  188. print "# with specified sections\n";
  189. #Then translate the sections into an array of case IDs.
  190. confess("Sections passed to spawn must be ARRAYREF") unless (reftype($tropts->{'sections'}) || 'undef') eq 'ARRAY';
  191. @{$tropts->{'sections'}} = $tr->sectionNamesToIds($tropts->{'project_id'},$tropts->{'testsuite_id'},@{$tropts->{'sections'}});
  192. foreach my $section (@{$tropts->{'sections'}}) {
  193. my $section_cases = $tr->getCases($tropts->{'project_id'},$tropts->{'testsuite_id'},{ 'section_id' => $section });
  194. push(@$cases,@$section_cases) if (reftype($section_cases) || 'undef') eq 'ARRAY';
  195. }
  196. }
  197. if (scalar(@$cases)) {
  198. @$cases = map {$_->{'id'}} @$cases;
  199. } else {
  200. $cases = undef;
  201. }
  202. if ($tropts->{'plan'}) {
  203. print "# inside of plan\n";
  204. $plan = $tr->createRunInPlan( $tropts->{'plan'}->{'id'}, $tropts->{'testsuite_id'}, $tropts->{'run'}, undef, $config_ids, $cases );
  205. $run = $plan->{'runs'}->[0] if exists($plan->{'runs'}) && (reftype($plan->{'runs'}) || 'undef') eq 'ARRAY' && scalar(@{$plan->{'runs'}});
  206. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  207. $tropts->{'run'} = $run;
  208. $tropts->{'run_id'} = $run->{'id'};
  209. }
  210. } else {
  211. $run = $tr->createRun( $tropts->{'project_id'}, $tropts->{'testsuite_id'}, $tropts->{'run'}, "Automatically created Run from TestRail::API", undef, undef, $cases );
  212. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  213. $tropts->{'run'} = $run;
  214. $tropts->{'run_id'} = $run->{'id'};
  215. }
  216. }
  217. confess("Could not spawn run with requested parameters!") if !$tropts->{'run_id'};
  218. print "# Success!\n"
  219. }
  220. confess("No run ID provided, and no run with specified name exists in provided project/plan!") if !$tropts->{'run_id'};
  221. my $self = $class->SUPER::new($opts);
  222. if (defined($self->{'_iterator'}->{'command'}) && reftype($self->{'_iterator'}->{'command'}) eq 'ARRAY' ) {
  223. $self->{'file'} = $self->{'_iterator'}->{'command'}->[-1];
  224. print "# PROCESSING RESULTS FROM TEST FILE: $self->{'file'}\n";
  225. $self->{'track_time'} = 1;
  226. } else {
  227. #Not running inside of prove in real-time, don't bother with tracking elapsed times.
  228. $self->{'track_time'} = 0;
  229. }
  230. #Make sure the step results field passed exists on the system
  231. $tropts->{'step_results'} = $tr->getTestResultFieldByName($tropts->{'step_results'},$tropts->{'project_id'}) if defined $tropts->{'step_results'};
  232. $self->{'tr_opts'} = $tropts;
  233. $self->{'errors'} = 0;
  234. #Start the shot clock
  235. $self->{'starttime'} = time();
  236. #Make sure we get the time it took to get to each step from the last correctly
  237. $self->{'lasttime'} = $self->{'starttime'};
  238. $self->{'raw_output'} = "";
  239. return $self;
  240. }
  241. =head1 PARSER CALLBACKS
  242. =head2 unknownCallback
  243. Called whenever we encounter an unknown line in TAP. Only useful for prove output, as we might pick a filename out of there.
  244. Stores said filename for future use if encountered.
  245. =cut
  246. # Look for file boundaries, etc.
  247. sub unknownCallback {
  248. my ($test) = @_;
  249. my $self = $test->{'parser'};
  250. my $line = $test->as_string;
  251. $self->{'raw_output'} .= "$line\n";
  252. #Unofficial "Extensions" to TAP
  253. my ($status_override) = $line =~ m/^% mark_status=([a-z|_]*)/;
  254. if ($status_override) {
  255. cluck "Unknown status override" unless defined $self->{'tr_opts'}->{$status_override}->{'id'};
  256. $self->{'global_status'} = $self->{'tr_opts'}->{$status_override}->{'id'} if $self->{'tr_opts'}->{$status_override};
  257. print "# Overriding status to $status_override (".$self->{'global_status'}.")...\n" if $self->{'global_status'};
  258. }
  259. #XXX I'd love to just rely on the 'name' attr in App::Prove::State::Result::Test, but...
  260. #try to pick out the filename if we are running this on TAP in files, where App::Prove is uninvolved
  261. my $file = TestRail::Utils::getFilenameFromTapLine($line);
  262. $self->{'file'} = $file if $file;
  263. }
  264. =head2 commentCallback
  265. Grabs comments preceding a test so that we can include that as the test's notes.
  266. Especially useful when merge=1 is passed to the constructor.
  267. =cut
  268. # Register the current suite or test desc for use by test callback, if the line begins with the special magic words
  269. sub commentCallback {
  270. my ($test) = @_;
  271. my $self = $test->{'parser'};
  272. my $line = $test->as_string;
  273. $self->{'raw_output'} .= "$line\n";
  274. if ($line =~ m/^#TESTDESC:\s*/) {
  275. $self->{'tr_opts'}->{'test_desc'} = $line;
  276. $self->{'tr_opts'}->{'test_desc'} =~ s/^#TESTDESC:\s*//g;
  277. return;
  278. }
  279. #keep all comments before a test that aren't these special directives to save in NOTES field of reportTCResult
  280. $self->{'tr_opts'}->{'test_notes'} .= "$line\n";
  281. }
  282. =head2 testCallback
  283. If we are using step_results, append it to the step results array for use at EOF.
  284. If we are using case_per_ok, update TestRail per case.
  285. Otherwise, do nothing.
  286. =cut
  287. sub testCallback {
  288. my ($test) = @_;
  289. my $self = $test->{'parser'};
  290. if ( $self->{'track_time'} ) {
  291. #Test done. Record elapsed time.
  292. my $tm = time();
  293. $self->{'tr_opts'}->{'result_options'}->{'elapsed'} = _compute_elapsed($self->{'lasttime'},$tm);
  294. $self->{'elapse_display'} = defined($self->{'tr_opts'}->{'result_options'}->{'elapsed'}) ? $self->{'tr_opts'}->{'result_options'}->{'elapsed'} : "0s";
  295. $self->{'lasttime'} = $tm;
  296. }
  297. #Default assumption is that case name is step text (case_per_ok), unless...
  298. my $line = $test->as_string;
  299. my $tline = $line;
  300. $tline = "[".strftime("%H:%M:%S %b %e %Y",localtime($self->{'lasttime'}))." ($self->{elapse_display})] $line" if $self->{'track_time'};
  301. $self->{'raw_output'} .= "$tline\n";
  302. #Don't do anything if we don't want to map TR case => ok or use step-by-step results
  303. if ( !($self->{'tr_opts'}->{'step_results'} || $self->{'tr_opts'}->{'case_per_ok'}) ) {
  304. 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'};
  305. return 1;
  306. }
  307. if ($self->{'tr_opts'}->{'step_results'} && $self->{'tr_opts'}->{'case_per_ok'}) {
  308. cluck("ERROR: step_options and case_per_ok options are mutually exclusive!");
  309. $self->{'errors'}++;
  310. return 0;
  311. }
  312. #Fail on unplanned tests
  313. if ($test->is_unplanned()) {
  314. cluck("ERROR: Unplanned test detected. Will not attempt to upload results.");
  315. $self->{'errors'}++;
  316. return 0;
  317. }
  318. $line =~ s/^(ok|not ok)\s[0-9]*\s-\s//g;
  319. my $test_name = $line;
  320. my $run_id = $self->{'tr_opts'}->{'run_id'};
  321. print "# Assuming test name is '$test_name'...\n" if $self->{'tr_opts'}->{'debug'} && !$self->{'tr_opts'}->{'step_results'};
  322. my $todo_reason;
  323. #Setup args to pass to function
  324. my $status = $self->{'tr_opts'}->{'not_ok'}->{'id'};
  325. if ($test->is_actual_ok()) {
  326. $status = $self->{'tr_opts'}->{'ok'}->{'id'};
  327. if ($test->has_skip()) {
  328. $status = $self->{'tr_opts'}->{'skip'}->{'id'};
  329. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  330. $test_name =~ s/^# skip //gi;
  331. }
  332. if ($test->has_todo()) {
  333. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'};
  334. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  335. $test_name =~ s/(^# todo & skip )//gi; #handle todo_skip
  336. $test_name =~ s/ # todo\s(.*)$//gi;
  337. $todo_reason = $1;
  338. }
  339. } else {
  340. if ($test->has_todo()) {
  341. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'};
  342. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  343. $test_name =~ s/^# todo & skip //gi; #handle todo_skip
  344. $test_name =~ s/# todo\s(.*)$//gi;
  345. $todo_reason = $1;
  346. }
  347. }
  348. #If this is a TODO, set the reason in the notes
  349. $self->{'tr_opts'}->{'test_notes'} .= "\nTODO reason: $todo_reason\n" if $todo_reason;
  350. #Setup step options and exit if that's the mode we be rollin'
  351. if ($self->{'tr_opts'}->{'step_results'}) {
  352. $self->{'tr_opts'}->{'result_custom_options'} = {} if !defined $self->{'tr_opts'}->{'result_custom_options'};
  353. $self->{'tr_opts'}->{'result_custom_options'}->{'step_results'} = [] if !defined $self->{'tr_opts'}->{'result_custom_options'}->{'step_results'};
  354. #TimeStamp every particular step
  355. $line = "[".strftime("%H:%M:%S %b %e %Y",localtime($self->{'lasttime'}))." ($self->{elapse_display})] $line" if $self->{'track_time'};
  356. #XXX Obviously getting the 'expected' and 'actual' from the tap DIAGs would be ideal
  357. push(
  358. @{$self->{'tr_opts'}->{'result_custom_options'}->{'step_results'}},
  359. TestRail::API::buildStepResults($line,"Good result","Bad Result",$status)
  360. );
  361. print "# Appended step results.\n" if $self->{'tr_opts'}->{'debug'};
  362. return 1;
  363. }
  364. #Optional args
  365. my $notes = $self->{'tr_opts'}->{'test_notes'};
  366. my $options = $self->{'tr_opts'}->{'result_options'};
  367. my $custom_options = $self->{'tr_opts'}->{'result_custom_options'};
  368. $self->_set_result($run_id,$test_name,$status,$notes,$options,$custom_options);
  369. #Re-start the shot clock
  370. $self->{'starttime'} = time();
  371. #Blank out test description in anticipation of next test
  372. # also blank out notes
  373. $self->{'tr_opts'}->{'test_notes'} = undef;
  374. $self->{'tr_opts'}->{'test_desc'} = undef;
  375. }
  376. =head2 EOFCallback
  377. If we are running in step_results mode, send over all the step results to TestRail.
  378. If we are running in case_per_ok mode, do nothing.
  379. Otherwise, upload the overall results of the test to TestRail.
  380. =cut
  381. sub EOFCallback {
  382. my ($self) = @_;
  383. if ( $self->{'track_time'} ) {
  384. #Test done. Record elapsed time.
  385. $self->{'tr_opts'}->{'result_options'}->{'elapsed'} = _compute_elapsed($self->{'starttime'},time());
  386. }
  387. if ($self->{'tr_opts'}->{'case_per_ok'}) {
  388. print "# Nothing left to do.\n";
  389. $self->_test_closure();
  390. undef $self->{'tr_opts'} unless $self->{'tr_opts'}->{'debug'};
  391. return 1;
  392. }
  393. #Fail if the file is not set
  394. if (!defined($self->{'file'})) {
  395. cluck("ERROR: Cannot detect filename, will not be able to find a Test Case with that name");
  396. $self->{'errors'}++;
  397. return 0;
  398. }
  399. my $run_id = $self->{'tr_opts'}->{'run_id'};
  400. my $test_name = basename($self->{'file'});
  401. my $status = $self->{'tr_opts'}->{'ok'}->{'id'};
  402. $status = $self->{'tr_opts'}->{'not_ok'}->{'id'} if $self->has_problems();
  403. $status = $self->{'tr_opts'}->{'retest'}->{'id'} if !$self->tests_run(); #No tests were run, env fail
  404. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'} if $self->todo_passed() && !$self->failed() && $self->is_good_plan(); #If no fails, but a TODO pass, mark as TODO PASS
  405. $status = $self->{'tr_opts'}->{'skip'}->{'id'} if $self->skip_all(); #Skip all, whee
  406. #Global status override
  407. $status = $self->{'global_status'} if $self->{'global_status'};
  408. #Optional args
  409. my $notes = $self->{'tr_opts'}->{'test_notes'};
  410. $notes = $self->{'raw_output'};
  411. my $options = $self->{'tr_opts'}->{'result_options'};
  412. my $custom_options = $self->{'tr_opts'}->{'result_custom_options'};
  413. print "# Setting results...\n";
  414. my $cres = $self->_set_result($run_id,$test_name,$status,$notes,$options,$custom_options);
  415. $self->_test_closure();
  416. $self->{'global_status'} = $status;
  417. undef $self->{'tr_opts'} unless $self->{'tr_opts'}->{'debug'};
  418. return $cres;
  419. }
  420. sub _set_result {
  421. my ($self,$run_id,$test_name,$status,$notes,$options,$custom_options) = @_;
  422. my $tc;
  423. print "# Test elapsed: ".$options->{'elapsed'}."\n" if $options->{'elapsed'};
  424. print "# Attempting to find case by title '".$test_name." in run $run_id'...\n";
  425. $tc = $self->{'tr_opts'}->{'testrail'}->getTestByName($run_id,$test_name);
  426. if (!defined($tc) || (reftype($tc) || 'undef') ne 'HASH') {
  427. cluck("ERROR: Could not find test case: $tc");
  428. $self->{'errors'}++;
  429. return 0;
  430. }
  431. my $xid = $tc ? $tc->{'id'} : '???';
  432. my $cres;
  433. #Set test result
  434. if ($tc) {
  435. print "# Reporting result of case $xid in run $self->{'tr_opts'}->{'run_id'} as status '$status'...";
  436. # createTestResults(test_id,status_id,comment,options,custom_options)
  437. $cres = $self->{'tr_opts'}->{'testrail'}->createTestResults($tc->{'id'},$status, $notes, $options, $custom_options);
  438. print "# OK! (set to $status)\n" if (reftype($cres) || 'undef') eq 'HASH';
  439. }
  440. if (!$tc || ((reftype($cres) || 'undef') ne 'HASH') ) {
  441. print "# Failed!\n";
  442. print "# No Such test case in TestRail ($xid).\n";
  443. $self->{'errors'}++;
  444. }
  445. }
  446. #Compute the expected testrail date interval from 2 unix timestamps.
  447. sub _compute_elapsed {
  448. my ($begin,$end) = @_;
  449. my $secs_elapsed = $end - $begin;
  450. my $mins_elapsed = floor($secs_elapsed / 60);
  451. my $secs_remain = $secs_elapsed % 60;
  452. my $hours_elapsed = floor($mins_elapsed / 60);
  453. my $mins_remain = $mins_elapsed % 60;
  454. my $datestr = "";
  455. #You have bigger problems if your test takes days
  456. if ($hours_elapsed) {
  457. $datestr .= "$hours_elapsed"."h $mins_remain"."m";
  458. } else {
  459. $datestr .= "$mins_elapsed"."m";
  460. }
  461. if ($mins_elapsed) {
  462. $datestr .= " $secs_remain"."s";
  463. } else {
  464. $datestr .= " $secs_elapsed"."s";
  465. }
  466. undef $datestr if $datestr eq "0m 0s";
  467. return $datestr;
  468. }
  469. sub _test_closure {
  470. my ($self) = @_;
  471. return unless $self->{'tr_opts'}->{'autoclose'};
  472. my $is_plan = $self->{'tr_opts'}->{'plan'} ? 1 : 0;
  473. my $id = $self->{'tr_opts'}->{'plan'} ? $self->{'tr_opts'}->{'plan'}->{'id'} : $self->{'tr_opts'}->{'run'};
  474. if ($is_plan) {
  475. my $plan_summary = $self->{'tr_opts'}->{'testrail'}->getPlanSummary($id);
  476. return if ( $plan_summary->{'totals'}->{'Untested'} + $plan_summary->{'totals'}->{'Retest'} );
  477. print "# No more outstanding cases detected. Closing Plan.\n";
  478. $self->{'plan_closed'} = 1;
  479. return $self->{'tr_opts'}->{'testrail'}->closePlan($id);
  480. }
  481. my ($run_summary) = $self->{'tr_opts'}->{'testrail'}->getRunSummary($id);
  482. return if ( $run_summary->{'run_status'}->{'Untested'} + $run_summary->{'run_status'}->{'Retest'} );
  483. print "# No more outstanding cases detected. Closing Run.\n";
  484. $self->{'run_closed'} = 1;
  485. return $self->{'tr_opts'}->{'testrail'}->closeRun($self->{'tr_opts'}->{'run_id'});
  486. }
  487. =head2 make_result
  488. make_result has been overridden to make the parser object available to callbacks.
  489. =cut
  490. sub make_result {
  491. my ($self,@args) = @_;
  492. my $res = $self->SUPER::make_result(@args);
  493. $res->{'parser'} = $self;
  494. return $res;
  495. }
  496. 1;
  497. __END__
  498. =head1 NOTES
  499. 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.
  500. =head1 SEE ALSO
  501. L<TestRail::API>
  502. L<TAP::Parser>
  503. =head1 SPECIAL THANKS
  504. Thanks to cPanel Inc, for graciously funding the creation of this module.