Parser.pm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 TestRail::API;
  10. use Scalar::Util qw{reftype};
  11. use File::Basename qw{basename};
  12. our $self;
  13. =head1 DESCRIPTION
  14. A TAP parser which will upload your test results to a TestRail install.
  15. Has several options as to how you might want to upload said results.
  16. Subclass of L<TAP::Parser>, see that for usage past the constructor.
  17. You should probably use L<App::Prove::Plugin::TestRail> or the bundled program testrail-report for day-to-day usage...
  18. unless you need to subclass this. In that case a couple of options have been exposed for your convenience.
  19. =cut
  20. =head1 CONSTRUCTOR
  21. =head2 B<new(OPTIONS)>
  22. Get the TAP Parser ready to talk to TestRail, and register a bunch of callbacks to upload test results.
  23. =over 4
  24. =item B<OPTIONS> - HASHREF -- Keys are as follows:
  25. =over 4
  26. =item B<apiurl> - STRING: Full URI to your TestRail installation.
  27. =item B<user> - STRING: Name of your TestRail user.
  28. =item B<pass> - STRING: Said user's password.
  29. =item B<debug> - BOOLEAN: Print a bunch of extra messages
  30. =item B<browser> - OBJECT: Something like an LWP::UserAgent. Useful for mocking with L<Test::LWP::UserAgent::TestRailMock>.
  31. =item B<run> - STRING (optional): name of desired run. Required if run_id not passed.
  32. =item B<run_id> - INTEGER (optional): ID of desired run. Required if run not passed.
  33. =item B<project> - STRING (optional): name of project containing your desired run. Required if project_id not passed.
  34. =item B<project_id> - INTEGER (optional): ID of project containing your desired run. Required if project not passed.
  35. =item B<step_results> - STRING (optional): 'internal name' of the 'step_results' type field available for your project. Mutually exclusive with case_per_ok
  36. =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.
  37. =item B<result_options> - HASHREF (optional): Extra options to set with your result. See L<TestRail::API>'s createTestResults function for more information.
  38. =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.
  39. =back
  40. =back
  41. 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.
  42. In both this mode and step_results, the file name of the test is expected to correspond to the test name in TestRail.
  43. =cut
  44. sub new {
  45. my ($class,$opts) = @_;
  46. our $self;
  47. #Load our callbacks
  48. $opts->{'callbacks'} = {
  49. 'test' => \&testCallback,
  50. 'comment' => \&commentCallback,
  51. 'unknown' => \&unknownCallback,
  52. 'EOF' => \&EOFCallback
  53. };
  54. my $tropts = {
  55. 'apiurl' => delete $opts->{'apiurl'},
  56. 'user' => delete $opts->{'user'},
  57. 'pass' => delete $opts->{'pass'},
  58. 'debug' => delete $opts->{'debug'},
  59. 'browser' => delete $opts->{'browser'},
  60. 'run' => delete $opts->{'run'},
  61. 'run_id' => delete $opts->{'run_id'},
  62. 'project' => delete $opts->{'project'},
  63. 'project_id' => delete $opts->{'project_id'},
  64. 'step_results' => delete $opts->{'step_results'},
  65. 'case_per_ok' => delete $opts->{'case_per_ok'},
  66. 'plan' => delete $opts->{'plan'},
  67. 'configs' => delete $opts->{'configs'},
  68. #Stubs for extension by subclassers
  69. 'result_options' => delete $opts->{'result_options'},
  70. 'result_custom_options' => delete $opts->{'result_custom_options'}
  71. };
  72. #Allow natural confessing from constructor
  73. my $tr = TestRail::API->new($tropts->{'apiurl'},$tropts->{'user'},$tropts->{'pass'},$tropts->{'debug'});
  74. $tropts->{'testrail'} = $tr;
  75. $tr->{'browser'} = $tropts->{'browser'} if defined($tropts->{'browser'}); #allow mocks
  76. $tr->{'debug'} = 0; #Always suppress in production
  77. #Get project ID from name, if not provided
  78. if (!defined($tropts->{'project_id'})) {
  79. my $pname = $tropts->{'project'};
  80. $tropts->{'project'} = $tr->getProjectByName($pname);
  81. confess("Could not list projects! Shutting down.") if ($tropts->{'project'} == -500);
  82. if (!$tropts->{'project'}) {
  83. confess("No project (or project_id) provided, or that which was provided was invalid!");
  84. }
  85. } else {
  86. $tropts->{'project'} = $tr->getProjectByID($tropts->{'project_id'});
  87. confess("No such project with ID $tropts->{project_id}!") if !$tropts->{'project'};
  88. }
  89. $tropts->{'project_id'} = $tropts->{'project'}->{'id'};
  90. #Discover possible test statuses
  91. $tropts->{'statuses'} = $tr->getPossibleTestStatuses();
  92. my @ok = grep {$_->{'name'} eq 'passed'} @{$tropts->{'statuses'}};
  93. my @not_ok = grep {$_->{'name'} eq 'failed'} @{$tropts->{'statuses'}};
  94. my @skip = grep {$_->{'name'} eq 'skip'} @{$tropts->{'statuses'}};
  95. my @todof = grep {$_->{'name'} eq 'todo_fail'} @{$tropts->{'statuses'}};
  96. my @todop = grep {$_->{'name'} eq 'todo_pass'} @{$tropts->{'statuses'}};
  97. confess("No status with internal name 'passed' in TestRail!") unless scalar(@ok);
  98. confess("No status with internal name 'failed' in TestRail!") unless scalar(@not_ok);
  99. confess("No status with internal name 'skip' in TestRail!") unless scalar(@skip);
  100. confess("No status with internal name 'todo_fail' in TestRail!") unless scalar(@todof);
  101. confess("No status with internal name 'todo_pass' in TestRail!") unless scalar(@todop);
  102. $tropts->{'ok'} = $ok[0];
  103. $tropts->{'not_ok'} = $not_ok[0];
  104. $tropts->{'skip'} = $skip[0];
  105. $tropts->{'todo_fail'} = $todof[0];
  106. $tropts->{'todo_pass'} = $todop[0];
  107. #Grab run
  108. my $run_id = $tropts->{'run_id'};
  109. my $run;
  110. #TODO check if configs passed are defined for project
  111. if ($tropts->{'run'}) {
  112. if ($tropts->{'plan'}) {
  113. #Attempt to find run, filtered by configurations
  114. my $plan = $tr->getPlanByName($tropts->{'project_id'},$tropts->{'plan'});
  115. if ($plan) {
  116. $tropts->{'plan'} = $plan; #XXX Save for later just in case?
  117. $run = $tr->getChildRunByName($plan,$tropts->{'run'},$tropts->{'configs'}); #Find plan filtered by configs
  118. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  119. $tropts->{'run'} = $run;
  120. $tropts->{'run_id'} = $run->{'id'};
  121. }
  122. } else {
  123. confess("Could not find plan ".$tropts->{'plan'}." in provided project!");
  124. }
  125. } else {
  126. $run = $tr->getRunByName($tropts->{'project_id'},$tropts->{'run'});
  127. if (defined($run) && (reftype($run) || 'undef') eq 'HASH') {
  128. $tropts->{'run'} = $run;
  129. $tropts->{'run_id'} = $run->{'id'};
  130. }
  131. }
  132. } else {
  133. $tropts->{'run'} = $tr->getRunByID($run_id);
  134. }
  135. confess("No run ID provided, and no run with specified name exists in provided project/plan!") if !$tropts->{'run_id'};
  136. $self = $class->SUPER::new($opts);
  137. if (defined($self->{'_iterator'}->{'command'}) && reftype($self->{'_iterator'}->{'command'}) eq 'ARRAY' ) {
  138. $self->{'file'} = $self->{'_iterator'}->{'command'}->[-1];
  139. print "PROCESSING RESULTS FROM TEST FILE: $self->{'file'}\n";
  140. }
  141. #Make sure the step results field passed exists on the system
  142. $tropts->{'step_results'} = $tr->getTestResultFieldByName($tropts->{'step_results'},$tropts->{'project_id'}) if defined $tropts->{'step_results'};
  143. $self->{'tr_opts'} = $tropts;
  144. $self->{'errors'} = 0;
  145. return $self;
  146. }
  147. =head1 PARSER CALLBACKS
  148. =head2 unknownCallback
  149. Called whenever we encounter an unknown line in TAP. Only useful for prove output, as we might pick a filename out of there.
  150. Stores said filename for future use if encountered.
  151. =cut
  152. # Look for file boundaries, etc.
  153. sub unknownCallback {
  154. my (@args) = @_;
  155. our $self;
  156. my $line = $args[0]->as_string;
  157. #try to pick out the filename if we are running this on TAP in files
  158. #old prove
  159. if ($line =~ /^Running\s(.*)/) {
  160. #TODO figure out which testsuite this implies
  161. $self->{'file'} = $1;
  162. print "PROCESSING RESULTS FROM TEST FILE: $self->{'file'}\n";
  163. }
  164. #RAW tap #XXX this regex could be improved
  165. if ($line =~ /(.*)\s\.\.\s*$/) {
  166. $self->{'file'} = $1 unless $line =~ /^[ok|not ok] - /; #a little more careful
  167. }
  168. print "$line\n" if ($line =~ /^error/i);
  169. }
  170. =head2 commentCallback
  171. Grabs comments preceding a test so that we can include that as the test's notes.
  172. Especially useful when merge=1 is passed to the constructor.
  173. =cut
  174. # Register the current suite or test desc for use by test callback, if the line begins with the special magic words
  175. sub commentCallback {
  176. my (@args) = @_;
  177. our $self;
  178. my $line = $args[0]->as_string;
  179. if ($line =~ m/^#TESTDESC:\s*/) {
  180. $self->{'tr_opts'}->{'test_desc'} = $line;
  181. $self->{'tr_opts'}->{'test_desc'} =~ s/^#TESTDESC:\s*//g;
  182. return;
  183. }
  184. #keep all comments before a test that aren't these special directives to save in NOTES field of reportTCResult
  185. $self->{'tr_opts'}->{'test_notes'} .= "$line\n";
  186. }
  187. =head2 testCallback
  188. If we are using step_results, append it to the step results array for use at EOF.
  189. If we are using case_per_ok, update TestRail per case.
  190. Otherwise, do nothing.
  191. =cut
  192. sub testCallback {
  193. my (@args) = @_;
  194. my $test = $args[0];
  195. our $self;
  196. #Don't do anything if we don't want to map TR case => ok or use step-by-step results
  197. if ( !($self->{'tr_opts'}->{'step_results'} || $self->{'tr_opts'}->{'case_per_ok'}) ) {
  198. print "Neither step_results of case_per_ok set. No action to be taken, except on a whole test basis.\n" if $self->{'tr_opts'}->{'debug'};
  199. return 1;
  200. }
  201. if ($self->{'tr_opts'}->{'step_results'} && $self->{'tr_opts'}->{'case_per_ok'}) {
  202. cluck("ERROR: step_options and case_per_ok options are mutually exclusive!");
  203. $self->{'errors'}++;
  204. return 0;
  205. }
  206. #Fail on unplanned tests
  207. if ($test->is_unplanned()) {
  208. cluck("ERROR: Unplanned test detected. Will not attempt to upload results.");
  209. $self->{'errors'}++;
  210. return 0;
  211. }
  212. #Default assumption is that case name is step text (case_per_ok), unless...
  213. my $line = $test->as_string;
  214. $line =~ s/^(ok|not ok)\s[0-9]*\s-\s//g;
  215. my $test_name = $line;
  216. my $run_id = $self->{'tr_opts'}->{'run_id'};
  217. print "Assuming test name is '$test_name'...\n" if $self->{'tr_opts'}->{'debug'} && !$self->{'tr_opts'}->{'step_results'};
  218. my $todo_reason;
  219. #Setup args to pass to function
  220. my $status = $self->{'tr_opts'}->{'not_ok'}->{'id'};
  221. if ($test->is_actual_ok()) {
  222. $status = $self->{'tr_opts'}->{'ok'}->{'id'};
  223. if ($test->has_skip()) {
  224. $status = $self->{'tr_opts'}->{'skip'}->{'id'};
  225. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  226. $test_name =~ s/^# skip //gi;
  227. }
  228. if ($test->has_todo()) {
  229. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'};
  230. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  231. $test_name =~ s/(^# todo & skip )//gi; #handle todo_skip
  232. $test_name =~ s/ # todo\s(.*)$//gi;
  233. $todo_reason = $1;
  234. }
  235. } else {
  236. if ($test->has_todo()) {
  237. $status = $self->{'tr_opts'}->{'todo_pass'}->{'id'};
  238. $test_name =~ s/^(ok|not ok)\s[0-9]*\s//g;
  239. $test_name =~ s/^# todo & skip //gi; #handle todo_skip
  240. $test_name =~ s/# todo\s(.*)$//gi;
  241. $todo_reason = $1;
  242. }
  243. }
  244. #If this is a TODO, set the reason in the notes
  245. $self->{'tr_opts'}->{'test_notes'} .= "\nTODO reason: $todo_reason\n" if $todo_reason;
  246. #Setup step options and exit if that's the mode we be rollin'
  247. if ($self->{'tr_opts'}->{'step_results'}) {
  248. $self->{'tr_opts'}->{'result_custom_options'} = {} if !defined $self->{'tr_opts'}->{'result_custom_options'};
  249. $self->{'tr_opts'}->{'result_custom_options'}->{'step_results'} = [] if !defined $self->{'tr_opts'}->{'result_custom_options'}->{'step_results'};
  250. #XXX Obviously getting the 'expected' and 'actual' from the tap DIAGs would be ideal
  251. push(
  252. @{$self->{'tr_opts'}->{'result_custom_options'}->{'step_results'}},
  253. TestRail::API::buildStepResults($line,"Good result","Bad Result",$status)
  254. );
  255. print "Appended step results.\n" if $self->{'tr_opts'}->{'debug'};
  256. return 1;
  257. }
  258. #Optional args
  259. my $notes = $self->{'tr_opts'}->{'test_notes'};
  260. my $options = $self->{'tr_opts'}->{'result_options'};
  261. my $custom_options = $self->{'tr_opts'}->{'result_custom_options'};
  262. _set_result($run_id,$test_name,$status,$notes,$options,$custom_options);
  263. #Blank out test description in anticipation of next test
  264. # also blank out notes
  265. $self->{'tr_opts'}->{'test_notes'} = undef;
  266. $self->{'tr_opts'}->{'test_desc'} = undef;
  267. }
  268. =head2 EOFCallback
  269. If we are running in step_results mode, send over all the step results to TestRail.
  270. If we are running in case_per_ok mode, do nothing.
  271. Otherwise, upload the overall results of the test to TestRail.
  272. =cut
  273. sub EOFCallback {
  274. our $self;
  275. if (!(!$self->{'tr_opts'}->{'step_results'} xor $self->{'tr_opts'}->{'case_per_ok'})) {
  276. print "Nothing left to do.\n";
  277. undef $self->{'tr_opts'};
  278. return 1;
  279. }
  280. #Fail if the file is not set
  281. if (!defined($self->{'file'})) {
  282. cluck("ERROR: Cannot detect filename, will not be able to find a Test Case with that name");
  283. $self->{'errors'}++;
  284. return 0;
  285. }
  286. my $run_id = $self->{'tr_opts'}->{'run_id'};
  287. my $test_name = basename($self->{'file'});
  288. my $status = $self->{'tr_opts'}->{'ok'}->{'id'};
  289. $status = $self->{'tr_opts'}->{'not_ok'}->{'id'} if $self->has_problems();
  290. $status = $self->{'tr_opts'}->{'skip'}->{'id'} if $self->skip_all();
  291. #Optional args
  292. my $notes = $self->{'tr_opts'}->{'test_notes'};
  293. my $options = $self->{'tr_opts'}->{'result_options'};
  294. my $custom_options = $self->{'tr_opts'}->{'result_custom_options'};
  295. print "Setting results...\n";
  296. my $cres = _set_result($run_id,$test_name,$status,$notes,$options,$custom_options);
  297. undef $self->{'tr_opts'};
  298. return $cres;
  299. }
  300. sub _set_result {
  301. my ($run_id,$test_name,$status,$notes,$options,$custom_options) = @_;
  302. our $self;
  303. my $tc;
  304. print "Attempting to find case by title '".$test_name."'...\n";
  305. $tc = $self->{'tr_opts'}->{'testrail'}->getTestByName($run_id,$test_name);
  306. if (!defined($tc) || (reftype($tc) || 'undef') ne 'HASH') {
  307. cluck("ERROR: Could not find test case: $tc");
  308. $self->{'errors'}++;
  309. return 0;
  310. }
  311. my $xid = $tc ? $tc->{'id'} : '???';
  312. my $cres;
  313. #Set test result
  314. if ($tc) {
  315. print "Reporting result of case $xid in run $self->{'tr_opts'}->{'run_id'} as status '$status'...";
  316. # createTestResults(test_id,status_id,comment,options,custom_options)
  317. $cres = $self->{'tr_opts'}->{'testrail'}->createTestResults($tc->{'id'},$status, $notes, $options, $custom_options);
  318. print "OK! (set to $status)\n" if (reftype($cres) || 'undef') eq 'HASH';
  319. }
  320. if (!$tc || ((reftype($cres) || 'undef') ne 'HASH') ) {
  321. print "Failed!\n";
  322. print "No Such test case in TestRail ($xid).\n";
  323. $self->{'errors'}++;
  324. }
  325. }
  326. 1;
  327. __END__
  328. =head1 NOTES
  329. 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.
  330. =head1 SEE ALSO
  331. L<TestRail::API>
  332. L<TAP::Parser>
  333. =head1 SPECIAL THANKS
  334. Thanks to cPanel Inc, for graciously funding the creation of this module.