API.pm 62 KB

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