API.pm 59 KB

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