API.pm 68 KB

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