API.pm 68 KB

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