Find.pm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. # PODNAME: TestRail::Utils::Find
  2. # ABSTRACT: Find runs and tests according to user specifications.
  3. package TestRail::Utils::Find;
  4. use strict;
  5. use warnings;
  6. use Carp qw{confess cluck};
  7. use Scalar::Util qw{blessed};
  8. use List::Util qw{any first};
  9. use List::MoreUtils qw{uniq};
  10. use File::Find;
  11. use Cwd qw{abs_path};
  12. use File::Basename qw{basename};
  13. use Hash::Merge qw{merge};
  14. use MCE::Loop;
  15. use TestRail::Utils;
  16. =head1 DESCRIPTION
  17. =head1 FUNCTIONS
  18. =head2 findRuns
  19. Find runs based on the options HASHREF provided.
  20. See the documentation for testrail-runs, as the long argument names there correspond to hash keys.
  21. The primary routine of testrail-runs.
  22. =over 4
  23. =item HASHREF C<OPTIONS> - flags acceptable by testrail-tests
  24. =item TestRail::API C<HANDLE> - TestRail::API object
  25. =back
  26. Returns ARRAYREF of run definition HASHREFs.
  27. =cut
  28. sub findRuns {
  29. my ($opts,$tr) = @_;
  30. confess("TestRail handle must be provided as argument 2") unless blessed($tr) eq 'TestRail::API';
  31. my ($status_labels);
  32. #Process statuses
  33. if ($opts->{'statuses'}) {
  34. @$status_labels = $tr->statusNamesToLabels(@{$opts->{'statuses'}});
  35. }
  36. my $project = $tr->getProjectByName($opts->{'project'});
  37. confess("No such project '$opts->{project}'.\n") if !$project;
  38. my $pconfigs = [];
  39. @$pconfigs = $tr->translateConfigNamesToIds($project->{'id'},@{$opts->{configs}}) if $opts->{'configs'};
  40. my ($runs,$plans,$planRuns,$cruns,$found) = ([],[],[],[],0);
  41. $runs = $tr->getRuns($project->{'id'}) if (!$opts->{'configs'}); # If configs are passed, global runs are not in consideration.
  42. $plans = $tr->getPlans($project->{'id'});
  43. @$plans = map {$tr->getPlanByID($_->{'id'})} @$plans;
  44. foreach my $plan (@$plans) {
  45. $cruns = $tr->getChildRuns($plan);
  46. next if !$cruns;
  47. foreach my $run (@$cruns) {
  48. next if scalar(@$pconfigs) != scalar(@{$run->{'config_ids'}});
  49. #Compare run config IDs against desired, invalidate run if all conditions not satisfied
  50. $found = 0;
  51. foreach my $cid (@{$run->{'config_ids'}}) {
  52. $found++ if grep {$_ == $cid} @$pconfigs;
  53. }
  54. $run->{'created_on'} = $plan->{'created_on'};
  55. $run->{'milestone_id'} = $plan->{'milestone_id'};
  56. push(@$planRuns, $run) if $found == scalar(@{$run->{'config_ids'}});
  57. }
  58. }
  59. push(@$runs,@$planRuns);
  60. if ($opts->{'statuses'}) {
  61. @$runs = $tr->getRunSummary(@$runs);
  62. @$runs = grep { defined($_->{'run_status'}) } @$runs; #Filter stuff with no results
  63. foreach my $status (@$status_labels) {
  64. @$runs = grep { $_->{'run_status'}->{$status} } @$runs; #If it's positive, keep it. Otherwise forget it.
  65. }
  66. }
  67. #Sort FIFO/LIFO by milestone or creation date of run
  68. my $sortkey = 'created_on';
  69. if ($opts->{'milesort'}) {
  70. @$runs = map {
  71. my $run = $_;
  72. $run->{'milestone'} = $tr->getMilestoneByID($run->{'milestone_id'}) if $run->{'milestone_id'};
  73. my $milestone = $run->{'milestone'} ? $run->{'milestone'}->{'due_on'} : 0;
  74. $run->{'due_on'} = $milestone;
  75. $run
  76. } @$runs;
  77. $sortkey = 'due_on';
  78. }
  79. #Suppress 'no such option' warnings
  80. @$runs = map { $_->{$sortkey} //= ''; $_ } @$runs;
  81. if ($opts->{'lifo'}) {
  82. @$runs = sort { $b->{$sortkey} cmp $a->{$sortkey} } @$runs;
  83. } else {
  84. @$runs = sort { $a->{$sortkey} cmp $b->{$sortkey} } @$runs;
  85. }
  86. return $runs;
  87. }
  88. =head2 getTests(opts,testrail)
  89. Get the tests specified by the options passed.
  90. =over 4
  91. =item HASHREF C<OPTS> - Options for getting the tests
  92. =over 4
  93. =item STRING C<PROJECT> - name of Project to look for tests in
  94. =item STRING C<RUN> - name of Run to get tests from
  95. =item STRING C<PLAN> (optional) - name of Plan to get run from
  96. =item ARRAYREF[STRING] C<CONFIGS> (optional) - names of configs run must satisfy, if part of a plan
  97. =item ARRAYREF[STRING] C<USERS> (optional) - names of users to filter cases by assignee
  98. =item ARRAYREF[STRING] C<STATUSES> (optional) - names of statuses to filter cases by
  99. =back
  100. =back
  101. Returns ARRAYREF of tests, and the run in which they belong.
  102. =cut
  103. sub getTests {
  104. my ($opts,$tr) = @_;
  105. confess("TestRail handle must be provided as argument 2") unless blessed($tr) eq 'TestRail::API';
  106. my (undef,undef,$run) = TestRail::Utils::getRunInformation($tr,$opts);
  107. my ($status_ids,$user_ids);
  108. #Process statuses
  109. @$status_ids = $tr->statusNamesToIds(@{$opts->{'statuses'}}) if $opts->{'statuses'};
  110. #Process assignedto ids
  111. @$user_ids = $tr->userNamesToIds(@{$opts->{'users'}}) if $opts->{'users'};
  112. my $cases = $tr->getTests($run->{'id'},$status_ids,$user_ids);
  113. return ($cases,$run);
  114. }
  115. =head2 findTests(opts,case1,...,caseN)
  116. Given an ARRAY of tests, find tests meeting your criteria (or not) in the specified directory.
  117. =over 4
  118. =item HASHREF C<OPTS> - Options for finding tests:
  119. =over 4
  120. =item STRING C<MATCH> - Only return tests which exist in the path provided, and in TestRail. Mutually exclusive with no-match, orphans.
  121. =item STRING C<NO-MATCH> - Only return tests which are in the path provided, but not in TestRail. Mutually exclusive with match, orphans.
  122. =item STRING C<ORPHANS> - Only return tests which are in TestRail, and not in the path provided. Mutually exclusive with match, no-match
  123. =item BOOL C<NO-RECURSE> - Do not do a recursive scan for files.
  124. =item BOOL C<NAMES-ONLY> - Only return the names of the tests rather than the entire test objects.
  125. =item STRING C<EXTENSION> (optional) - Only return files ending with the provided text (e.g. .t, .test, .pl, .pm)
  126. =item CODE C<FINDER> (optional) - Use the provided sub to get the list of files on disk. Provides the directory & extension based on above options as arguments. Must return list of tests.
  127. =back
  128. =item ARRAY C<CASES> - Array of cases to translate to pathnames based on above options.
  129. =back
  130. Returns tests found that meet the criteria laid out in the options.
  131. Provides absolute path to tests if match is passed; this is the 'full_title' key if names-only is false/undef.
  132. Dies if mutually exclusive options are passed.
  133. =cut
  134. sub findTests {
  135. my ($opts,@cases) = @_;
  136. confess "Error! match and no-match options are mutually exclusive.\n" if ($opts->{'match'} && $opts->{'no-match'});
  137. confess "Error! match and orphans options are mutually exclusive.\n" if ($opts->{'match'} && $opts->{'orphans'});
  138. confess "Error! no-match and orphans options are mutually exclusive.\n" if ($opts->{'orphans'} && $opts->{'no-match'});
  139. my @tests = @cases;
  140. my (@realtests);
  141. my $ext = $opts->{'extension'} // '';
  142. if ($opts->{'match'} || $opts->{'no-match'} || $opts->{'orphans'}) {
  143. my @tmpArr = ();
  144. my $dir = ($opts->{'match'} || $opts->{'orphans'}) ? ($opts->{'match'} || $opts->{'orphans'}) : $opts->{'no-match'};
  145. confess "No such directory '$dir'" if ! -d $dir;
  146. if (ref($opts->{finder}) eq 'CODE') {
  147. @realtests = $opts->{finder}->($dir,$ext)
  148. } else {
  149. if (!$opts->{'no-recurse'}) {
  150. File::Find::find( sub { push(@realtests,$File::Find::name) if -f && m/\Q$ext\E$/ }, $dir );
  151. } else {
  152. @realtests = glob("$dir/*$ext");
  153. }
  154. }
  155. foreach my $case (@cases) {
  156. foreach my $path (@realtests) {
  157. #Filter obviously bogus stuff first to not incur basename() cost except for when we're right, or have a name that contains this name
  158. next unless index($path,$case->{'title'}) > 0;
  159. next unless basename($path) eq $case->{title};
  160. $case->{'path'} = $path;
  161. push(@tmpArr, $case);
  162. last;
  163. }
  164. }
  165. @tmpArr = grep {my $otest = $_; !(grep {$otest->{'title'} eq $_->{'title'}} @tmpArr) } @tests if $opts->{'orphans'};
  166. @tests = @tmpArr;
  167. @tests = map {{'title' => $_}} grep {my $otest = basename($_); scalar(grep {basename($_->{'title'}) eq $otest} @tests) == 0} @realtests if $opts->{'no-match'}; #invert the list in this case.
  168. }
  169. @tests = map { abs_path($_->{'path'}) } @tests if $opts->{'match'} && $opts->{'names-only'};
  170. @tests = map { $_->{'full_title'} = abs_path($_->{'path'}); $_ } @tests if $opts->{'match'} && !$opts->{'names-only'};
  171. @tests = map { $_->{'title'} } @tests if !$opts->{'match'} && $opts->{'names-only'};
  172. return @tests;
  173. }
  174. =head2 getCases
  175. Get cases in a testsuite matching your parameters passed
  176. =cut
  177. sub getCases {
  178. my ($opts,$tr) = @_;
  179. confess("First argument must be instance of TestRail::API") unless blessed($tr) eq 'TestRail::API';
  180. my $project = $tr->getProjectByName($opts->{'project'});
  181. confess "No such project '$opts->{project}'.\n" if !$project;
  182. my $suite = $tr->getTestSuiteByName($project->{'id'},$opts->{'testsuite'});
  183. confess "No such testsuite '$opts->{testsuite}'.\n" if !$suite;
  184. $opts->{'testsuite_id'} = $suite->{'id'};
  185. my $section;
  186. $section = $tr->getSectionByName($project->{'id'},$suite->{'id'},$opts->{'section'}) if $opts->{'section'};
  187. confess "No such section '$opts->{section}.\n" if $opts->{'section'} && !$section;
  188. my $section_id;
  189. $section_id = $section->{'id'} if ref $section eq "HASH";
  190. my $type_ids;
  191. @$type_ids = $tr->typeNamesToIds(@{$opts->{'types'}}) if ref $opts->{'types'} eq 'ARRAY';
  192. #Above will confess if anything's the matter
  193. #TODO Translate opts into filters
  194. my $filters = {
  195. 'section_id' => $section_id,
  196. 'type_id' => $type_ids
  197. };
  198. return $tr->getCases($project->{'id'},$suite->{'id'},$filters);
  199. }
  200. =head2 findCases(opts,@cases)
  201. Find orphan, missing and needing-update cases.
  202. They are returned as the hash keys 'orphans', 'missing', and 'updates' respectively.
  203. The testsuite_id is also returned in the output hashref.
  204. Option hash keys for input are 'no-missing', 'orphans', and 'update'.
  205. Returns HASHREF.
  206. =cut
  207. sub findCases {
  208. my ($opts,@cases) = @_;
  209. confess('testsuite_id parameter mandatory in options HASHREF') unless defined $opts->{'testsuite_id'};
  210. confess('Directory parameter mandatory in options HASHREF.') unless defined $opts->{'directory'};
  211. confess('No such directory "'.$opts->{'directory'}."\"\n") unless -d $opts->{'directory'};
  212. my $ret = {'testsuite_id' => $opts->{'testsuite_id'}};
  213. if (!$opts->{'no-missing'}) {
  214. my $mopts = {
  215. 'no-match' => $opts->{'directory'},
  216. 'names-only' => 1,
  217. 'extension' => $opts->{'extension'}
  218. };
  219. my @missing = findTests($mopts,@cases);
  220. $ret->{'missing'} = \@missing;
  221. }
  222. if ($opts->{'orphans'}) {
  223. my $oopts = {
  224. 'orphans' => $opts->{'directory'},
  225. 'extension' => $opts->{'extension'}
  226. };
  227. my @orphans = findTests($oopts,@cases);
  228. $ret->{'orphans'} = \@orphans;
  229. }
  230. if ($opts->{'update'}) {
  231. my $uopts = {
  232. 'match' => $opts->{'directory'},
  233. 'extension' => $opts->{'extension'}
  234. };
  235. my @updates = findTests($uopts,@cases);
  236. $ret->{'update'} = \@updates;
  237. }
  238. return $ret;
  239. }
  240. =head2 getResults(options, @cases)
  241. Get results for tests by name, filtered by the provided options, and skipping any runs found in the provided ARRAYREF of run IDs.
  242. Probably should have called this findResults, but we all prefer to get results right?
  243. Returns ARRAYREF of results, and an ARRAYREF of seen plan IDs
  244. Valid Options:
  245. =over 4
  246. =item B<plans> - ARRAYREF of plan names to check.
  247. =item B<runs> - ARRAYREF of runs names to check.
  248. =item B<plan_ids> - ARRAYREF of plan IDs to NOT check.
  249. =item B<run_ids> - ARRAYREF of run IDs to NOT check.
  250. =item B<pattern> - Pattern to filter case results on.
  251. =item B<defects> - ARRAYREF of defects of which at least one must be present in a result.
  252. =item B<fast> - Whether to get only the latest result from the test in your run(s). This can significantly speed up operations when gathering metrics for large numbers of tests.
  253. =back
  254. =cut
  255. sub getResults {
  256. my ($tr,$opts,@cases) = @_;
  257. my $res = {};
  258. my $projects = $tr->getProjects();
  259. my (@seenRunIds,@seenPlanIds);
  260. my @results;
  261. #TODO obey status filtering
  262. #TODO obey result notes text grepping
  263. foreach my $project (@$projects) {
  264. next if $opts->{projects} && !( grep { $_ eq $project->{'name'} } @{$opts->{'projects'}} );
  265. my $runs = $tr->getRuns($project->{'id'});
  266. #XXX No runs, or temporary error to ignore
  267. next unless ref($runs) eq 'ARRAY';
  268. push(@seenRunIds, map { $_->{id} } @$runs);
  269. #Translate plan names to ids
  270. my $plans = $tr->getPlans($project->{'id'}) || [];
  271. push(@seenPlanIds, map { $_->{id} } @$plans);
  272. #Filter out plans which do not match our filters to prevent a call to getPlanByID
  273. if ($opts->{'plans'}) {
  274. @$plans = grep { my $p = $_; any { $p->{'name'} eq $_ } @{$opts->{'plans'}} } @$plans;
  275. }
  276. #Filter out runs which do not match our filters
  277. if ($opts->{'runs'}) {
  278. @$runs = grep { my $r = $_; any { $r->{'name'} eq $_ } @{$opts->{'runs'}} } @$runs;
  279. }
  280. #Filter out prior plans
  281. if ($opts->{'plan_ids'}) {
  282. @$plans = grep { my $p = $_; !any { $p->{'id'} eq $_ } @{$opts->{'plan_ids'}} } @$plans;
  283. }
  284. #Filter out prior runs
  285. if ($opts->{'run_ids'}) {
  286. @$runs = grep { my $r = $_; !any { $r->{'id'} eq $_ } @{$opts->{'run_ids'}} } @$runs;
  287. }
  288. $opts->{'runs'} //= [];
  289. foreach my $plan (@$plans) {
  290. $plan = $tr->getPlanByID($plan->{'id'});
  291. my $plan_runs = $tr->getChildRuns($plan);
  292. push(@$runs,@$plan_runs) if $plan_runs;
  293. }
  294. my $configs = $tr->getConfigurations($project->{id});
  295. my %config_map;
  296. @config_map{map {$_->{'id'}} @$configs} = map {$_->{'name'}} @$configs;
  297. MCE::Loop::init {
  298. max_workers => 'auto',
  299. chunk_size => 'auto'
  300. };
  301. push (@results, mce_loop {
  302. my $runz = $_;
  303. #XXX it appears as though some versions of MCE do not have uniform passing convention
  304. $runz = [$runz] if ref($runz) ne 'ARRAY';
  305. my $res = {};
  306. foreach my $run (@$runz) {
  307. #XXX super bad bug in some versions of MCE, apparently causes data loss, or is duping jobs with incomplete info!
  308. next if !$run->{id};
  309. #Translate config ids to names, also remove any gone configs
  310. my @run_configs = grep { defined $_ } map { $config_map{$_} } @{$run->{config_ids}};
  311. next if scalar(@{$opts->{runs}}) && !( grep { $_ eq $run->{'name'} } @{$opts->{'runs'}} );
  312. if ($opts->{fast}) {
  313. my @csz = @cases;
  314. @csz = grep { ref($_) eq 'HASH' } map {
  315. my $cname = basename($_);
  316. my $c = $tr->getTestByName($run->{id},$cname);
  317. $c->{config_ids} = \@run_configs;
  318. $c->{name} = $cname if $c;
  319. $c
  320. } @csz;
  321. next unless scalar(@csz);
  322. my $results = $tr->getRunResults($run->{id});
  323. foreach my $c (@csz) {
  324. $res->{$c->{name}} //= [];
  325. my $cres = first { $c->{id} == $_->{test_id} } @$results;
  326. return unless $cres;
  327. $c->{results} = [$cres];
  328. $c = _filterResults($opts,$c);
  329. push(@{$res->{$c->{name}}}, $c) if scalar(@{$c->{results}});
  330. }
  331. next;
  332. }
  333. foreach my $case (@cases) {
  334. my $c = $tr->getTestByName($run->{'id'},basename($case));
  335. next unless ref $c eq 'HASH';
  336. $res->{$case} //= [];
  337. $c->{results} = $tr->getTestResults($c->{'id'},$tr->{'global_limit'},0);
  338. $c->{config_ids} = \@run_configs;
  339. $c = _filterResults($opts,$c);
  340. push(@{$res->{$case}}, $c) if scalar(@{$c->{results}}); #Make sure they weren't filtered out
  341. }
  342. }
  343. return MCE->gather(MCE->chunk_id,$res);
  344. } $runs);
  345. }
  346. foreach my $result (@results) {
  347. $res = merge($res,$result);
  348. }
  349. return ($res,\@seenPlanIds,\@seenRunIds);
  350. }
  351. sub _filterResults {
  352. my ($opts,$c) = @_;
  353. #Filter by provided pattern, if any
  354. if ($opts->{'pattern'}) {
  355. my $pattern = $opts->{pattern};
  356. @{$c->{results}} = grep { my $comment = $_->{comment} || ''; $comment =~ m/$pattern/i } @{$c->{results}};
  357. }
  358. #Filter by the provided case IDs, if any
  359. if (ref($opts->{'defects'}) eq 'ARRAY' && scalar(@{$opts->{defects}})) {
  360. @{$c->{results}} = grep {
  361. my $defects = $_->{defects};
  362. any {
  363. my $df_case = $_;
  364. any { $df_case eq $_ } @{$opts->{defects}};
  365. } @$defects
  366. } @{$c->{results}};
  367. }
  368. #Filter by the provided versions, if any
  369. if (ref($opts->{'versions'}) eq 'ARRAY' && scalar(@{$opts->{versions}})) {
  370. @{$c->{results}} = grep {
  371. my $version = $_->{version};
  372. any { $version eq $_ } @{$opts->{versions}};
  373. } @{$c->{results}};
  374. }
  375. return $c;
  376. }
  377. 1;
  378. __END__
  379. =head1 SPECIAL THANKS
  380. Thanks to cPanel Inc, for graciously funding the creation of this module.