Parser.pm 29 KB

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