Parser.pm 30 KB

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