API.pm 63 KB

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