API.pm 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547
  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)>
  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. =back
  911. Returns run definition HASHREF, or false if no such run is found.
  912. Convenience method using getChildRuns.
  913. Will throw a fatal error if one or more of the configurations passed does not exist in the project.
  914. =cut
  915. sub getChildRunByName {
  916. state $check = compile(Object, HashRef, Str, Optional[Maybe[ArrayRef[Str]]]);
  917. my ($self,$plan,$name,$configurations) = $check->(@_);
  918. my $runs = $self->getChildRuns($plan);
  919. return 0 if !$runs;
  920. my @pconfigs = ();
  921. #Figure out desired config IDs
  922. if (defined $configurations) {
  923. my $avail_configs = $self->getConfigurations($plan->{'project_id'});
  924. my ($cname);
  925. @pconfigs = map {$_->{'id'}} grep { $cname = $_->{'name'}; grep {$_ eq $cname} @$configurations } @$avail_configs; #Get a list of IDs from the names passed
  926. }
  927. confess("One or more configurations passed does not exist in your project!") if defined($configurations) && (scalar(@pconfigs) != scalar(@$configurations));
  928. my $found;
  929. foreach my $run (@$runs) {
  930. next if $run->{name} ne $name;
  931. next if scalar(@pconfigs) != scalar(@{$run->{'config_ids'}});
  932. #Compare run config IDs against desired, invalidate run if all conditions not satisfied
  933. $found = 0;
  934. foreach my $cid (@{$run->{'config_ids'}}) {
  935. $found++ if grep {$_ == $cid} @pconfigs;
  936. }
  937. return $run if $found == scalar(@{$run->{'config_ids'}});
  938. }
  939. return 0;
  940. }
  941. =head1 PLAN METHODS
  942. =head2 B<createPlan (project_id,name,description,milestone_id,entries)>
  943. Create a test plan.
  944. =over 4
  945. =item INTEGER C<PROJECT ID> - ID of parent project.
  946. =item STRING C<NAME> - Name of plan
  947. =item STRING C<DESCRIPTION> (optional) - Description of plan
  948. =item INTEGER C<MILESTONE_ID> (optional) - ID of milestone
  949. =item ARRAYREF C<ENTRIES> (optional) - New Runs to initially populate the plan with -- See TestRail API documentation for more advanced inputs here.
  950. =back
  951. Returns test plan definition HASHREF, or false on failure.
  952. $entries = [{
  953. suite_id => 345,
  954. include_all => 1,
  955. assignedto_id => 1
  956. }];
  957. $tr->createPlan(1,'Gosplan','Robo-Signed Soviet 5-year plan',22,$entries);
  958. =cut
  959. sub createPlan {
  960. state $check = compile(Object, Int, Str, Optional[Maybe[Str]], Optional[Maybe[Int]], Optional[Maybe[ArrayRef[HashRef]]]);
  961. my ($self,$project_id,$name,$desc,$milestone_id,$entries) = $check->(@_);
  962. my $stuff = {
  963. name => $name,
  964. description => $desc,
  965. milestone_id => $milestone_id,
  966. entries => $entries
  967. };
  968. return $self->_doRequest("index.php?/api/v2/add_plan/$project_id",'POST',$stuff);
  969. }
  970. =head2 B<deletePlan (plan_id)>
  971. Deletes specified plan.
  972. =over 4
  973. =item INTEGER C<PLAN ID> - ID of plan to delete.
  974. =back
  975. Returns BOOLEAN.
  976. $tr->deletePlan(8675309);
  977. =cut
  978. sub deletePlan {
  979. state $check = compile(Object, Int);
  980. my ($self,$plan_id) = $check->(@_);
  981. return $self->_doRequest("index.php?/api/v2/delete_plan/$plan_id",'POST');
  982. }
  983. =head2 B<getPlans (project_id)>
  984. Gets all test plans in specified project.
  985. Like getRuns, must make multiple HTTP requests when the number of results exceeds 250.
  986. =over 4
  987. =item INTEGER C<PROJECT ID> - ID of parent project.
  988. =back
  989. Returns ARRAYREF of all plan definition HASHREFs in a project.
  990. $tr->getPlans(8);
  991. Does not contain any information about child test runs.
  992. Use getPlanByID or getPlanByName if you want that, in particular if you are interested in using getChildRunByName.
  993. =cut
  994. sub getPlans {
  995. state $check = compile(Object, Int);
  996. my ($self,$project_id) = $check->(@_);
  997. my $initial_plans = $self->getPlansPaginated($project_id,$self->{'global_limit'},0);
  998. return $initial_plans unless (reftype($initial_plans) || 'undef') eq 'ARRAY';
  999. my $plans = [];
  1000. push(@$plans,@$initial_plans);
  1001. my $offset = 1;
  1002. while (scalar(@$initial_plans) == $self->{'global_limit'}) {
  1003. $initial_plans = $self->getPlansPaginated($project_id,$self->{'global_limit'},($self->{'global_limit'} * $offset));
  1004. push(@$plans,@$initial_plans);
  1005. $offset++;
  1006. }
  1007. return $plans;
  1008. }
  1009. =head2 B<getPlansPaginated (project_id,limit,offset)>
  1010. Get some plans for specified project.
  1011. =over 4
  1012. =item INTEGER C<PROJECT_ID> - ID of parent project
  1013. =item INTEGER C<LIMIT> - Number of plans to return.
  1014. =item INTEGER C<OFFSET> - Page of plans to return.
  1015. =back
  1016. Returns ARRAYREF of plan definition HASHREFs.
  1017. $someRuns = $tr->getPlansPaginated(6969,222,44);
  1018. =cut
  1019. sub getPlansPaginated {
  1020. state $check = compile(Object, Int, Optional[Maybe[Int]], Optional[Maybe[Int]]);
  1021. my ($self,$project_id,$limit,$offset) = $check->(@_);
  1022. confess("Limit greater than ".$self->{'global_limit'}) if $limit > $self->{'global_limit'};
  1023. my $apiurl = "index.php?/api/v2/get_plans/$project_id";
  1024. $apiurl .= "&offset=$offset" if defined($offset);
  1025. $apiurl .= "&limit=$limit" if $limit; #You have problems if you want 0 results
  1026. return $self->_doRequest($apiurl);
  1027. }
  1028. =head2 B<getPlanByName (project_id,name)>
  1029. Gets specified plan by name.
  1030. =over 4
  1031. =item INTEGER C<PROJECT ID> - ID of parent project.
  1032. =item STRING C<NAME> - Name of test plan.
  1033. =back
  1034. Returns plan definition HASHREF.
  1035. $tr->getPlanByName(8,'GosPlan');
  1036. =cut
  1037. sub getPlanByName {
  1038. state $check = compile(Object, Int, Str);
  1039. my ($self,$project_id,$name) = $check->(@_);
  1040. my $plans = $self->getPlans($project_id);
  1041. return -500 if !$plans || (reftype($plans) || 'undef') ne 'ARRAY';
  1042. foreach my $plan (@$plans) {
  1043. if ($plan->{'name'} eq $name) {
  1044. return $self->getPlanByID($plan->{'id'});
  1045. }
  1046. }
  1047. return 0;
  1048. }
  1049. =head2 B<getPlanByID (plan_id)>
  1050. Gets specified plan by ID.
  1051. =over 4
  1052. =item INTEGER C<PLAN ID> - ID of plan.
  1053. =back
  1054. Returns plan definition HASHREF.
  1055. $tr->getPlanByID(2);
  1056. =cut
  1057. sub getPlanByID {
  1058. state $check = compile(Object, Int);
  1059. my ($self,$plan_id) = $check->(@_);
  1060. return $self->_doRequest("index.php?/api/v2/get_plan/$plan_id");
  1061. }
  1062. =head2 B<getPlanSummary(plan_ID)>
  1063. Returns hashref describing the various pass, fail, etc. percentages for tests in the plan.
  1064. The 'totals' key has total cases in each status ('status' => count)
  1065. The 'percentages' key has the same, but as a percentage of the total.
  1066. =over 4
  1067. =item SCALAR C<plan_ID> - ID of your test plan.
  1068. =back
  1069. $tr->getPlanSummary($plan_id);
  1070. =cut
  1071. sub getPlanSummary {
  1072. state $check = compile(Object, Int);
  1073. my ($self,$plan_id) = $check->(@_);
  1074. my $runs = $self->getPlanByID( $plan_id );
  1075. $runs = $self->getChildRuns( $runs );
  1076. @$runs = $self->getRunSummary(@{$runs});
  1077. my $total_sum = 0;
  1078. my $ret = { plan => $plan_id };
  1079. #Compile totals
  1080. foreach my $summary ( @$runs ) {
  1081. my @elems = keys( %{ $summary->{'run_status'} } );
  1082. foreach my $key (@elems) {
  1083. $ret->{'totals'}->{$key} = 0 if !defined $ret->{'totals'}->{$key};
  1084. $ret->{'totals'}->{$key} += $summary->{'run_status'}->{$key};
  1085. $total_sum += $summary->{'run_status'}->{$key};
  1086. }
  1087. }
  1088. #Compile percentages
  1089. foreach my $key (keys(%{$ret->{'totals'}})) {
  1090. next if grep {$_ eq $key} qw{plan configs percentages};
  1091. $ret->{"percentages"}->{$key} = sprintf( "%.2f%%", ( $ret->{'totals'}->{$key} / $total_sum ) * 100 );
  1092. }
  1093. return $ret;
  1094. }
  1095. =head2 B<createRunInPlan (plan_id,suite_id,name,milestone_id,assigned_to_id,config_ids,case_ids)>
  1096. Create a run in a plan.
  1097. =over 4
  1098. =item INTEGER C<PLAN ID> - ID of parent project.
  1099. =item INTEGER C<SUITE ID> - ID of suite to base run on
  1100. =item STRING C<NAME> - Name of run
  1101. =item INTEGER C<ASSIGNED TO ID> (optional) - User to assign the run to
  1102. =item ARRAYREF C<CONFIG IDS> (optional) - Array of Configuration IDs (see getConfigurations) to apply to the created run
  1103. =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.
  1104. =back
  1105. Returns run definition HASHREF.
  1106. $tr->createRun(1,1345,'PlannedRun',3,[1,4,77],[3,4,5,6]);
  1107. =cut
  1108. #If you pass an array of case ids, it implies include_all is false
  1109. sub createRunInPlan {
  1110. state $check = compile(Object, Int, Int, Str, Optional[Maybe[Int]], Optional[Maybe[ArrayRef[Int]]], Optional[Maybe[ArrayRef[Int]]]);
  1111. my ($self,$plan_id,$suite_id,$name,$assignedto_id,$config_ids,$case_ids) = $check->(@_);
  1112. my $runs = [
  1113. {
  1114. config_ids => $config_ids,
  1115. include_all => defined($case_ids) ? 0 : 1,
  1116. case_ids => $case_ids
  1117. }
  1118. ];
  1119. my $stuff = {
  1120. suite_id => $suite_id,
  1121. name => $name,
  1122. assignedto_id => $assignedto_id,
  1123. include_all => defined($case_ids) ? 0 : 1,
  1124. case_ids => $case_ids,
  1125. config_ids => $config_ids,
  1126. runs => $runs
  1127. };
  1128. return $self->_doRequest("index.php?/api/v2/add_plan_entry/$plan_id",'POST',$stuff);
  1129. }
  1130. =head2 B<closePlan (plan_id)>
  1131. Close the specified plan.
  1132. =over 4
  1133. =item INTEGER C<PLAN ID> - ID of desired plan.
  1134. =back
  1135. Returns plan definition HASHREF on success, false on failure.
  1136. $tr->closePlan(75020);
  1137. =cut
  1138. sub closePlan {
  1139. state $check = compile(Object, Int);
  1140. my ($self,$plan_id) = $check->(@_);
  1141. return $self->_doRequest("index.php?/api/v2/close_plan/$plan_id",'POST');
  1142. }
  1143. =head1 MILESTONE METHODS
  1144. =head2 B<createMilestone (project_id,name,description,due_on)>
  1145. Create a milestone.
  1146. =over 4
  1147. =item INTEGER C<PROJECT ID> - ID of parent project.
  1148. =item STRING C<NAME> - Name of milestone
  1149. =item STRING C<DESCRIPTION> (optional) - Description of milestone
  1150. =item INTEGER C<DUE_ON> - Date at which milestone should be completed. Unix Timestamp.
  1151. =back
  1152. Returns milestone definition HASHREF, or false on failure.
  1153. $tr->createMilestone(1,'Patriotic victory of world perlism','Accomplish by Robo-Signed Soviet 5-year plan',time()+157788000);
  1154. =cut
  1155. sub createMilestone {
  1156. state $check = compile(Object, Int, Str, Optional[Maybe[Str]], Optional[Maybe[Int]]);
  1157. my ($self,$project_id,$name,$desc,$due_on) = $check->(@_);
  1158. my $stuff = {
  1159. name => $name,
  1160. description => $desc,
  1161. due_on => $due_on # unix timestamp
  1162. };
  1163. return $self->_doRequest("index.php?/api/v2/add_milestone/$project_id",'POST',$stuff);
  1164. }
  1165. =head2 B<deleteMilestone (milestone_id)>
  1166. Deletes specified milestone.
  1167. =over 4
  1168. =item INTEGER C<MILESTONE ID> - ID of milestone to delete.
  1169. =back
  1170. Returns BOOLEAN.
  1171. $tr->deleteMilestone(86);
  1172. =cut
  1173. sub deleteMilestone {
  1174. state $check = compile(Object, Int);
  1175. my ($self,$milestone_id) = $check->(@_);
  1176. return $self->_doRequest("index.php?/api/v2/delete_milestone/$milestone_id",'POST');
  1177. }
  1178. =head2 B<getMilestones (project_id)>
  1179. Get milestones for some project.
  1180. =over 4
  1181. =item INTEGER C<PROJECT ID> - ID of parent project.
  1182. =back
  1183. Returns ARRAYREF of milestone definition HASHREFs.
  1184. $tr->getMilestones(8);
  1185. =cut
  1186. sub getMilestones {
  1187. state $check = compile(Object, Int);
  1188. my ($self,$project_id) = $check->(@_);
  1189. return $self->_doRequest("index.php?/api/v2/get_milestones/$project_id");
  1190. }
  1191. =head2 B<getMilestoneByName (project_id,name)>
  1192. Gets specified milestone by name.
  1193. =over 4
  1194. =item INTEGER C<PROJECT ID> - ID of parent project.
  1195. =item STRING C<NAME> - Name of milestone.
  1196. =back
  1197. Returns milestone definition HASHREF.
  1198. $tr->getMilestoneByName(8,'whee');
  1199. =cut
  1200. sub getMilestoneByName {
  1201. state $check = compile(Object, Int, Str);
  1202. my ($self,$project_id,$name) = $check->(@_);
  1203. my $milestones = $self->getMilestones($project_id);
  1204. return -500 if !$milestones || (reftype($milestones) || 'undef') ne 'ARRAY';
  1205. foreach my $milestone (@$milestones) {
  1206. return $milestone if $milestone->{'name'} eq $name;
  1207. }
  1208. return 0;
  1209. }
  1210. =head2 B<getMilestoneByID (milestone_id)>
  1211. Gets specified milestone by ID.
  1212. =over 4
  1213. =item INTEGER C<MILESTONE ID> - ID of milestone.
  1214. =back
  1215. Returns milestone definition HASHREF.
  1216. $tr->getMilestoneByID(2);
  1217. =cut
  1218. sub getMilestoneByID {
  1219. state $check = compile(Object, Int);
  1220. my ($self,$milestone_id) = $check->(@_);
  1221. return $self->_doRequest("index.php?/api/v2/get_milestone/$milestone_id");
  1222. }
  1223. =head1 TEST METHODS
  1224. =head2 B<getTests (run_id,status_ids,assignedto_ids)>
  1225. Get tests for some run. Optionally filter by provided status_ids and assigned_to ids.
  1226. =over 4
  1227. =item INTEGER C<RUN ID> - ID of parent run.
  1228. =item ARRAYREF C<STATUS IDS> (optional) - IDs of relevant test statuses to filter by. Get with getPossibleTestStatuses.
  1229. =item ARRAYREF C<ASSIGNEDTO IDS> (optional) - IDs of users assigned to test to filter by. Get with getUsers.
  1230. =back
  1231. Returns ARRAYREF of test definition HASHREFs.
  1232. $tr->getTests(8,[1,2,3],[2]);
  1233. =cut
  1234. sub getTests {
  1235. state $check = compile(Object, Int, Optional[Maybe[ArrayRef[Int]]], Optional[Maybe[ArrayRef[Int]]]);
  1236. my ($self,$run_id,$status_ids,$assignedto_ids) = $check->(@_);
  1237. my $query_string = '';
  1238. $query_string = '&status_id='.join(',',@$status_ids) if defined($status_ids) && scalar(@$status_ids);
  1239. my $results = $self->_doRequest("index.php?/api/v2/get_tests/$run_id$query_string");
  1240. @$results = grep {my $aid = $_->{'assignedto_id'}; grep {defined($aid) && $aid == $_} @$assignedto_ids} @$results if defined($assignedto_ids) && scalar(@$assignedto_ids);
  1241. return $results;
  1242. }
  1243. =head2 B<getTestByName (run_id,name)>
  1244. Gets specified test by name.
  1245. =over 4
  1246. =item INTEGER C<RUN ID> - ID of parent run.
  1247. =item STRING C<NAME> - Name of milestone.
  1248. =back
  1249. Returns test definition HASHREF.
  1250. $tr->getTestByName(36,'wheeTest');
  1251. =cut
  1252. sub getTestByName {
  1253. state $check = compile(Object, Int, Str);
  1254. my ($self,$run_id,$name) = $check->(@_);
  1255. my $tests = $self->getTests($run_id);
  1256. return -500 if !$tests || (reftype($tests) || 'undef') ne 'ARRAY';
  1257. foreach my $test (@$tests) {
  1258. return $test if $test->{'title'} eq $name;
  1259. }
  1260. return 0;
  1261. }
  1262. =head2 B<getTestByID (test_id)>
  1263. Gets specified test by ID.
  1264. =over 4
  1265. =item INTEGER C<TEST ID> - ID of test.
  1266. =back
  1267. Returns test definition HASHREF.
  1268. $tr->getTestByID(222222);
  1269. =cut
  1270. sub getTestByID {
  1271. state $check = compile(Object, Int);
  1272. my ($self,$test_id) = $check->(@_);
  1273. return $self->_doRequest("index.php?/api/v2/get_test/$test_id");
  1274. }
  1275. =head2 B<getTestResultFields()>
  1276. Gets custom fields that can be set for tests.
  1277. Returns ARRAYREF of result definition HASHREFs.
  1278. =cut
  1279. sub getTestResultFields {
  1280. state $check = compile(Object);
  1281. my ($self) = $check->(@_);
  1282. return $self->{'tr_fields'} if defined($self->{'tr_fields'}); #cache
  1283. $self->{'tr_fields'} = $self->_doRequest('index.php?/api/v2/get_result_fields');
  1284. return $self->{'tr_fields'};
  1285. }
  1286. =head2 B<getTestResultFieldByName(SYSTEM_NAME,PROJECT_ID)>
  1287. Gets a test result field by it's system name. Optionally filter by project ID.
  1288. =over 4
  1289. =item B<SYSTEM NAME> - STRING: system name of a result field.
  1290. =item B<PROJECT ID> - INTEGER (optional): Filter by whether or not the field is enabled for said project
  1291. =back
  1292. Returns a value less than 0 if unsuccessful.
  1293. =cut
  1294. sub getTestResultFieldByName {
  1295. state $check = compile(Object, Str, Optional[Maybe[Int]]);
  1296. my ($self,$system_name,$project_id) = $check->(@_);
  1297. my @candidates = grep { $_->{'name'} eq $system_name} @{$self->getTestResultFields()};
  1298. return 0 if !scalar(@candidates); #No such name
  1299. return -1 if ref($candidates[0]) ne 'HASH';
  1300. return -2 if ref($candidates[0]->{'configs'}) ne 'ARRAY' && !scalar(@{$candidates[0]->{'configs'}}); #bogofilter
  1301. #Give it to the user
  1302. my $ret = $candidates[0]; #copy/save for later
  1303. return $ret if !defined($project_id);
  1304. #Filter by project ID
  1305. foreach my $config (@{$candidates[0]->{'configs'}}) {
  1306. return $ret if ( grep { $_ == $project_id} @{ $config->{'context'}->{'project_ids'} } )
  1307. }
  1308. return -3;
  1309. }
  1310. =head2 B<getPossibleTestStatuses()>
  1311. Gets all possible statuses a test can be set to.
  1312. Returns ARRAYREF of status definition HASHREFs.
  1313. Caches the result for the lifetime of the TestRail::API object.
  1314. =cut
  1315. sub getPossibleTestStatuses {
  1316. state $check = compile(Object);
  1317. my ($self) = $check->(@_);
  1318. return $self->{'status_cache'} if $self->{'status_cache'};
  1319. $self->{'status_cache'} = $self->_doRequest('index.php?/api/v2/get_statuses');
  1320. return $self->{'status_cache'};
  1321. }
  1322. =head2 statusNamesToIds(names)
  1323. Convenience method to translate a list of statuses to TestRail status IDs.
  1324. The names referred to here are 'internal names' rather than the labels shown in TestRail.
  1325. =over 4
  1326. =item ARRAY C<NAMES> - Array of status names to translate to IDs.
  1327. =back
  1328. Returns ARRAY of status IDs in the same order as the status names passed.
  1329. Throws an exception in the case of one (or more) of the names not corresponding to a valid test status.
  1330. =cut
  1331. sub statusNamesToIds {
  1332. my ($self,@names) = @_;
  1333. return _X_in_my_Y($self,$self->getPossibleTestStatuses(),'id',@names);
  1334. };
  1335. =head2 statusNamesToLabels(names)
  1336. Convenience method to translate a list of statuses to TestRail status labels (the 'nice' form of status names).
  1337. This is useful when interacting with getRunSummary or getPlanSummary, which uses these labels as hash keys.
  1338. =over 4
  1339. =item ARRAY C<NAMES> - Array of status names to translate to IDs.
  1340. =back
  1341. Returns ARRAY of status labels in the same order as the status names passed.
  1342. Throws an exception in the case of one (or more) of the names not corresponding to a valid test status.
  1343. =cut
  1344. sub statusNamesToLabels {
  1345. my ($self,@names) = @_;
  1346. return _X_in_my_Y($self,$self->getPossibleTestStatuses(),'label',@names);
  1347. };
  1348. # Reduce code duplication with internal methods?
  1349. # It's more likely than you think
  1350. # Free PC check @ cpan.org
  1351. sub _X_in_my_Y {
  1352. state $check = compile(Object, ArrayRef, Str, slurpy ArrayRef[Str]);
  1353. my ($self,$search_arr,$key,$names) = $check->(@_);
  1354. my @ret;
  1355. foreach my $name (@$names) {
  1356. foreach my $member (@$search_arr) {
  1357. if ($member->{'name'} eq $name) {
  1358. push @ret, $member->{$key};
  1359. last;
  1360. }
  1361. }
  1362. }
  1363. confess("One or more names provided does not exist in TestRail.") unless scalar(@$names) == scalar(@ret);
  1364. return @ret;
  1365. }
  1366. =head2 B<createTestResults(test_id,status_id,comment,options,custom_options)>
  1367. Creates a result entry for a test.
  1368. =over 4
  1369. =item INTEGER C<TEST_ID> - ID of desired test
  1370. =item INTEGER C<STATUS_ID> - ID of desired test result status
  1371. =item STRING C<COMMENT> (optional) - Any comments about this result
  1372. =item HASHREF C<OPTIONS> (optional) - Various "Baked-In" options that can be set for test results. See TR docs for more information.
  1373. =item HASHREF C<CUSTOM OPTIONS> (optional) - Options to set for custom fields. See buildStepResults for a simple way to post up custom steps.
  1374. =back
  1375. Returns result definition HASHREF.
  1376. $options = {
  1377. elapsed => '30m 22s',
  1378. defects => ['TSR-3','BOOM-44'],
  1379. version => '6969'
  1380. };
  1381. $custom_options = {
  1382. step_results => [
  1383. {
  1384. content => 'Step 1',
  1385. expected => "Bought Groceries",
  1386. actual => "No Dinero!",
  1387. status_id => 2
  1388. },
  1389. {
  1390. content => 'Step 2',
  1391. expected => 'Ate Dinner',
  1392. actual => 'Went Hungry',
  1393. status_id => 2
  1394. }
  1395. ]
  1396. };
  1397. $res = $tr->createTestResults(1,2,'Test failed because it was all like WAAAAAAA when I poked it',$options,$custom_options);
  1398. =cut
  1399. sub createTestResults {
  1400. state $check = compile(Object, Int, Int, Optional[Maybe[Str]], Optional[Maybe[HashRef]], Optional[Maybe[HashRef]]);
  1401. my ($self,$test_id,$status_id,$comment,$opts,$custom_fields) = $check->(@_);
  1402. my $stuff = {
  1403. status_id => $status_id,
  1404. comment => $comment
  1405. };
  1406. #Handle options
  1407. if (defined($opts) && reftype($opts) eq 'HASH') {
  1408. $stuff->{'version'} = defined($opts->{'version'}) ? $opts->{'version'} : undef;
  1409. $stuff->{'elapsed'} = defined($opts->{'elapsed'}) ? $opts->{'elapsed'} : undef;
  1410. $stuff->{'defects'} = defined($opts->{'defects'}) ? join(',',@{$opts->{'defects'}}) : undef;
  1411. $stuff->{'assignedto_id'} = defined($opts->{'assignedto_id'}) ? $opts->{'assignedto_id'} : undef;
  1412. }
  1413. #Handle custom fields
  1414. if (defined($custom_fields) && reftype($custom_fields) eq 'HASH') {
  1415. foreach my $field (keys(%$custom_fields)) {
  1416. $stuff->{"custom_$field"} = $custom_fields->{$field};
  1417. }
  1418. }
  1419. return $self->_doRequest("index.php?/api/v2/add_result/$test_id",'POST',$stuff);
  1420. }
  1421. =head2 bulkAddResults(run_id,results)
  1422. Add multiple results to a run, where each result is a HASHREF with keys as outlined in the get_results API call documentation.
  1423. =over 4
  1424. =item INTEGER C<RUN_ID> - ID of desired run to add results to
  1425. =item ARRAYREF C<RESULTS> - Array of result HASHREFs to upload.
  1426. =back
  1427. Returns ARRAYREF of result definition HASHREFs.
  1428. =cut
  1429. sub bulkAddResults {
  1430. state $check = compile(Object, Int, ArrayRef[HashRef]);
  1431. my ($self,$run_id, $results) = $check->(@_);
  1432. return $self->_doRequest("index.php?/api/v2/add_results/$run_id", 'POST', { 'results' => $results });
  1433. }
  1434. =head2 B<getTestResults(test_id,limit,offset)>
  1435. Get the recorded results for desired test, limiting output to 'limit' entries.
  1436. =over 4
  1437. =item INTEGER C<TEST_ID> - ID of desired test
  1438. =item POSITIVE INTEGER C<LIMIT> (OPTIONAL) - provide no more than this number of results.
  1439. =item INTEGER C<OFFSET> (OPTIONAL) - Offset to begin viewing result set at.
  1440. =back
  1441. Returns ARRAYREF of result definition HASHREFs.
  1442. =cut
  1443. sub getTestResults {
  1444. state $check = compile(Object, Int, Optional[Maybe[Int]], Optional[Maybe[Int]]);
  1445. my ($self,$test_id,$limit,$offset) = $check->(@_);
  1446. my $url = "index.php?/api/v2/get_results/$test_id";
  1447. $url .= "&limit=$limit" if $limit;
  1448. $url .= "&offset=$offset" if defined($offset);
  1449. return $self->_doRequest($url);
  1450. }
  1451. =head1 CONFIGURATION METHODS
  1452. =head2 B<getConfigurationGroups(project_id)>
  1453. Gets the available configuration groups for a project, with their configurations as children.
  1454. =over 4
  1455. =item INTEGER C<PROJECT_ID> - ID of relevant project
  1456. =back
  1457. Returns ARRAYREF of configuration group definition HASHREFs.
  1458. =cut
  1459. sub getConfigurationGroups {
  1460. state $check = compile(Object, Int);
  1461. my ($self,$project_id) = $check->(@_);
  1462. my $url = "index.php?/api/v2/get_configs/$project_id";
  1463. return $self->_doRequest($url);
  1464. }
  1465. =head2 B<getConfigurationGroupByName(project_id,name)>
  1466. Get the provided configuration group by name.
  1467. Returns false if the configuration group could not be found.
  1468. =cut
  1469. sub getConfigurationGroupByName {
  1470. state $check = compile(Object, Int, Str);
  1471. my ($self,$project_id,$name) = $check->(@_);
  1472. my $cgroups = $self->getConfigurationGroups($project_id);
  1473. return 0 if ref($cgroups) ne 'ARRAY';
  1474. @$cgroups = grep {$_->{'name'} eq $name} @$cgroups;
  1475. return 0 unless scalar(@$cgroups);
  1476. return $cgroups->[0];
  1477. }
  1478. =head2 B<addConfigurationGroup(project_id,name)>
  1479. New in TestRail 5.2.
  1480. Add a configuration group to the specified project.
  1481. =over 4
  1482. =item INTEGER C<PROJECT_ID> - ID of relevant project
  1483. =item STRING C<NAME> - Name for new configuration Group.
  1484. =back
  1485. Returns HASHREF with new configuration group.
  1486. =cut
  1487. sub addConfigurationGroup {
  1488. state $check = compile(Object, Int, Str);
  1489. my ($self,$project_id,$name) = $check->(@_);
  1490. my $url = "index.php?/api/v2/add_config_group/$project_id";
  1491. return $self->_doRequest($url,'POST',{'name' => $name});
  1492. }
  1493. =head2 B<editConfigurationGroup(config_group_id,name)>
  1494. New in TestRail 5.2.
  1495. Change the name of a configuration group.
  1496. =over 4
  1497. =item INTEGER C<CONFIG_GROUP_ID> - ID of relevant configuration group
  1498. =item STRING C<NAME> - Name for new configuration Group.
  1499. =back
  1500. Returns HASHREF with new configuration group.
  1501. =cut
  1502. sub editConfigurationGroup {
  1503. state $check = compile(Object, Int, Str);
  1504. my ($self,$config_group_id,$name) = $check->(@_);
  1505. my $url = "index.php?/api/v2/update_config_group/$config_group_id";
  1506. return $self->_doRequest($url,'POST',{'name' => $name});
  1507. }
  1508. =head2 B<deleteConfigurationGroup(config_group_id)>
  1509. New in TestRail 5.2.
  1510. Delete a configuration group.
  1511. =over 4
  1512. =item INTEGER C<CONFIG_GROUP_ID> - ID of relevant configuration group
  1513. =back
  1514. Returns BOOL.
  1515. =cut
  1516. sub deleteConfigurationGroup {
  1517. state $check = compile(Object, Int);
  1518. my ($self,$config_group_id) = $check->(@_);
  1519. my $url = "index.php?/api/v2/delete_config_group/$config_group_id";
  1520. return $self->_doRequest($url,'POST');
  1521. }
  1522. =head2 B<getConfigurations(project_id)>
  1523. Gets the available configurations for a project.
  1524. Mostly for convenience (no need to write a boilerplate loop over the groups).
  1525. =over 4
  1526. =item INTEGER C<PROJECT_ID> - ID of relevant project
  1527. =back
  1528. Returns ARRAYREF of configuration definition HASHREFs.
  1529. Returns result of getConfigurationGroups (likely -500) in the event that call fails.
  1530. =cut
  1531. sub getConfigurations {
  1532. state $check = compile(Object, Int);
  1533. my ($self,$project_id) = $check->(@_);
  1534. my $cgroups = $self->getConfigurationGroups($project_id);
  1535. my $configs = [];
  1536. return $cgroups unless (reftype($cgroups) || 'undef') eq 'ARRAY';
  1537. foreach my $cfg (@$cgroups) {
  1538. push(@$configs, @{$cfg->{'configs'}});
  1539. }
  1540. return $configs;
  1541. }
  1542. =head2 B<addConfiguration(configuration_group_id,name)>
  1543. New in TestRail 5.2.
  1544. Add a configuration to the specified configuration group.
  1545. =over 4
  1546. =item INTEGER C<CONFIGURATION_GROUP_ID> - ID of relevant configuration group
  1547. =item STRING C<NAME> - Name for new configuration.
  1548. =back
  1549. Returns HASHREF with new configuration.
  1550. =cut
  1551. sub addConfiguration {
  1552. state $check = compile(Object, Int, Str);
  1553. my ($self,$configuration_group_id,$name) = $check->(@_);
  1554. my $url = "index.php?/api/v2/add_config/$configuration_group_id";
  1555. return $self->_doRequest($url,'POST',{'name' => $name});
  1556. }
  1557. =head2 B<editConfiguration(config_id,name)>
  1558. New in TestRail 5.2.
  1559. Change the name of a configuration.
  1560. =over 4
  1561. =item INTEGER C<CONFIG_ID> - ID of relevant configuration.
  1562. =item STRING C<NAME> - New name for configuration.
  1563. =back
  1564. Returns HASHREF with new configuration group.
  1565. =cut
  1566. sub editConfiguration {
  1567. state $check = compile(Object, Int, Str);
  1568. my ($self,$config_id,$name) = $check->(@_);
  1569. my $url = "index.php?/api/v2/update_config/$config_id";
  1570. return $self->_doRequest($url,'POST',{'name' => $name});
  1571. }
  1572. =head2 B<deleteConfiguration(config_id)>
  1573. New in TestRail 5.2.
  1574. Delete a configuration.
  1575. =over 4
  1576. =item INTEGER C<CONFIG_ID> - ID of relevant configuration
  1577. =back
  1578. Returns BOOL.
  1579. =cut
  1580. sub deleteConfiguration {
  1581. state $check = compile(Object, Int);
  1582. my ($self,$config_id) = $check->(@_);
  1583. my $url = "index.php?/api/v2/delete_config/$config_id";
  1584. return $self->_doRequest($url,'POST');
  1585. }
  1586. =head2 B<translateConfigNamesToIds(project_id,configs)>
  1587. Transforms a list of configuration names into a list of config IDs.
  1588. =over 4
  1589. =item INTEGER C<PROJECT_ID> - Relevant project ID for configs.
  1590. =item ARRAY C<CONFIGS> - Array of config names
  1591. =back
  1592. Returns ARRAY of configuration names, with undef values for unknown configuration names.
  1593. =cut
  1594. sub translateConfigNamesToIds {
  1595. my ($self,$project_id,@names) = @_;
  1596. my $configs = $self->getConfigurations($project_id) or confess("Could not determine configurations in provided project.");
  1597. return _X_in_my_Y($self,$configs,'id',@names);
  1598. }
  1599. =head1 STATIC METHODS
  1600. =head2 B<buildStepResults(content,expected,actual,status_id)>
  1601. Convenience method to build the stepResult hashes seen in the custom options for getTestResults.
  1602. =over 4
  1603. =item STRING C<CONTENT> (optional) - The step itself.
  1604. =item STRING C<EXPECTED> (optional) - Expected result of test step.
  1605. =item STRING C<ACTUAL> (optional) - Actual result of test step
  1606. =item INTEGER C<STATUS ID> (optional) - Status ID of result
  1607. =back
  1608. =cut
  1609. #Convenience method for building stepResults
  1610. sub buildStepResults {
  1611. state $check = compile(Str, Str, Str, Int);
  1612. my ($content,$expected,$actual,$status_id) = $check->(@_);
  1613. return {
  1614. content => $content,
  1615. expected => $expected,
  1616. actual => $actual,
  1617. status_id => $status_id
  1618. };
  1619. }
  1620. 1;
  1621. __END__
  1622. =head1 SEE ALSO
  1623. L<HTTP::Request>
  1624. L<LWP::UserAgent>
  1625. L<JSON::MaybeXS>
  1626. L<http://docs.gurock.com/testrail-api2/start>
  1627. =head1 SPECIAL THANKS
  1628. Thanks to cPanel Inc, for graciously funding the creation of this module.