API.pm 72 KB

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