API.pm 70 KB

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