API.pm 64 KB

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