API.pm 67 KB

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