API.pm 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519
  1. # ABSTRACT: Provides an interface to TestRail's REST api via HTTP
  2. # PODNAME: TestRail::API
  3. package TestRail::API;
  4. =head1 SYNOPSIS
  5. use TestRail::API;
  6. my ($username,$password,$host) = ('foo','bar','http://testrail.baz.foo');
  7. my $tr = TestRail::API->new($host, $username, $password);
  8. =head1 DESCRIPTION
  9. C<TestRail::API> provides methods to access an existing TestRail account using API v2. You can then do things like look up tests, set statuses and create runs from lists of cases.
  10. It is by no means exhaustively implementing every TestRail API function.
  11. =head1 IMPORTANT
  12. All the methods aside from the constructor should not die, but return a false value upon failure.
  13. When the server is not responsive, expect a -500 response, and retry accordingly.
  14. I recommend using the excellent L<Attempt> module for this purpose.
  15. Also, all *ByName methods are vulnerable to duplicate naming issues. Try not to use the same name for:
  16. * projects
  17. * testsuites within the same project
  18. * sections within the same testsuite that are peers
  19. * test cases
  20. * test plans and runs outside of plans which are not completed
  21. To do so will result in the first of said item found being returned rather than an array of possibilities to choose from.
  22. =cut
  23. use 5.010;
  24. use strict;
  25. use warnings;
  26. use Carp qw{cluck confess};
  27. use Scalar::Util qw{reftype looks_like_number};
  28. use Clone 'clone';
  29. use Try::Tiny;
  30. use Types::Standard qw( slurpy ClassName Object Str Int Bool HashRef ArrayRef Maybe Optional);
  31. use Type::Params qw( compile );
  32. use JSON::MaybeXS 1.001000 ();
  33. use HTTP::Request;
  34. use LWP::UserAgent;
  35. use Data::Validate::URI qw{is_uri};
  36. use List::Util 1.33;
  37. use Encode ();
  38. =head1 CONSTRUCTOR
  39. =head2 B<new (api_url, user, password, encoding, debug)>
  40. Creates new C<TestRail::API> object.
  41. =over 4
  42. =item STRING C<API URL> - base url for your TestRail api server.
  43. =item STRING C<USER> - Your TestRail User.
  44. =item STRING C<PASSWORD> - Your TestRail password, or a valid API key (TestRail 4.2 and above).
  45. =item STRING C<ENCODING> - The character encoding used by the caller. Defaults to 'UTF-8', see L<Encode::Supported> and for supported encodings.
  46. =item BOOLEAN C<DEBUG> (optional) - Print the JSON responses from TL with your requests. Default false.
  47. =back
  48. Returns C<TestRail::API> object if login is successful.
  49. my $tr = TestRail::API->new('http://tr.test/testrail', 'moo','M000000!');
  50. Dies on all communication errors with the TestRail server.
  51. Does not do above checks if debug is passed.
  52. =cut
  53. sub new {
  54. state $check = compile(ClassName, Str, Str, Str, Optional[Maybe[Str]], Optional[Maybe[Bool]]);
  55. my ($class,$apiurl,$user,$pass,$encoding,$debug) = $check->(@_);
  56. confess("Invalid URI passed to constructor") if !is_uri($apiurl);
  57. $debug //= 0;
  58. my $self = {
  59. user => $user,
  60. pass => $pass,
  61. apiurl => $apiurl,
  62. debug => $debug,
  63. encoding => $encoding || 'UTF-8',
  64. testtree => [],
  65. flattree => [],
  66. user_cache => [],
  67. configurations => {},
  68. tr_fields => undef,
  69. default_request => undef,
  70. global_limit => 250, #Discovered by experimentation
  71. browser => new LWP::UserAgent()
  72. };
  73. #Check chara encoding
  74. $self->{'encoding-nonaliased'} = Encode::resolve_alias($self->{'encoding'});
  75. confess("Invalid encoding alias '".$self->{'encoding'}."' passed, see Encoding::Supported for a list of allowed encodings")
  76. unless $self->{'encoding-nonaliased'};
  77. confess("Invalid encoding '".$self->{'encoding-nonaliased'}."' passed, see Encoding::Supported for a list of allowed encodings")
  78. unless grep {$_ eq $self->{'encoding-nonaliased'}} (Encode->encodings(":all"));
  79. #Create default request to pass on to LWP::UserAgent
  80. $self->{'default_request'} = new HTTP::Request();
  81. $self->{'default_request'}->authorization_basic($user,$pass);
  82. bless( $self, $class );
  83. return $self if $self->debug; #For easy class testing without mocks
  84. #Manually do the get_users call to check HTTP status
  85. my $res = $self->_doRequest('index.php?/api/v2/get_users');
  86. confess "Error: network unreachable" if !defined($res);
  87. if ( (reftype($res) || 'undef') ne 'ARRAY') {
  88. confess "Unexpected return from _doRequest: $res" if !looks_like_number($res);
  89. confess "Could not communicate with TestRail Server! Check that your URI is correct, and your TestRail installation is functioning correctly." if $res == -500;
  90. confess "Could not list testRail users! Check that your TestRail installation has it's API enabled, and your credentials are correct" if $res == -403;
  91. confess "Bad user credentials!" if $res == -401;
  92. confess "HTTP error $res encountered while communicating with TestRail server. Resolve issue and try again." if !$res;
  93. confess "Unknown error occurred: $res";
  94. }
  95. confess "No users detected on TestRail Install! Check that your API is functioning correctly." if !scalar(@$res);
  96. $self->{'user_cache'} = $res;
  97. return $self;
  98. }
  99. =head1 GETTERS
  100. =head2 B<apiurl>
  101. =head2 B<debug>
  102. Accessors for these parameters you pass into the constructor, in case you forget.
  103. =cut
  104. sub apiurl {
  105. state $check = compile(Object);
  106. my ($self) = $check->(@_);
  107. return $self->{'apiurl'}
  108. }
  109. sub debug {
  110. state $check = compile(Object);
  111. my ($self) = $check->(@_);
  112. return $self->{'debug'};
  113. }
  114. #Convenient JSON-HTTP fetcher
  115. sub _doRequest {
  116. state $check = compile(Object, Str, Optional[Maybe[Str]], Optional[Maybe[HashRef]]);
  117. my ($self,$path,$method,$data) = $check->(@_);
  118. my $req = clone $self->{'default_request'};
  119. $method //= 'GET';
  120. $req->method($method);
  121. $req->url($self->apiurl.'/'.$path);
  122. warn "$method ".$self->apiurl."/$path" if $self->debug;
  123. my $coder = JSON::MaybeXS->new;
  124. #Data sent is JSON, and encoded per user preference
  125. my $content = $data ? Encode::encode( $self->{'encoding-nonaliased'}, $coder->encode($data) ) : '';
  126. $req->content($content);
  127. $req->header( "Content-Type" => "application/json; charset=".$self->{'encoding'} );
  128. my $response = $self->{'browser'}->request($req);
  129. #Uncomment to generate mocks
  130. #use Data::Dumper;
  131. #open(my $fh, '>>', 'mock.out');
  132. #print $fh "{\n\n";
  133. #print $fh Dumper($path,'200','OK',$response->headers,$response->content);
  134. #print $fh '$mockObject->map_response(qr/\Q$VAR1\E/,HTTP::Response->new($VAR2, $VAR3, $VAR4, $VAR5));';
  135. #print $fh "\n\n}\n\n";
  136. #close $fh;
  137. return $response if !defined($response); #worst case
  138. if ($response->code == 403) {
  139. cluck "ERROR: Access Denied.";
  140. return -403;
  141. }
  142. if ($response->code != 200) {
  143. cluck "ERROR: Arguments Bad: ".$response->content;
  144. return -int($response->code);
  145. }
  146. try {
  147. return $coder->decode($response->content);
  148. } catch {
  149. if ($response->code == 200 && !$response->content) {
  150. return 1; #This function probably just returns no data
  151. } else {
  152. cluck "ERROR: Malformed JSON returned by API.";
  153. cluck $@;
  154. if (!$self->debug) { #Otherwise we've already printed this, but we need to know if we encounter this
  155. cluck "RAW CONTENT:";
  156. cluck $response->content
  157. }
  158. return 0;
  159. }
  160. }
  161. }
  162. =head1 USER METHODS
  163. =head2 B<getUsers ()>
  164. Get all the user definitions for the provided Test Rail install.
  165. Returns ARRAYREF of user definition HASHREFs.
  166. =cut
  167. sub getUsers {
  168. state $check = compile(Object);
  169. my ($self) = $check->(@_);
  170. my $res = $self->_doRequest('index.php?/api/v2/get_users');
  171. return -500 if !$res || (reftype($res) || 'undef') ne 'ARRAY';
  172. $self->{'user_cache'} = $res;
  173. return $res;
  174. }
  175. =head2 B<getUserByID(id)>
  176. =cut
  177. =head2 B<getUserByName(name)>
  178. =cut
  179. =head2 B<getUserByEmail(email)>
  180. Get user definition hash by ID, Name or Email.
  181. Returns user def HASHREF.
  182. =cut
  183. #I'm just using the cache for the following methods because it's more straightforward and faster past 1 call.
  184. sub getUserByID {
  185. state $check = compile(Object, Int);
  186. my ($self,$user) = $check->(@_);
  187. $self->getUsers() if !defined($self->{'user_cache'});
  188. return -500 if (!defined($self->{'user_cache'}) || (reftype($self->{'user_cache'}) || 'undef') ne 'ARRAY');
  189. foreach my $usr (@{$self->{'user_cache'}}) {
  190. return $usr if $usr->{'id'} == $user;
  191. }
  192. return 0;
  193. }
  194. sub getUserByName {
  195. state $check = compile(Object, Str);
  196. my ($self,$user) = $check->(@_);
  197. $self->getUsers() if !defined($self->{'user_cache'});
  198. return -500 if (!defined($self->{'user_cache'}) || (reftype($self->{'user_cache'}) || 'undef') ne 'ARRAY');
  199. foreach my $usr (@{$self->{'user_cache'}}) {
  200. return $usr if $usr->{'name'} eq $user;
  201. }
  202. return 0;
  203. }
  204. sub getUserByEmail {
  205. state $check = compile(Object, Str);
  206. my ($self,$email) = $check->(@_);
  207. $self->getUsers() if !defined($self->{'user_cache'});
  208. return -500 if (!defined($self->{'user_cache'}) || (reftype($self->{'user_cache'}) || 'undef') ne 'ARRAY');
  209. foreach my $usr (@{$self->{'user_cache'}}) {
  210. return $usr if $usr->{'email'} eq $email;
  211. }
  212. return 0;
  213. }
  214. =head2 userNamesToIds(names)
  215. Convenience method to translate a list of user names to TestRail user IDs.
  216. =over 4
  217. =item ARRAY C<NAMES> - Array of user names to translate to IDs.
  218. =back
  219. Returns ARRAY of user IDs.
  220. Throws an exception in the case of one (or more) of the names not corresponding to a valid username.
  221. =cut
  222. sub userNamesToIds {
  223. state $check = compile(Object, slurpy ArrayRef[Str]);
  224. my ($self,$names) = $check->(@_);
  225. confess("At least one user name must be provided") if !scalar(@$names);
  226. my @ret = grep {defined $_} map {my $user = $_; my @list = grep {$user->{'name'} eq $_} @$names; scalar(@list) ? $user->{'id'} : undef} @{$self->getUsers()};
  227. confess("One or more user names provided does not exist in TestRail.") unless scalar(@$names) == scalar(@ret);
  228. return @ret;
  229. };
  230. =head1 PROJECT METHODS
  231. =head2 B<createProject (name, [description,send_announcement])>
  232. Creates new Project (Database of testsuites/tests).
  233. Optionally specify an announcement to go out to the users.
  234. Requires TestRail admin login.
  235. =over 4
  236. =item STRING C<NAME> - Desired name of project.
  237. =item STRING C<DESCRIPTION> (optional) - Description of project. Default value is 'res ipsa loquiter'.
  238. =item BOOLEAN C<SEND ANNOUNCEMENT> (optional) - Whether to confront users with an announcement about your awesome project on next login. Default false.
  239. =back
  240. Returns project definition HASHREF on success, false otherwise.
  241. $tl->createProject('Widgetronic 4000', 'Tests for the whiz-bang new product', true);
  242. =cut
  243. sub createProject {
  244. state $check = compile(Object, Str, Optional[Maybe[Str]], Optional[Maybe[Bool]]);
  245. my ($self,$name,$desc,$announce) = $check->(@_);
  246. $desc //= 'res ipsa loquiter';
  247. $announce //= 0;
  248. my $input = {
  249. name => $name,
  250. announcement => $desc,
  251. show_announcement => $announce
  252. };
  253. return $self->_doRequest('index.php?/api/v2/add_project','POST',$input);
  254. }
  255. =head2 B<deleteProject (id)>
  256. Deletes specified project by ID.
  257. Requires TestRail admin login.
  258. =over 4
  259. =item STRING C<NAME> - Desired name of project.
  260. =back
  261. Returns BOOLEAN.
  262. $success = $tl->deleteProject(1);
  263. =cut
  264. sub deleteProject {
  265. state $check = compile(Object, Int);
  266. my ($self,$proj) = $check->(@_);
  267. return $self->_doRequest('index.php?/api/v2/delete_project/'.$proj,'POST');
  268. }
  269. =head2 B<getProjects ()>
  270. Get all available projects
  271. Returns array of project definition HASHREFs, false otherwise.
  272. $projects = $tl->getProjects;
  273. =cut
  274. sub getProjects {
  275. state $check = compile(Object);
  276. my ($self) = $check->(@_);
  277. my $result = $self->_doRequest('index.php?/api/v2/get_projects');
  278. #Save state for future use, if needed
  279. return -500 if !$result || (reftype($result) || 'undef') ne 'ARRAY';
  280. $self->{'testtree'} = $result;
  281. #Note that it's a project for future reference by recursive tree search
  282. return -500 if !$result || (reftype($result) || 'undef') ne 'ARRAY';
  283. foreach my $pj (@{$result}) {
  284. $pj->{'type'} = 'project';
  285. }
  286. return $result;
  287. }
  288. =head2 B<getProjectByName ($project)>
  289. Gets some project definition hash by it's name
  290. =over 4
  291. =item STRING C<PROJECT> - desired project
  292. =back
  293. Returns desired project def HASHREF, false otherwise.
  294. $project = $tl->getProjectByName('FunProject');
  295. =cut
  296. sub getProjectByName {
  297. state $check = compile(Object, Str);
  298. my ($self,$project) = $check->(@_);
  299. #See if we already have the project list...
  300. my $projects = $self->{'testtree'};
  301. return -500 if !$projects || (reftype($projects) || 'undef') ne 'ARRAY';
  302. $projects = $self->getProjects() unless scalar(@$projects);
  303. #Search project list for project
  304. return -500 if !$projects || (reftype($projects) || 'undef') ne 'ARRAY';
  305. for my $candidate (@$projects) {
  306. return $candidate if ($candidate->{'name'} eq $project);
  307. }
  308. return 0;
  309. }
  310. =head2 B<getProjectByID ($project)>
  311. Gets some project definition hash by it's ID
  312. =over 4
  313. =item INTEGER C<PROJECT> - desired project
  314. =back
  315. Returns desired project def HASHREF, false otherwise.
  316. $projects = $tl->getProjectByID(222);
  317. =cut
  318. sub getProjectByID {
  319. state $check = compile(Object, Int);
  320. my ($self,$project) = $check->(@_);
  321. #See if we already have the project list...
  322. my $projects = $self->{'testtree'};
  323. $projects = $self->getProjects() unless scalar(@$projects);
  324. #Search project list for project
  325. return -500 if !$projects || (reftype($projects) || 'undef') ne 'ARRAY';
  326. for my $candidate (@$projects) {
  327. return $candidate if ($candidate->{'id'} eq $project);
  328. }
  329. return 0;
  330. }
  331. =head1 TESTSUITE METHODS
  332. =head2 B<createTestSuite (project_id, name, [description])>
  333. Creates new TestSuite (folder of tests) in the database of test specifications under given project id having given name and details.
  334. =over 4
  335. =item INTEGER C<PROJECT ID> - ID of project this test suite should be under.
  336. =item STRING C<NAME> - Desired name of test suite.
  337. =item STRING C<DESCRIPTION> (optional) - Description of test suite. Default value is 'res ipsa loquiter'.
  338. =back
  339. Returns TS definition HASHREF on success, false otherwise.
  340. $tl->createTestSuite(1, 'broken tests', 'Tests that should be reviewed');
  341. =cut
  342. sub createTestSuite {
  343. state $check = compile(Object, Int, Str, Optional[Maybe[Str]]);
  344. my ($self,$project_id,$name,$details) = $check->(@_);
  345. $details //= 'res ipsa loquiter';
  346. my $input = {
  347. name => $name,
  348. description => $details
  349. };
  350. return $self->_doRequest('index.php?/api/v2/add_suite/'.$project_id,'POST',$input);
  351. }
  352. =head2 B<deleteTestSuite (suite_id)>
  353. Deletes specified testsuite.
  354. =over 4
  355. =item INTEGER C<SUITE ID> - ID of testsuite to delete.
  356. =back
  357. Returns BOOLEAN.
  358. $tl->deleteTestSuite(1);
  359. =cut
  360. sub deleteTestSuite {
  361. state $check = compile(Object, Int);
  362. my ($self,$suite_id) = $check->(@_);
  363. return $self->_doRequest('index.php?/api/v2/delete_suite/'.$suite_id,'POST');
  364. }
  365. =head2 B<getTestSuites (project_id)>
  366. Gets the testsuites for a project
  367. =over 4
  368. =item STRING C<PROJECT ID> - desired project's ID
  369. =back
  370. Returns ARRAYREF of testsuite definition HASHREFs, 0 on error.
  371. $suites = $tl->getTestSuites(123);
  372. =cut
  373. sub getTestSuites {
  374. state $check = compile(Object, Int);
  375. my ($self,$proj) = $check->(@_);
  376. return $self->_doRequest('index.php?/api/v2/get_suites/'.$proj);
  377. }
  378. =head2 B<getTestSuiteByName (project_id,testsuite_name)>
  379. Gets the testsuite that matches the given name inside of given project.
  380. =over 4
  381. =item STRING C<PROJECT ID> - ID of project holding this testsuite
  382. =item STRING C<TESTSUITE NAME> - desired parent testsuite name
  383. =back
  384. Returns desired testsuite definition HASHREF, false otherwise.
  385. $suites = $tl->getTestSuitesByName(321, 'hugSuite');
  386. =cut
  387. sub getTestSuiteByName {
  388. state $check = compile(Object, Int, Str);
  389. my ($self,$project_id,$testsuite_name) = $check->(@_);
  390. #TODO cache
  391. my $suites = $self->getTestSuites($project_id);
  392. return -500 if !$suites || (reftype($suites) || 'undef') ne 'ARRAY'; #No suites for project, or no project
  393. foreach my $suite (@$suites) {
  394. return $suite if $suite->{'name'} eq $testsuite_name;
  395. }
  396. return 0; #Couldn't find it
  397. }
  398. =head2 B<getTestSuiteByID (testsuite_id)>
  399. Gets the testsuite with the given ID.
  400. =over 4
  401. =item STRING C<TESTSUITE_ID> - TestSuite ID.
  402. =back
  403. Returns desired testsuite definition HASHREF, false otherwise.
  404. $tests = $tl->getTestSuiteByID(123);
  405. =cut
  406. sub getTestSuiteByID {
  407. state $check = compile(Object, Int);
  408. my ($self,$testsuite_id) = $check->(@_);
  409. return $self->_doRequest('index.php?/api/v2/get_suite/'.$testsuite_id);
  410. }
  411. =head1 SECTION METHODS
  412. =head2 B<createSection(project_id,suite_id,name,[parent_id])>
  413. Creates a section.
  414. =over 4
  415. =item INTEGER C<PROJECT ID> - Parent Project ID.
  416. =item INTEGER C<SUITE ID> - Parent TestSuite ID.
  417. =item STRING C<NAME> - desired section name.
  418. =item INTEGER C<PARENT ID> (optional) - parent section id
  419. =back
  420. Returns new section definition HASHREF, false otherwise.
  421. $section = $tr->createSection(1,1,'nugs',1);
  422. =cut
  423. sub createSection {
  424. state $check = compile(Object, Int, Int, Str, Optional[Maybe[Int]]);
  425. my ($self,$project_id,$suite_id,$name,$parent_id) = $check->(@_);
  426. my $input = {
  427. name => $name,
  428. suite_id => $suite_id
  429. };
  430. $input->{'parent_id'} = $parent_id if $parent_id;
  431. return $self->_doRequest('index.php?/api/v2/add_section/'.$project_id,'POST',$input);
  432. }
  433. =head2 B<deleteSection (section_id)>
  434. Deletes specified section.
  435. =over 4
  436. =item INTEGER C<SECTION ID> - ID of section to delete.
  437. =back
  438. Returns BOOLEAN.
  439. $tr->deleteSection(1);
  440. =cut
  441. sub deleteSection {
  442. state $check = compile(Object, Int);
  443. my ($self,$section_id) = $check->(@_);
  444. return $self->_doRequest('index.php?/api/v2/delete_section/'.$section_id,'POST');
  445. }
  446. =head2 B<getSections (project_id,suite_id)>
  447. Gets sections for a given project and suite.
  448. =over 4
  449. =item INTEGER C<PROJECT ID> - ID of parent project.
  450. =item INTEGER C<SUITE ID> - ID of suite to get sections for.
  451. =back
  452. Returns ARRAYREF of section definition HASHREFs.
  453. $tr->getSections(1,2);
  454. =cut
  455. sub getSections {
  456. state $check = compile(Object, Int, Int);
  457. my ($self,$project_id,$suite_id) = $check->(@_);
  458. #Cache sections to reduce requests in tight loops
  459. return $self->{'sections'}->{$project_id} if $self->{'sections'}->{$project_id};
  460. $self->{'sections'}->{$project_id} = $self->_doRequest("index.php?/api/v2/get_sections/$project_id&suite_id=$suite_id");
  461. return $self->{'sections'}->{$project_id};
  462. }
  463. =head2 B<getSectionByID (section_id)>
  464. Gets desired section.
  465. =over 4
  466. =item INTEGER C<PROJECT ID> - ID of parent project.
  467. =item INTEGER C<SUITE ID> - ID of suite to get sections for.
  468. =back
  469. Returns section definition HASHREF.
  470. $tr->getSectionByID(344);
  471. =cut
  472. sub getSectionByID {
  473. state $check = compile(Object, Int);
  474. my ($self,$section_id) = $check->(@_);
  475. return $self->_doRequest("index.php?/api/v2/get_section/$section_id");
  476. }
  477. =head2 B<getSectionByName (project_id,suite_id,name)>
  478. Gets desired section.
  479. =over 4
  480. =item INTEGER C<PROJECT ID> - ID of parent project.
  481. =item INTEGER C<SUITE ID> - ID of suite to get section for.
  482. =item STRING C<NAME> - name of section to get
  483. =back
  484. Returns section definition HASHREF.
  485. $tr->getSectionByName(1,2,'nugs');
  486. =cut
  487. sub getSectionByName {
  488. state $check = compile(Object, Int, Int, Str);
  489. my ($self,$project_id,$suite_id,$section_name) = $check->(@_);
  490. my $sections = $self->getSections($project_id,$suite_id);
  491. return -500 if !$sections || (reftype($sections) || 'undef') ne 'ARRAY';
  492. foreach my $sec (@$sections) {
  493. return $sec if $sec->{'name'} eq $section_name;
  494. }
  495. return 0;
  496. }
  497. =head2 B<getChildSections ($project_id, section)>
  498. Gets desired section's child sections.
  499. =over 4
  500. =item INTEGER C<PROJECT_ID> - parent project ID of section.
  501. =item HASHREF C<SECTION> - section definition HASHREF.
  502. =back
  503. Returns ARRAYREF of section definition HASHREF. ARRAYREF is empty if there are none.
  504. Recursively searches for children, so the children of child sections will be returned as well.
  505. $tr->getChildSections($section);
  506. =cut
  507. sub getChildSections {
  508. state $check = compile(Object, Int, HashRef);
  509. my ($self, $project_id, $section) = $check->(@_);
  510. my $sections_orig = $self->getSections($project_id,$section->{suite_id});
  511. return [] if !$sections_orig || (reftype($sections_orig) || 'undef') ne 'ARRAY';
  512. my @sections = grep { $_->{'parent_id'} ? $_->{'parent_id'} == $section->{'id'} : 0 } @$sections_orig;
  513. foreach my $sec (@sections) {
  514. push(@sections, grep { $_->{'parent_id'} ? $_->{'parent_id'} == $sec->{'id'} : 0 } @$sections_orig);
  515. }
  516. return \@sections;
  517. }
  518. =head2 sectionNamesToIds(project_id,suite_id,names)
  519. Convenience method to translate a list of section names to TestRail section IDs.
  520. =over 4
  521. =item INTEGER C<PROJECT ID> - ID of parent project.
  522. =item INTEGER C<SUITE ID> - ID of parent suite.
  523. =item ARRAY C<NAMES> - Array of section names to translate to IDs.
  524. =back
  525. Returns ARRAY of section IDs.
  526. Throws an exception in the case of one (or more) of the names not corresponding to a valid section name.
  527. =cut
  528. sub sectionNamesToIds {
  529. my ($self,$project_id,$suite_id,@names) = @_;
  530. my $sections = $self->getSections($project_id,$suite_id) or confess("Could not find sections in provided project/suite.");
  531. return _X_in_my_Y($self,$sections,'id',@names);
  532. }
  533. =head1 CASE METHODS
  534. =head2 B<getCaseTypes ()>
  535. Gets possible case types.
  536. Returns ARRAYREF of case type definition HASHREFs.
  537. $tr->getCaseTypes();
  538. =cut
  539. sub getCaseTypes {
  540. state $check = compile(Object);
  541. my ($self) = $check->(@_);
  542. return $self->{'type_cache'} if defined($self->{'type_cache'});
  543. my $types = $self->_doRequest("index.php?/api/v2/get_case_types");
  544. return -500 if !$types || (reftype($types) || 'undef') ne 'ARRAY';
  545. $self->{'type_cache'} = $types;
  546. return $types;
  547. }
  548. =head2 B<getCaseTypeByName (name)>
  549. Gets case type by name.
  550. =over 4
  551. =item STRING C<NAME> - Name of desired case type
  552. =back
  553. Returns case type definition HASHREF.
  554. Dies if named case type does not exist.
  555. $tr->getCaseTypeByName();
  556. =cut
  557. sub getCaseTypeByName {
  558. state $check = compile(Object, Str);
  559. my ($self,$name) = $check->(@_);
  560. my $types = $self->getCaseTypes();
  561. return -500 if !$types || (reftype($types) || 'undef') ne 'ARRAY';
  562. foreach my $type (@$types) {
  563. return $type if $type->{'name'} eq $name;
  564. }
  565. confess("No such case type '$name'!");
  566. }
  567. =head2 typeNamesToIds(names)
  568. Convenience method to translate a list of case type names to TestRail case type IDs.
  569. =over 4
  570. =item ARRAY C<NAMES> - Array of status names to translate to IDs.
  571. =back
  572. Returns ARRAY of type IDs in the same order as the type names passed.
  573. Throws an exception in the case of one (or more) of the names not corresponding to a valid case type.
  574. =cut
  575. sub typeNamesToIds {
  576. my ($self,@names) = @_;
  577. return _X_in_my_Y($self,$self->getCaseTypes(),'id',@names);
  578. };
  579. =head2 B<createCase(section_id,title,type_id,options,extra_options)>
  580. Creates a test case.
  581. =over 4
  582. =item INTEGER C<SECTION ID> - Parent Section ID.
  583. =item STRING C<TITLE> - Case title.
  584. =item INTEGER C<TYPE_ID> (optional) - desired test type's ID. Defaults to whatever your TR install considers the default type.
  585. =item HASHREF C<OPTIONS> (optional) - Custom fields in the case are the keys, set to the values provided. See TestRail API documentation for more info.
  586. =item HASHREF C<EXTRA OPTIONS> (optional) - contains priority_id, estimate, milestone_id and refs as possible keys. See TestRail API documentation for more info.
  587. =back
  588. Returns new case definition HASHREF, false otherwise.
  589. $custom_opts = {
  590. preconds => "Test harness installed",
  591. steps => "Do the needful",
  592. expected => "cubicle environment transforms into Dali painting"
  593. };
  594. $other_opts = {
  595. priority_id => 4,
  596. milestone_id => 666,
  597. estimate => '2m 45s',
  598. refs => ['TRACE-22','ON-166'] #ARRAYREF of bug IDs.
  599. }
  600. $case = $tr->createCase(1,'Do some stuff',3,$custom_opts,$other_opts);
  601. =cut
  602. sub createCase {
  603. state $check = compile(Object, Int, Str, Optional[Maybe[Int]], Optional[Maybe[HashRef]], Optional[Maybe[HashRef]]);
  604. my ($self,$section_id,$title,$type_id,$opts,$extras) = $check->(@_);
  605. my $stuff = {
  606. title => $title,
  607. type_id => $type_id
  608. };
  609. #Handle sort of optional but baked in options
  610. if (defined($extras) && reftype($extras) eq 'HASH') {
  611. $stuff->{'priority_id'} = $extras->{'priority_id'} if defined($extras->{'priority_id'});
  612. $stuff->{'estimate'} = $extras->{'estimate'} if defined($extras->{'estimate'});
  613. $stuff->{'milestone_id'} = $extras->{'milestone_id'} if defined($extras->{'milestone_id'});
  614. $stuff->{'refs'} = join(',',@{$extras->{'refs'}}) if defined($extras->{'refs'});
  615. }
  616. #Handle custom fields
  617. if (defined($opts) && reftype($opts) eq 'HASH') {
  618. foreach my $key (keys(%$opts)) {
  619. $stuff->{"custom_$key"} = $opts->{$key};
  620. }
  621. }
  622. return $self->_doRequest("index.php?/api/v2/add_case/$section_id",'POST',$stuff);
  623. }
  624. =head2 B<updateCase(case_id,options)>
  625. Updates a test case.
  626. =over 4
  627. =item INTEGER C<CASE ID> - Case ID.
  628. =item HASHREF C<OPTIONS> - Various things about a case to set. Everything except section_id in the output of getCaseBy* methods is a valid input here.
  629. =back
  630. Returns new case definition HASHREF, false otherwise.
  631. =cut
  632. sub updateCase {
  633. state $check = compile(Object, Int, Optional[Maybe[HashRef]]);
  634. my ($self,$case_id,$options) = $check->(@_);
  635. return $self->_doRequest("index.php?/api/v2/update_case/$case_id",'POST',$options);
  636. }
  637. =head2 B<deleteCase (case_id)>
  638. Deletes specified test case.
  639. =over 4
  640. =item INTEGER C<CASE ID> - ID of case to delete.
  641. =back
  642. Returns BOOLEAN.
  643. $tr->deleteCase(1324);
  644. =cut
  645. sub deleteCase {
  646. state $check = compile(Object, Int);
  647. my ($self,$case_id) = $check->(@_);
  648. return $self->_doRequest("index.php?/api/v2/delete_case/$case_id",'POST');
  649. }
  650. =head2 B<getCases (project_id,suite_id,filters)>
  651. Gets cases for provided section.
  652. =over 4
  653. =item INTEGER C<PROJECT ID> - ID of parent project.
  654. =item INTEGER C<SUITE ID> - ID of parent suite.
  655. =item HASHREF C<FILTERS> (optional) - HASHREF describing parameters to filter cases by.
  656. =back
  657. See:
  658. L<http://docs.gurock.com/testrail-api2/reference-cases#get_cases>
  659. for details as to the allowable filter keys.
  660. If the section ID is omitted, all cases for the suite will be returned.
  661. Returns ARRAYREF of test case definition HASHREFs.
  662. $tr->getCases(1,2, {'section_id' => 3} );
  663. =cut
  664. sub getCases {
  665. state $check = compile(Object, Int, Int, Optional[Maybe[HashRef]]);
  666. my ($self,$project_id,$suite_id,$filters) = $check->(@_);
  667. my $url = "index.php?/api/v2/get_cases/$project_id&suite_id=$suite_id";
  668. my @valid_keys = qw{section_id created_after created_before created_by milestone_id priority_id type_id updated_after updated_before updated_by};
  669. # Add in filters
  670. foreach my $filter (keys(%$filters)) {
  671. confess("Invalid filter key '$filter' passed") unless grep {$_ eq $filter} @valid_keys;
  672. if (ref $filters->{$filter} eq 'ARRAY') {
  673. confess "$filter cannot be an ARRAYREF" if grep {$_ eq $filter} qw{created_after created_before updated_after updated_before};
  674. $url .= "&$filter=".join(',',@{$filters->{$filter}});
  675. } else {
  676. $url .= "&$filter=".$filters->{$filter} if defined($filters->{$filter});
  677. }
  678. }
  679. return $self->_doRequest($url);
  680. }
  681. =head2 B<getCaseByName (project_id,suite_id,name,filters)>
  682. Gets case by name.
  683. =over 4
  684. =item INTEGER C<PROJECT ID> - ID of parent project.
  685. =item INTEGER C<SUITE ID> - ID of parent suite.
  686. =item STRING C<NAME> - Name of desired test case.
  687. =item HASHREF C<FILTERS> - Filter dictionary acceptable to getCases.
  688. =back
  689. Returns test case definition HASHREF.
  690. $tr->getCaseByName(1,2,'nugs', {'section_id' => 3});
  691. =cut
  692. sub getCaseByName {
  693. state $check = compile(Object, Int, Int, Str, Optional[Maybe[HashRef]]);
  694. my ($self,$project_id,$suite_id,$name,$filters) = $check->(@_);
  695. my $cases = $self->getCases($project_id,$suite_id,$filters);
  696. return -500 if !$cases || (reftype($cases) || 'undef') ne 'ARRAY';
  697. foreach my $case (@$cases) {
  698. return $case if $case->{'title'} eq $name;
  699. }
  700. return 0;
  701. }
  702. =head2 B<getCaseByID (case_id)>
  703. Gets case by ID.
  704. =over 4
  705. =item INTEGER C<CASE ID> - ID of case.
  706. =back
  707. Returns test case definition HASHREF.
  708. $tr->getCaseByID(1345);
  709. =cut
  710. sub getCaseByID {
  711. state $check = compile(Object, Int);
  712. my ($self,$case_id) = $check->(@_);
  713. return $self->_doRequest("index.php?/api/v2/get_case/$case_id");
  714. }
  715. =head1 RUN METHODS
  716. =head2 B<createRun (project_id,suite_id,name,description,milestone_id,assigned_to_id,case_ids)>
  717. Create a run.
  718. =over 4
  719. =item INTEGER C<PROJECT ID> - ID of parent project.
  720. =item INTEGER C<SUITE ID> - ID of suite to base run on
  721. =item STRING C<NAME> - Name of run
  722. =item STRING C<DESCRIPTION> (optional) - Description of run
  723. =item INTEGER C<MILESTONE ID> (optional) - ID of milestone
  724. =item INTEGER C<ASSIGNED TO ID> (optional) - User to assign the run to
  725. =item ARRAYREF C<CASE IDS> (optional) - Array of case IDs in case you don't want to use the whole testsuite when making the build.
  726. =back
  727. Returns run definition HASHREF.
  728. $tr->createRun(1,1345,'RUN AWAY','SO FAR AWAY',22,3,[3,4,5,6]);
  729. =cut
  730. #If you pass an array of case ids, it implies include_all is false
  731. sub createRun {
  732. state $check = compile(Object, Int, Int, Str, Optional[Maybe[Str]], Optional[Maybe[Int]], Optional[Maybe[Int]], Optional[Maybe[ArrayRef[Int]]]);
  733. my ($self,$project_id,$suite_id,$name,$desc,$milestone_id,$assignedto_id,$case_ids) = $check->(@_);
  734. my $stuff = {
  735. suite_id => $suite_id,
  736. name => $name,
  737. description => $desc,
  738. milestone_id => $milestone_id,
  739. assignedto_id => $assignedto_id,
  740. include_all => defined($case_ids) ? 0 : 1,
  741. case_ids => $case_ids
  742. };
  743. return $self->_doRequest("index.php?/api/v2/add_run/$project_id",'POST',$stuff);
  744. }
  745. =head2 B<deleteRun (run_id)>
  746. Deletes specified run.
  747. =over 4
  748. =item INTEGER C<RUN ID> - ID of run to delete.
  749. =back
  750. Returns BOOLEAN.
  751. $tr->deleteRun(1324);
  752. =cut
  753. sub deleteRun {
  754. state $check = compile(Object, Int);
  755. my ($self,$run_id) = $check->(@_);
  756. return $self->_doRequest("index.php?/api/v2/delete_run/$run_id",'POST');
  757. }
  758. =head2 B<getRuns (project_id)>
  759. Get all runs for specified project.
  760. To do this, it must make (no. of runs/250) HTTP requests.
  761. This is due to the maximum result set limit enforced by testrail.
  762. =over 4
  763. =item INTEGER C<PROJECT_ID> - ID of parent project
  764. =back
  765. Returns ARRAYREF of run definition HASHREFs.
  766. $allRuns = $tr->getRuns(6969);
  767. =cut
  768. sub getRuns {
  769. state $check = compile(Object, Int);
  770. my ($self,$project_id) = $check->(@_);
  771. my $initial_runs = $self->getRunsPaginated($project_id,$self->{'global_limit'},0);
  772. return $initial_runs unless (reftype($initial_runs) || 'undef') eq 'ARRAY';
  773. my $runs = [];
  774. push(@$runs,@$initial_runs);
  775. my $offset = 1;
  776. while (scalar(@$initial_runs) == $self->{'global_limit'}) {
  777. $initial_runs = $self->getRunsPaginated($project_id,$self->{'global_limit'},($self->{'global_limit'} * $offset));
  778. push(@$runs,@$initial_runs);
  779. $offset++;
  780. }
  781. return $runs;
  782. }
  783. =head2 B<getRunsPaginated (project_id,limit,offset)>
  784. Get some runs for specified project.
  785. =over 4
  786. =item INTEGER C<PROJECT_ID> - ID of parent project
  787. =item INTEGER C<LIMIT> - Number of runs to return.
  788. =item INTEGER C<OFFSET> - Page of runs to return.
  789. =back
  790. Returns ARRAYREF of run definition HASHREFs.
  791. $someRuns = $tr->getRunsPaginated(6969,22,4);
  792. =cut
  793. sub getRunsPaginated {
  794. state $check = compile(Object, Int, Optional[Maybe[Int]], Optional[Maybe[Int]]);
  795. my ($self,$project_id,$limit,$offset) = $check->(@_);
  796. confess("Limit greater than ".$self->{'global_limit'}) if $limit > $self->{'global_limit'};
  797. my $apiurl = "index.php?/api/v2/get_runs/$project_id";
  798. $apiurl .= "&offset=$offset" if defined($offset);
  799. $apiurl .= "&limit=$limit" if $limit; #You have problems if you want 0 results
  800. return $self->_doRequest($apiurl);
  801. }
  802. =head2 B<getRunByName (project_id,name)>
  803. Gets run by name.
  804. =over 4
  805. =item INTEGER C<PROJECT ID> - ID of parent project.
  806. =item STRING <NAME> - Name of desired run.
  807. =back
  808. Returns run definition HASHREF.
  809. $tr->getRunByName(1,'R2');
  810. =cut
  811. sub getRunByName {
  812. state $check = compile(Object, Int, Str);
  813. my ($self,$project_id,$name) = $check->(@_);
  814. my $runs = $self->getRuns($project_id);
  815. return -500 if !$runs || (reftype($runs) || 'undef') ne 'ARRAY';
  816. foreach my $run (@$runs) {
  817. return $run if $run->{'name'} eq $name;
  818. }
  819. return 0;
  820. }
  821. =head2 B<getRunByID (run_id)>
  822. Gets run by ID.
  823. =over 4
  824. =item INTEGER C<RUN ID> - ID of desired run.
  825. =back
  826. Returns run definition HASHREF.
  827. $tr->getRunByID(7779311);
  828. =cut
  829. sub getRunByID {
  830. state $check = compile(Object, Int);
  831. my ($self,$run_id) = $check->(@_);
  832. return $self->_doRequest("index.php?/api/v2/get_run/$run_id");
  833. }
  834. =head2 B<closeRun (run_id)>
  835. Close the specified run.
  836. =over 4
  837. =item INTEGER C<RUN ID> - ID of desired run.
  838. =back
  839. Returns run definition HASHREF on success, false on failure.
  840. $tr->closeRun(90210);
  841. =cut
  842. sub closeRun {
  843. state $check = compile(Object, Int);
  844. my ($self,$run_id) = $check->(@_);
  845. return $self->_doRequest("index.php?/api/v2/close_run/$run_id",'POST');
  846. }
  847. =head2 B<getRunSummary(runs)>
  848. Returns array of hashrefs describing the # of tests in the run(s) with the available statuses.
  849. Translates custom_statuses into their system names for you.
  850. =over 4
  851. =item ARRAY C<RUNS> - runs obtained from getRun* or getChildRun* methods.
  852. =back
  853. Returns ARRAY of run HASHREFs with the added key 'run_status' holding a hashref where status_name => count.
  854. $tr->getRunSummary($run,$run2);
  855. =cut
  856. sub getRunSummary {
  857. state $check = compile(Object, slurpy ArrayRef[HashRef]);
  858. my ($self,$runs) = $check->(@_);
  859. confess("At least one run must be passed!") unless scalar(@$runs);
  860. #Translate custom statuses
  861. my $statuses = $self->getPossibleTestStatuses();
  862. my %shash;
  863. #XXX so, they do these tricks with the status names, see...so map the counts to their relevant status ids.
  864. @shash{map { ( $_->{'id'} < 6 ) ? $_->{'name'}."_count" : "custom_status".($_->{'id'} - 5)."_count" } @$statuses } = map { $_->{'id'} } @$statuses;
  865. my @sname;
  866. #Create listing of keys/values
  867. @$runs = map {
  868. my $run = $_;
  869. @{$run->{statuses}}{grep {$_ =~ m/_count$/} keys(%$run)} = grep {$_ =~ m/_count$/} keys(%$run);
  870. foreach my $status (keys(%{$run->{'statuses'}})) {
  871. next if !exists($shash{$status});
  872. @sname = grep {exists($shash{$status}) && $_->{'id'} == $shash{$status}} @$statuses;
  873. $run->{'statuses_clean'}->{$sname[0]->{'label'}} = $run->{$status};
  874. }
  875. $run;
  876. } @$runs;
  877. return map { {'id' => $_->{'id'}, 'name' => $_->{'name'}, 'run_status' => $_->{'statuses_clean'}, 'config_ids' => $_->{'config_ids'} } } @$runs;
  878. }
  879. =head1 RUN AS CHILD OF PLAN METHODS
  880. =head2 B<getChildRuns(plan)>
  881. Extract the child runs from a plan. Convenient, as the structure of this hash is deep, and correct error handling can be tedious.
  882. =over 4
  883. =item HASHREF C<PLAN> - Test Plan definition HASHREF returned by any of the PLAN methods below.
  884. =back
  885. Returns ARRAYREF of run definition HASHREFs. Returns 0 upon failure to extract the data.
  886. =cut
  887. sub getChildRuns {
  888. state $check = compile(Object, HashRef);
  889. my ($self,$plan) = $check->(@_);
  890. return 0 unless defined($plan->{'entries'}) && (reftype($plan->{'entries'}) || 'undef') eq 'ARRAY';
  891. my $entries = $plan->{'entries'};
  892. my $plans = [];
  893. foreach my $entry (@$entries) {
  894. push(@$plans,@{$entry->{'runs'}}) if defined($entry->{'runs'}) && ((reftype($entry->{'runs'}) || 'undef') eq 'ARRAY')
  895. }
  896. return $plans;
  897. }
  898. =head2 B<getChildRunByName(plan,name,configurations)>
  899. =over 4
  900. =item HASHREF C<PLAN> - Test Plan definition HASHREF returned by any of the PLAN methods below.
  901. =item STRING C<NAME> - Name of run to search for within plan.
  902. =item ARRAYREF C<CONFIGURATIONS> (optional) - Names of configurations to filter runs by.
  903. =back
  904. Returns run definition HASHREF, or false if no such run is found.
  905. Convenience method using getChildRuns.
  906. Will throw a fatal error if one or more of the configurations passed does not exist in the project.
  907. =cut
  908. sub getChildRunByName {
  909. state $check = compile(Object, HashRef, Str, Optional[Maybe[ArrayRef[Str]]]);
  910. my ($self,$plan,$name,$configurations) = $check->(@_);
  911. my $runs = $self->getChildRuns($plan);
  912. return 0 if !$runs;
  913. my @pconfigs = ();
  914. #Figure out desired config IDs
  915. if (defined $configurations) {
  916. my $avail_configs = $self->getConfigurations($plan->{'project_id'});
  917. my ($cname);
  918. @pconfigs = map {$_->{'id'}} grep { $cname = $_->{'name'}; grep {$_ eq $cname} @$configurations } @$avail_configs; #Get a list of IDs from the names passed
  919. }
  920. confess("One or more configurations passed does not exist in your project!") if defined($configurations) && (scalar(@pconfigs) != scalar(@$configurations));
  921. my $found;
  922. foreach my $run (@$runs) {
  923. next if $run->{name} ne $name;
  924. next if scalar(@pconfigs) != scalar(@{$run->{'config_ids'}});
  925. #Compare run config IDs against desired, invalidate run if all conditions not satisfied
  926. $found = 0;
  927. foreach my $cid (@{$run->{'config_ids'}}) {
  928. $found++ if grep {$_ == $cid} @pconfigs;
  929. }
  930. return $run if $found == scalar(@{$run->{'config_ids'}});
  931. }
  932. return 0;
  933. }
  934. =head1 PLAN METHODS
  935. =head2 B<createPlan (project_id,name,description,milestone_id,entries)>
  936. Create a test plan.
  937. =over 4
  938. =item INTEGER C<PROJECT ID> - ID of parent project.
  939. =item STRING C<NAME> - Name of plan
  940. =item STRING C<DESCRIPTION> (optional) - Description of plan
  941. =item INTEGER C<MILESTONE_ID> (optional) - ID of milestone
  942. =item ARRAYREF C<ENTRIES> (optional) - New Runs to initially populate the plan with -- See TestRail API documentation for more advanced inputs here.
  943. =back
  944. Returns test plan definition HASHREF, or false on failure.
  945. $entries = [{
  946. suite_id => 345,
  947. include_all => 1,
  948. assignedto_id => 1
  949. }];
  950. $tr->createPlan(1,'Gosplan','Robo-Signed Soviet 5-year plan',22,$entries);
  951. =cut
  952. sub createPlan {
  953. state $check = compile(Object, Int, Str, Optional[Maybe[Str]], Optional[Maybe[Int]], Optional[Maybe[ArrayRef[HashRef]]]);
  954. my ($self,$project_id,$name,$desc,$milestone_id,$entries) = $check->(@_);
  955. my $stuff = {
  956. name => $name,
  957. description => $desc,
  958. milestone_id => $milestone_id,
  959. entries => $entries
  960. };
  961. return $self->_doRequest("index.php?/api/v2/add_plan/$project_id",'POST',$stuff);
  962. }
  963. =head2 B<deletePlan (plan_id)>
  964. Deletes specified plan.
  965. =over 4
  966. =item INTEGER C<PLAN ID> - ID of plan to delete.
  967. =back
  968. Returns BOOLEAN.
  969. $tr->deletePlan(8675309);
  970. =cut
  971. sub deletePlan {
  972. state $check = compile(Object, Int);
  973. my ($self,$plan_id) = $check->(@_);
  974. return $self->_doRequest("index.php?/api/v2/delete_plan/$plan_id",'POST');
  975. }
  976. =head2 B<getPlans (project_id)>
  977. Gets all test plans in specified project.
  978. Like getRuns, must make multiple HTTP requests when the number of results exceeds 250.
  979. =over 4
  980. =item INTEGER C<PROJECT ID> - ID of parent project.
  981. =back
  982. Returns ARRAYREF of all plan definition HASHREFs in a project.
  983. $tr->getPlans(8);
  984. Does not contain any information about child test runs.
  985. Use getPlanByID or getPlanByName if you want that, in particular if you are interested in using getChildRunByName.
  986. =cut
  987. sub getPlans {
  988. state $check = compile(Object, Int);
  989. my ($self,$project_id) = $check->(@_);
  990. my $initial_plans = $self->getPlansPaginated($project_id,$self->{'global_limit'},0);
  991. return $initial_plans unless (reftype($initial_plans) || 'undef') eq 'ARRAY';
  992. my $plans = [];
  993. push(@$plans,@$initial_plans);
  994. my $offset = 1;
  995. while (scalar(@$initial_plans) == $self->{'global_limit'}) {
  996. $initial_plans = $self->getPlansPaginated($project_id,$self->{'global_limit'},($self->{'global_limit'} * $offset));
  997. push(@$plans,@$initial_plans);
  998. $offset++;
  999. }
  1000. return $plans;
  1001. }
  1002. =head2 B<getPlansPaginated (project_id,limit,offset)>
  1003. Get some plans for specified project.
  1004. =over 4
  1005. =item INTEGER C<PROJECT_ID> - ID of parent project
  1006. =item INTEGER C<LIMIT> - Number of plans to return.
  1007. =item INTEGER C<OFFSET> - Page of plans to return.
  1008. =back
  1009. Returns ARRAYREF of plan definition HASHREFs.
  1010. $someRuns = $tr->getPlansPaginated(6969,222,44);
  1011. =cut
  1012. sub getPlansPaginated {
  1013. state $check = compile(Object, Int, Optional[Maybe[Int]], Optional[Maybe[Int]]);
  1014. my ($self,$project_id,$limit,$offset) = $check->(@_);
  1015. confess("Limit greater than ".$self->{'global_limit'}) if $limit > $self->{'global_limit'};
  1016. my $apiurl = "index.php?/api/v2/get_plans/$project_id";
  1017. $apiurl .= "&offset=$offset" if defined($offset);
  1018. $apiurl .= "&limit=$limit" if $limit; #You have problems if you want 0 results
  1019. return $self->_doRequest($apiurl);
  1020. }
  1021. =head2 B<getPlanByName (project_id,name)>
  1022. Gets specified plan by name.
  1023. =over 4
  1024. =item INTEGER C<PROJECT ID> - ID of parent project.
  1025. =item STRING C<NAME> - Name of test plan.
  1026. =back
  1027. Returns plan definition HASHREF.
  1028. $tr->getPlanByName(8,'GosPlan');
  1029. =cut
  1030. sub getPlanByName {
  1031. state $check = compile(Object, Int, Str);
  1032. my ($self,$project_id,$name) = $check->(@_);
  1033. my $plans = $self->getPlans($project_id);
  1034. return -500 if !$plans || (reftype($plans) || 'undef') ne 'ARRAY';
  1035. foreach my $plan (@$plans) {
  1036. if ($plan->{'name'} eq $name) {
  1037. return $self->getPlanByID($plan->{'id'});
  1038. }
  1039. }
  1040. return 0;
  1041. }
  1042. =head2 B<getPlanByID (plan_id)>
  1043. Gets specified plan by ID.
  1044. =over 4
  1045. =item INTEGER C<PLAN ID> - ID of plan.
  1046. =back
  1047. Returns plan definition HASHREF.
  1048. $tr->getPlanByID(2);
  1049. =cut
  1050. sub getPlanByID {
  1051. state $check = compile(Object, Int);
  1052. my ($self,$plan_id) = $check->(@_);
  1053. return $self->_doRequest("index.php?/api/v2/get_plan/$plan_id");
  1054. }
  1055. =head2 B<getPlanSummary(plan_ID)>
  1056. Returns hashref describing the various pass, fail, etc. percentages for tests in the plan.
  1057. The 'totals' key has total cases in each status ('status' => count)
  1058. The 'percentages' key has the same, but as a percentage of the total.
  1059. =over 4
  1060. =item SCALAR C<plan_ID> - ID of your test plan.
  1061. =back
  1062. $tr->getPlanSummary($plan_id);
  1063. =cut
  1064. sub getPlanSummary {
  1065. state $check = compile(Object, Int);
  1066. my ($self,$plan_id) = $check->(@_);
  1067. my $runs = $self->getPlanByID( $plan_id );
  1068. $runs = $self->getChildRuns( $runs );
  1069. @$runs = $self->getRunSummary(@{$runs});
  1070. my $total_sum = 0;
  1071. my $ret = { plan => $plan_id };
  1072. #Compile totals
  1073. foreach my $summary ( @$runs ) {
  1074. my @elems = keys( %{ $summary->{'run_status'} } );
  1075. foreach my $key (@elems) {
  1076. $ret->{'totals'}->{$key} = 0 if !defined $ret->{'totals'}->{$key};
  1077. $ret->{'totals'}->{$key} += $summary->{'run_status'}->{$key};
  1078. $total_sum += $summary->{'run_status'}->{$key};
  1079. }
  1080. }
  1081. #Compile percentages
  1082. foreach my $key (keys(%{$ret->{'totals'}})) {
  1083. next if grep {$_ eq $key} qw{plan configs percentages};
  1084. $ret->{"percentages"}->{$key} = sprintf( "%.2f%%", ( $ret->{'totals'}->{$key} / $total_sum ) * 100 );
  1085. }
  1086. return $ret;
  1087. }
  1088. =head2 B<createRunInPlan (plan_id,suite_id,name,milestone_id,assigned_to_id,config_ids,case_ids)>
  1089. Create a run in a plan.
  1090. =over 4
  1091. =item INTEGER C<PLAN ID> - ID of parent project.
  1092. =item INTEGER C<SUITE ID> - ID of suite to base run on
  1093. =item STRING C<NAME> - Name of run
  1094. =item INTEGER C<ASSIGNED TO ID> (optional) - User to assign the run to
  1095. =item ARRAYREF C<CONFIG IDS> (optional) - Array of Configuration IDs (see getConfigurations) to apply to the created run
  1096. =item ARRAYREF C<CASE IDS> (optional) - Array of case IDs in case you don't want to use the whole testsuite when making the build.
  1097. =back
  1098. Returns run definition HASHREF.
  1099. $tr->createRun(1,1345,'PlannedRun',3,[1,4,77],[3,4,5,6]);
  1100. =cut
  1101. #If you pass an array of case ids, it implies include_all is false
  1102. sub createRunInPlan {
  1103. state $check = compile(Object, Int, Int, Str, Optional[Maybe[Int]], Optional[Maybe[ArrayRef[Int]]], Optional[Maybe[ArrayRef[Int]]]);
  1104. my ($self,$plan_id,$suite_id,$name,$assignedto_id,$config_ids,$case_ids) = $check->(@_);
  1105. my $runs = [
  1106. {
  1107. config_ids => $config_ids,
  1108. include_all => defined($case_ids) ? 0 : 1,
  1109. case_ids => $case_ids
  1110. }
  1111. ];
  1112. my $stuff = {
  1113. suite_id => $suite_id,
  1114. name => $name,
  1115. assignedto_id => $assignedto_id,
  1116. include_all => defined($case_ids) ? 0 : 1,
  1117. case_ids => $case_ids,
  1118. config_ids => $config_ids,
  1119. runs => $runs
  1120. };
  1121. return $self->_doRequest("index.php?/api/v2/add_plan_entry/$plan_id",'POST',$stuff);
  1122. }
  1123. =head2 B<closePlan (plan_id)>
  1124. Close the specified plan.
  1125. =over 4
  1126. =item INTEGER C<PLAN ID> - ID of desired plan.
  1127. =back
  1128. Returns plan definition HASHREF on success, false on failure.
  1129. $tr->closePlan(75020);
  1130. =cut
  1131. sub closePlan {
  1132. state $check = compile(Object, Int);
  1133. my ($self,$plan_id) = $check->(@_);
  1134. return $self->_doRequest("index.php?/api/v2/close_plan/$plan_id",'POST');
  1135. }
  1136. =head1 MILESTONE METHODS
  1137. =head2 B<createMilestone (project_id,name,description,due_on)>
  1138. Create a milestone.
  1139. =over 4
  1140. =item INTEGER C<PROJECT ID> - ID of parent project.
  1141. =item STRING C<NAME> - Name of milestone
  1142. =item STRING C<DESCRIPTION> (optional) - Description of milestone
  1143. =item INTEGER C<DUE_ON> - Date at which milestone should be completed. Unix Timestamp.
  1144. =back
  1145. Returns milestone definition HASHREF, or false on failure.
  1146. $tr->createMilestone(1,'Patriotic victory of world perlism','Accomplish by Robo-Signed Soviet 5-year plan',time()+157788000);
  1147. =cut
  1148. sub createMilestone {
  1149. state $check = compile(Object, Int, Str, Optional[Maybe[Str]], Optional[Maybe[Int]]);
  1150. my ($self,$project_id,$name,$desc,$due_on) = $check->(@_);
  1151. my $stuff = {
  1152. name => $name,
  1153. description => $desc,
  1154. due_on => $due_on # unix timestamp
  1155. };
  1156. return $self->_doRequest("index.php?/api/v2/add_milestone/$project_id",'POST',$stuff);
  1157. }
  1158. =head2 B<deleteMilestone (milestone_id)>
  1159. Deletes specified milestone.
  1160. =over 4
  1161. =item INTEGER C<MILESTONE ID> - ID of milestone to delete.
  1162. =back
  1163. Returns BOOLEAN.
  1164. $tr->deleteMilestone(86);
  1165. =cut
  1166. sub deleteMilestone {
  1167. state $check = compile(Object, Int);
  1168. my ($self,$milestone_id) = $check->(@_);
  1169. return $self->_doRequest("index.php?/api/v2/delete_milestone/$milestone_id",'POST');
  1170. }
  1171. =head2 B<getMilestones (project_id)>
  1172. Get milestones for some project.
  1173. =over 4
  1174. =item INTEGER C<PROJECT ID> - ID of parent project.
  1175. =back
  1176. Returns ARRAYREF of milestone definition HASHREFs.
  1177. $tr->getMilestones(8);
  1178. =cut
  1179. sub getMilestones {
  1180. state $check = compile(Object, Int);
  1181. my ($self,$project_id) = $check->(@_);
  1182. return $self->_doRequest("index.php?/api/v2/get_milestones/$project_id");
  1183. }
  1184. =head2 B<getMilestoneByName (project_id,name)>
  1185. Gets specified milestone by name.
  1186. =over 4
  1187. =item INTEGER C<PROJECT ID> - ID of parent project.
  1188. =item STRING C<NAME> - Name of milestone.
  1189. =back
  1190. Returns milestone definition HASHREF.
  1191. $tr->getMilestoneByName(8,'whee');
  1192. =cut
  1193. sub getMilestoneByName {
  1194. state $check = compile(Object, Int, Str);
  1195. my ($self,$project_id,$name) = $check->(@_);
  1196. my $milestones = $self->getMilestones($project_id);
  1197. return -500 if !$milestones || (reftype($milestones) || 'undef') ne 'ARRAY';
  1198. foreach my $milestone (@$milestones) {
  1199. return $milestone if $milestone->{'name'} eq $name;
  1200. }
  1201. return 0;
  1202. }
  1203. =head2 B<getMilestoneByID (milestone_id)>
  1204. Gets specified milestone by ID.
  1205. =over 4
  1206. =item INTEGER C<MILESTONE ID> - ID of milestone.
  1207. =back
  1208. Returns milestone definition HASHREF.
  1209. $tr->getMilestoneByID(2);
  1210. =cut
  1211. sub getMilestoneByID {
  1212. state $check = compile(Object, Int);
  1213. my ($self,$milestone_id) = $check->(@_);
  1214. return $self->_doRequest("index.php?/api/v2/get_milestone/$milestone_id");
  1215. }
  1216. =head1 TEST METHODS
  1217. =head2 B<getTests (run_id,status_ids,assignedto_ids)>
  1218. Get tests for some run. Optionally filter by provided status_ids and assigned_to ids.
  1219. =over 4
  1220. =item INTEGER C<RUN ID> - ID of parent run.
  1221. =item ARRAYREF C<STATUS IDS> (optional) - IDs of relevant test statuses to filter by. Get with getPossibleTestStatuses.
  1222. =item ARRAYREF C<ASSIGNEDTO IDS> (optional) - IDs of users assigned to test to filter by. Get with getUsers.
  1223. =back
  1224. Returns ARRAYREF of test definition HASHREFs.
  1225. $tr->getTests(8,[1,2,3],[2]);
  1226. =cut
  1227. sub getTests {
  1228. state $check = compile(Object, Int, Optional[Maybe[ArrayRef[Int]]], Optional[Maybe[ArrayRef[Int]]]);
  1229. my ($self,$run_id,$status_ids,$assignedto_ids) = $check->(@_);
  1230. my $query_string = '';
  1231. $query_string = '&status_id='.join(',',@$status_ids) if defined($status_ids) && scalar(@$status_ids);
  1232. my $results = $self->_doRequest("index.php?/api/v2/get_tests/$run_id$query_string");
  1233. @$results = grep {my $aid = $_->{'assignedto_id'}; grep {defined($aid) && $aid == $_} @$assignedto_ids} @$results if defined($assignedto_ids) && scalar(@$assignedto_ids);
  1234. return $results;
  1235. }
  1236. =head2 B<getTestByName (run_id,name)>
  1237. Gets specified test by name.
  1238. =over 4
  1239. =item INTEGER C<RUN ID> - ID of parent run.
  1240. =item STRING C<NAME> - Name of milestone.
  1241. =back
  1242. Returns test definition HASHREF.
  1243. $tr->getTestByName(36,'wheeTest');
  1244. =cut
  1245. sub getTestByName {
  1246. state $check = compile(Object, Int, Str);
  1247. my ($self,$run_id,$name) = $check->(@_);
  1248. my $tests = $self->getTests($run_id);
  1249. return -500 if !$tests || (reftype($tests) || 'undef') ne 'ARRAY';
  1250. foreach my $test (@$tests) {
  1251. return $test if $test->{'title'} eq $name;
  1252. }
  1253. return 0;
  1254. }
  1255. =head2 B<getTestByID (test_id)>
  1256. Gets specified test by ID.
  1257. =over 4
  1258. =item INTEGER C<TEST ID> - ID of test.
  1259. =back
  1260. Returns test definition HASHREF.
  1261. $tr->getTestByID(222222);
  1262. =cut
  1263. sub getTestByID {
  1264. state $check = compile(Object, Int);
  1265. my ($self,$test_id) = $check->(@_);
  1266. return $self->_doRequest("index.php?/api/v2/get_test/$test_id");
  1267. }
  1268. =head2 B<getTestResultFields()>
  1269. Gets custom fields that can be set for tests.
  1270. Returns ARRAYREF of result definition HASHREFs.
  1271. =cut
  1272. sub getTestResultFields {
  1273. state $check = compile(Object);
  1274. my ($self) = $check->(@_);
  1275. return $self->{'tr_fields'} if defined($self->{'tr_fields'}); #cache
  1276. $self->{'tr_fields'} = $self->_doRequest('index.php?/api/v2/get_result_fields');
  1277. return $self->{'tr_fields'};
  1278. }
  1279. =head2 B<getTestResultFieldByName(SYSTEM_NAME,PROJECT_ID)>
  1280. Gets a test result field by it's system name. Optionally filter by project ID.
  1281. =over 4
  1282. =item B<SYSTEM NAME> - STRING: system name of a result field.
  1283. =item B<PROJECT ID> - INTEGER (optional): Filter by whether or not the field is enabled for said project
  1284. =back
  1285. Returns a value less than 0 if unsuccessful.
  1286. =cut
  1287. sub getTestResultFieldByName {
  1288. state $check = compile(Object, Str, Optional[Maybe[Int]]);
  1289. my ($self,$system_name,$project_id) = $check->(@_);
  1290. my @candidates = grep { $_->{'name'} eq $system_name} @{$self->getTestResultFields()};
  1291. return 0 if !scalar(@candidates); #No such name
  1292. return -1 if ref($candidates[0]) ne 'HASH';
  1293. return -2 if ref($candidates[0]->{'configs'}) ne 'ARRAY' && !scalar(@{$candidates[0]->{'configs'}}); #bogofilter
  1294. #Give it to the user
  1295. my $ret = $candidates[0]; #copy/save for later
  1296. return $ret if !defined($project_id);
  1297. #Filter by project ID
  1298. foreach my $config (@{$candidates[0]->{'configs'}}) {
  1299. return $ret if ( grep { $_ == $project_id} @{ $config->{'context'}->{'project_ids'} } )
  1300. }
  1301. return -3;
  1302. }
  1303. =head2 B<getPossibleTestStatuses()>
  1304. Gets all possible statuses a test can be set to.
  1305. Returns ARRAYREF of status definition HASHREFs.
  1306. Caches the result for the lifetime of the TestRail::API object.
  1307. =cut
  1308. sub getPossibleTestStatuses {
  1309. state $check = compile(Object);
  1310. my ($self) = $check->(@_);
  1311. return $self->{'status_cache'} if $self->{'status_cache'};
  1312. $self->{'status_cache'} = $self->_doRequest('index.php?/api/v2/get_statuses');
  1313. return $self->{'status_cache'};
  1314. }
  1315. =head2 statusNamesToIds(names)
  1316. Convenience method to translate a list of statuses to TestRail status IDs.
  1317. The names referred to here are 'internal names' rather than the labels shown in TestRail.
  1318. =over 4
  1319. =item ARRAY C<NAMES> - Array of status names to translate to IDs.
  1320. =back
  1321. Returns ARRAY of status IDs in the same order as the status names passed.
  1322. Throws an exception in the case of one (or more) of the names not corresponding to a valid test status.
  1323. =cut
  1324. sub statusNamesToIds {
  1325. my ($self,@names) = @_;
  1326. return _X_in_my_Y($self,$self->getPossibleTestStatuses(),'id',@names);
  1327. };
  1328. =head2 statusNamesToLabels(names)
  1329. Convenience method to translate a list of statuses to TestRail status labels (the 'nice' form of status names).
  1330. This is useful when interacting with getRunSummary or getPlanSummary, which uses these labels as hash keys.
  1331. =over 4
  1332. =item ARRAY C<NAMES> - Array of status names to translate to IDs.
  1333. =back
  1334. Returns ARRAY of status labels in the same order as the status names passed.
  1335. Throws an exception in the case of one (or more) of the names not corresponding to a valid test status.
  1336. =cut
  1337. sub statusNamesToLabels {
  1338. my ($self,@names) = @_;
  1339. return _X_in_my_Y($self,$self->getPossibleTestStatuses(),'label',@names);
  1340. };
  1341. # Reduce code duplication with internal methods?
  1342. # It's more likely than you think
  1343. # Free PC check @ cpan.org
  1344. sub _X_in_my_Y {
  1345. state $check = compile(Object, ArrayRef, Str, slurpy ArrayRef[Str]);
  1346. my ($self,$search_arr,$key,$names) = $check->(@_);
  1347. my @ret;
  1348. foreach my $name (@$names) {
  1349. foreach my $member (@$search_arr) {
  1350. if ($member->{'name'} eq $name) {
  1351. push @ret, $member->{$key};
  1352. last;
  1353. }
  1354. }
  1355. }
  1356. confess("One or more names provided does not exist in TestRail.") unless scalar(@$names) == scalar(@ret);
  1357. return @ret;
  1358. }
  1359. =head2 B<createTestResults(test_id,status_id,comment,options,custom_options)>
  1360. Creates a result entry for a test.
  1361. =over 4
  1362. =item INTEGER C<TEST_ID> - ID of desired test
  1363. =item INTEGER C<STATUS_ID> - ID of desired test result status
  1364. =item STRING C<COMMENT> (optional) - Any comments about this result
  1365. =item HASHREF C<OPTIONS> (optional) - Various "Baked-In" options that can be set for test results. See TR docs for more information.
  1366. =item HASHREF C<CUSTOM OPTIONS> (optional) - Options to set for custom fields. See buildStepResults for a simple way to post up custom steps.
  1367. =back
  1368. Returns result definition HASHREF.
  1369. $options = {
  1370. elapsed => '30m 22s',
  1371. defects => ['TSR-3','BOOM-44'],
  1372. version => '6969'
  1373. };
  1374. $custom_options = {
  1375. step_results => [
  1376. {
  1377. content => 'Step 1',
  1378. expected => "Bought Groceries",
  1379. actual => "No Dinero!",
  1380. status_id => 2
  1381. },
  1382. {
  1383. content => 'Step 2',
  1384. expected => 'Ate Dinner',
  1385. actual => 'Went Hungry',
  1386. status_id => 2
  1387. }
  1388. ]
  1389. };
  1390. $res = $tr->createTestResults(1,2,'Test failed because it was all like WAAAAAAA when I poked it',$options,$custom_options);
  1391. =cut
  1392. sub createTestResults {
  1393. state $check = compile(Object, Int, Int, Optional[Maybe[Str]], Optional[Maybe[HashRef]], Optional[Maybe[HashRef]]);
  1394. my ($self,$test_id,$status_id,$comment,$opts,$custom_fields) = $check->(@_);
  1395. my $stuff = {
  1396. status_id => $status_id,
  1397. comment => $comment
  1398. };
  1399. #Handle options
  1400. if (defined($opts) && reftype($opts) eq 'HASH') {
  1401. $stuff->{'version'} = defined($opts->{'version'}) ? $opts->{'version'} : undef;
  1402. $stuff->{'elapsed'} = defined($opts->{'elapsed'}) ? $opts->{'elapsed'} : undef;
  1403. $stuff->{'defects'} = defined($opts->{'defects'}) ? join(',',@{$opts->{'defects'}}) : undef;
  1404. $stuff->{'assignedto_id'} = defined($opts->{'assignedto_id'}) ? $opts->{'assignedto_id'} : undef;
  1405. }
  1406. #Handle custom fields
  1407. if (defined($custom_fields) && reftype($custom_fields) eq 'HASH') {
  1408. foreach my $field (keys(%$custom_fields)) {
  1409. $stuff->{"custom_$field"} = $custom_fields->{$field};
  1410. }
  1411. }
  1412. return $self->_doRequest("index.php?/api/v2/add_result/$test_id",'POST',$stuff);
  1413. }
  1414. =head2 bulkAddResults(run_id,results)
  1415. Add multiple results to a run, where each result is a HASHREF with keys as outlined in the get_results API call documentation.
  1416. =over 4
  1417. =item INTEGER C<RUN_ID> - ID of desired run to add results to
  1418. =item ARRAYREF C<RESULTS> - Array of result HASHREFs to upload.
  1419. =back
  1420. Returns ARRAYREF of result definition HASHREFs.
  1421. =cut
  1422. sub bulkAddResults {
  1423. state $check = compile(Object, Int, ArrayRef[HashRef]);
  1424. my ($self,$run_id, $results) = $check->(@_);
  1425. return $self->_doRequest("index.php?/api/v2/add_results/$run_id", 'POST', { 'results' => $results });
  1426. }
  1427. =head2 B<getTestResults(test_id,limit,offset)>
  1428. Get the recorded results for desired test, limiting output to 'limit' entries.
  1429. =over 4
  1430. =item INTEGER C<TEST_ID> - ID of desired test
  1431. =item POSITIVE INTEGER C<LIMIT> (OPTIONAL) - provide no more than this number of results.
  1432. =item INTEGER C<OFFSET> (OPTIONAL) - Offset to begin viewing result set at.
  1433. =back
  1434. Returns ARRAYREF of result definition HASHREFs.
  1435. =cut
  1436. sub getTestResults {
  1437. state $check = compile(Object, Int, Optional[Maybe[Int]], Optional[Maybe[Int]]);
  1438. my ($self,$test_id,$limit,$offset) = $check->(@_);
  1439. my $url = "index.php?/api/v2/get_results/$test_id";
  1440. $url .= "&limit=$limit" if $limit;
  1441. $url .= "&offset=$offset" if defined($offset);
  1442. return $self->_doRequest($url);
  1443. }
  1444. =head1 CONFIGURATION METHODS
  1445. =head2 B<getConfigurationGroups(project_id)>
  1446. Gets the available configuration groups for a project, with their configurations as children.
  1447. =over 4
  1448. =item INTEGER C<PROJECT_ID> - ID of relevant project
  1449. =back
  1450. Returns ARRAYREF of configuration group definition HASHREFs.
  1451. =cut
  1452. sub getConfigurationGroups {
  1453. state $check = compile(Object, Int);
  1454. my ($self,$project_id) = $check->(@_);
  1455. my $url = "index.php?/api/v2/get_configs/$project_id";
  1456. return $self->_doRequest($url);
  1457. }
  1458. =head2 B<addConfigurationGroup(project_id,name)>
  1459. New in TestRail 5.2.
  1460. Add a configuration group to the specified project.
  1461. =over 4
  1462. =item INTEGER C<PROJECT_ID> - ID of relevant project
  1463. =item STRING C<NAME> - Name for new configuration Group.
  1464. =back
  1465. Returns HASHREF with new configuration group.
  1466. =cut
  1467. sub addConfigurationGroup {
  1468. state $check = compile(Object, Int, Str);
  1469. my ($self,$project_id,$name) = $check->(@_);
  1470. my $url = "index.php?/api/v2/add_config_group/$project_id";
  1471. return $self->_doRequest($url,'POST',{'name' => $name});
  1472. }
  1473. =head2 B<editConfigurationGroup(config_group_id,name)>
  1474. New in TestRail 5.2.
  1475. Change the name of a configuration group.
  1476. =over 4
  1477. =item INTEGER C<CONFIG_GROUP_ID> - ID of relevant configuration group
  1478. =item STRING C<NAME> - Name for new configuration Group.
  1479. =back
  1480. Returns HASHREF with new configuration group.
  1481. =cut
  1482. sub editConfigurationGroup {
  1483. state $check = compile(Object, Int, Str);
  1484. my ($self,$config_group_id,$name) = $check->(@_);
  1485. my $url = "index.php?/api/v2/update_config_group/$config_group_id";
  1486. return $self->_doRequest($url,'POST',{'name' => $name});
  1487. }
  1488. =head2 B<deleteConfigurationGroup(config_group_id)>
  1489. New in TestRail 5.2.
  1490. Delete a configuration group.
  1491. =over 4
  1492. =item INTEGER C<CONFIG_GROUP_ID> - ID of relevant configuration group
  1493. =back
  1494. Returns BOOL.
  1495. =cut
  1496. sub deleteConfigurationGroup {
  1497. state $check = compile(Object, Int);
  1498. my ($self,$config_group_id) = $check->(@_);
  1499. my $url = "index.php?/api/v2/delete_config_group/$config_group_id";
  1500. return $self->_doRequest($url,'POST');
  1501. }
  1502. =head2 B<getConfigurations(project_id)>
  1503. Gets the available configurations for a project.
  1504. Mostly for convenience (no need to write a boilerplate loop over the groups).
  1505. =over 4
  1506. =item INTEGER C<PROJECT_ID> - ID of relevant project
  1507. =back
  1508. Returns ARRAYREF of configuration definition HASHREFs.
  1509. Returns result of getConfigurationGroups (likely -500) in the event that call fails.
  1510. =cut
  1511. sub getConfigurations {
  1512. state $check = compile(Object, Int);
  1513. my ($self,$project_id) = $check->(@_);
  1514. my $cgroups = $self->getConfigurationGroups($project_id);
  1515. my $configs = [];
  1516. return $cgroups unless (reftype($cgroups) || 'undef') eq 'ARRAY';
  1517. foreach my $cfg (@$cgroups) {
  1518. push(@$configs, @{$cfg->{'configs'}});
  1519. }
  1520. return $configs;
  1521. }
  1522. =head2 B<addConfiguration(configuration_group_id,name)>
  1523. New in TestRail 5.2.
  1524. Add a configuration to the specified configuration group.
  1525. =over 4
  1526. =item INTEGER C<CONFIGURATION_GROUP_ID> - ID of relevant configuration group
  1527. =item STRING C<NAME> - Name for new configuration.
  1528. =back
  1529. Returns HASHREF with new configuration.
  1530. =cut
  1531. sub addConfiguration {
  1532. state $check = compile(Object, Int, Str);
  1533. my ($self,$configuration_group_id,$name) = $check->(@_);
  1534. my $url = "index.php?/api/v2/add_config/$configuration_group_id";
  1535. return $self->_doRequest($url,'POST',{'name' => $name});
  1536. }
  1537. =head2 B<editConfiguration(config_id,name)>
  1538. New in TestRail 5.2.
  1539. Change the name of a configuration.
  1540. =over 4
  1541. =item INTEGER C<CONFIG_ID> - ID of relevant configuration.
  1542. =item STRING C<NAME> - New name for configuration.
  1543. =back
  1544. Returns HASHREF with new configuration group.
  1545. =cut
  1546. sub editConfiguration {
  1547. state $check = compile(Object, Int, Str);
  1548. my ($self,$config_id,$name) = $check->(@_);
  1549. my $url = "index.php?/api/v2/update_config/$config_id";
  1550. return $self->_doRequest($url,'POST',{'name' => $name});
  1551. }
  1552. =head2 B<deleteConfiguration(config_id)>
  1553. New in TestRail 5.2.
  1554. Delete a configuration.
  1555. =over 4
  1556. =item INTEGER C<CONFIG_ID> - ID of relevant configuration
  1557. =back
  1558. Returns BOOL.
  1559. =cut
  1560. sub deleteConfiguration {
  1561. state $check = compile(Object, Int);
  1562. my ($self,$config_id) = $check->(@_);
  1563. my $url = "index.php?/api/v2/delete_config/$config_id";
  1564. return $self->_doRequest($url,'POST');
  1565. }
  1566. =head2 B<translateConfigNamesToIds(project_id,configs)>
  1567. Transforms a list of configuration names into a list of config IDs.
  1568. =over 4
  1569. =item INTEGER C<PROJECT_ID> - Relevant project ID for configs.
  1570. =item ARRAY C<CONFIGS> - Array of config names
  1571. =back
  1572. Returns ARRAY of configuration names, with undef values for unknown configuration names.
  1573. =cut
  1574. sub translateConfigNamesToIds {
  1575. my ($self,$project_id,@names) = @_;
  1576. my $configs = $self->getConfigurations($project_id) or confess("Could not determine configurations in provided project.");
  1577. return _X_in_my_Y($self,$configs,'id',@names);
  1578. }
  1579. =head1 STATIC METHODS
  1580. =head2 B<buildStepResults(content,expected,actual,status_id)>
  1581. Convenience method to build the stepResult hashes seen in the custom options for getTestResults.
  1582. =over 4
  1583. =item STRING C<CONTENT> (optional) - The step itself.
  1584. =item STRING C<EXPECTED> (optional) - Expected result of test step.
  1585. =item STRING C<ACTUAL> (optional) - Actual result of test step
  1586. =item INTEGER C<STATUS ID> (optional) - Status ID of result
  1587. =back
  1588. =cut
  1589. #Convenience method for building stepResults
  1590. sub buildStepResults {
  1591. state $check = compile(Str, Str, Str, Int);
  1592. my ($content,$expected,$actual,$status_id) = $check->(@_);
  1593. return {
  1594. content => $content,
  1595. expected => $expected,
  1596. actual => $actual,
  1597. status_id => $status_id
  1598. };
  1599. }
  1600. 1;
  1601. __END__
  1602. =head1 SEE ALSO
  1603. L<HTTP::Request>
  1604. L<LWP::UserAgent>
  1605. L<JSON::MaybeXS>
  1606. L<http://docs.gurock.com/testrail-api2/start>
  1607. =head1 SPECIAL THANKS
  1608. Thanks to cPanel Inc, for graciously funding the creation of this module.