API.pm 65 KB

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