From 6ceb671d38a8564d8bbe6e52a33e54ebdc4ca282 Mon Sep 17 00:00:00 2001 From: Charles McGarvey Date: Sun, 15 Mar 2020 17:37:32 -0600 Subject: [PATCH] add tests and many fixes --- LICENSE | 379 ++++++++++++++++++++++++++++++++++++ bin/graphql | 94 ++++++--- dist.ini | 39 +++- lib/GraphQL/Client.pm | 179 +++++++++++------ lib/GraphQL/Client/http.pm | 165 +++++++++++----- lib/GraphQL/Client/https.pm | 4 + maint/branch_solo.pl | 61 ++++++ maint/fatpack.pl | 238 ++++++++++++++++++++++ t/client.t | 165 ++++++++++++++++ t/http.t | 217 +++++++++++++++++++++ t/https.t | 13 ++ t/lib/MockTransport.pm | 38 ++++ t/lib/MockUA.pm | 48 +++++ 13 files changed, 1502 insertions(+), 138 deletions(-) create mode 100644 LICENSE create mode 100755 maint/branch_solo.pl create mode 100755 maint/fatpack.pl create mode 100755 t/client.t create mode 100755 t/http.t create mode 100755 t/https.t create mode 100644 t/lib/MockTransport.pm create mode 100644 t/lib/MockUA.pm diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f87adb0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,379 @@ +This software is copyright (c) 2020 by Charles McGarvey. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +Terms of the Perl programming language system itself + +a) the GNU General Public License as published by the Free + Software Foundation; either version 1, or (at your option) any + later version, or +b) the "Artistic License" + +--- The GNU General Public License, Version 1, February 1989 --- + +This software is Copyright (c) 2020 by Charles McGarvey. + +This is free software, licensed under: + + The GNU General Public License, Version 1, February 1989 + + GNU GENERAL PUBLIC LICENSE + Version 1, February 1989 + + Copyright (C) 1989 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The license agreements of most software companies try to keep users +at the mercy of those companies. By contrast, our General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. The +General Public License applies to the Free Software Foundation's +software and to any other program whose authors commit to using it. +You can use it for your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Specifically, the General Public License is designed to make +sure that you have the freedom to give away or sell copies of free +software, that you receive source code or can get it if you want it, +that you can change the software or use pieces of it in new free +programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of a such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must tell them their rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any program or other work which +contains a notice placed by the copyright holder saying it may be +distributed under the terms of this General Public License. The +"Program", below, refers to any such program or work, and a "work based +on the Program" means either the Program or any work containing the +Program or a portion of it, either verbatim or with modifications. Each +licensee is addressed as "you". + + 1. You may copy and distribute verbatim copies of the Program's source +code as you receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice and +disclaimer of warranty; keep intact all the notices that refer to this +General Public License and to the absence of any warranty; and give any +other recipients of the Program a copy of this General Public License +along with the Program. You may charge a fee for the physical act of +transferring a copy. + + 2. You may modify your copy or copies of the Program or any portion of +it, and copy and distribute such modifications under the terms of Paragraph +1 above, provided that you also do the following: + + a) cause the modified files to carry prominent notices stating that + you changed the files and the date of any change; and + + b) cause the whole of any work that you distribute or publish, that + in whole or in part contains the Program or any part thereof, either + with or without modifications, to be licensed at no charge to all + third parties under the terms of this General Public License (except + that you may choose to grant warranty protection to some or all + third parties, at your option). + + c) If the modified program normally reads commands interactively when + run, you must cause it, when started running for such interactive use + in the simplest and most usual way, to print or display an + announcement including an appropriate copyright notice and a notice + that there is no warranty (or else, saying that you provide a + warranty) and that users may redistribute the program under these + conditions, and telling the user how to view a copy of this General + Public License. + + d) You may charge a fee for the physical act of transferring a + copy, and you may at your option offer warranty protection in + exchange for a fee. + +Mere aggregation of another independent work with the Program (or its +derivative) on a volume of a storage or distribution medium does not bring +the other work under the scope of these terms. + + 3. You may copy and distribute the Program (or a portion or derivative of +it, under Paragraph 2) in object code or executable form under the terms of +Paragraphs 1 and 2 above provided that you also do one of the following: + + a) accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of + Paragraphs 1 and 2 above; or, + + b) accompany it with a written offer, valid for at least three + years, to give any third party free (except for a nominal charge + for the cost of distribution) a complete machine-readable copy of the + corresponding source code, to be distributed under the terms of + Paragraphs 1 and 2 above; or, + + c) accompany it with the information you received as to where the + corresponding source code may be obtained. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form alone.) + +Source code for a work means the preferred form of the work for making +modifications to it. For an executable file, complete source code means +all the source code for all modules it contains; but, as a special +exception, it need not include source code for modules which are standard +libraries that accompany the operating system on which the executable +file runs, or for standard header files or definitions files that +accompany that operating system. + + 4. You may not copy, modify, sublicense, distribute or transfer the +Program except as expressly provided under this General Public License. +Any attempt otherwise to copy, modify, sublicense, distribute or transfer +the Program is void, and will automatically terminate your rights to use +the Program under this License. However, parties who have received +copies, or rights to use copies, from you under this General Public +License will not have their licenses terminated so long as such parties +remain in full compliance. + + 5. By copying, distributing or modifying the Program (or any work based +on the Program) you indicate your acceptance of this license to do so, +and all its terms and conditions. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the original +licensor to copy, distribute or modify the Program subject to these +terms and conditions. You may not impose any further restrictions on the +recipients' exercise of the rights granted herein. + + 7. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of the license which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +the license, you may choose any version ever published by the Free Software +Foundation. + + 8. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + Appendix: How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to humanity, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + + To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively convey +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) 19yy + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 1, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) 19xx name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the +appropriate parts of the General Public License. Of course, the +commands you use may be called something other than `show w' and `show +c'; they could even be mouse-clicks or menu items--whatever suits your +program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + program `Gnomovision' (a program to direct compilers to make passes + at assemblers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +That's all there is to it! + + +--- The Artistic License 1.0 --- + +This software is Copyright (c) 2020 by Charles McGarvey. + +This is free software, licensed under: + + The Artistic License 1.0 + +The Artistic License + +Preamble + +The intent of this document is to state the conditions under which a Package +may be copied, such that the Copyright Holder maintains some semblance of +artistic control over the development of the package, while giving the users of +the package the right to use and distribute the Package in a more-or-less +customary fashion, plus the right to make reasonable modifications. + +Definitions: + + - "Package" refers to the collection of files distributed by the Copyright + Holder, and derivatives of that collection of files created through + textual modification. + - "Standard Version" refers to such a Package if it has not been modified, + or has been modified in accordance with the wishes of the Copyright + Holder. + - "Copyright Holder" is whoever is named in the copyright or copyrights for + the package. + - "You" is you, if you're thinking about copying or distributing this Package. + - "Reasonable copying fee" is whatever you can justify on the basis of media + cost, duplication charges, time of people involved, and so on. (You will + not be required to justify it to the Copyright Holder, but only to the + computing community at large as a market that must bear the fee.) + - "Freely Available" means that no fee is charged for the item itself, though + there may be fees involved in handling the item. It also means that + recipients of the item may redistribute it under the same conditions they + received it. + +1. You may make and give away verbatim copies of the source form of the +Standard Version of this Package without restriction, provided that you +duplicate all of the original copyright notices and associated disclaimers. + +2. You may apply bug fixes, portability fixes and other modifications derived +from the Public Domain or from the Copyright Holder. A Package modified in such +a way shall still be considered the Standard Version. + +3. You may otherwise modify your copy of this Package in any way, provided that +you insert a prominent notice in each changed file stating how and when you +changed that file, and provided that you do at least ONE of the following: + + a) place your modifications in the Public Domain or otherwise make them + Freely Available, such as by posting said modifications to Usenet or an + equivalent medium, or placing the modifications on a major archive site + such as ftp.uu.net, or by allowing the Copyright Holder to include your + modifications in the Standard Version of the Package. + + b) use the modified Package only within your corporation or organization. + + c) rename any non-standard executables so the names do not conflict with + standard executables, which must also be provided, and provide a separate + manual page for each non-standard executable that clearly documents how it + differs from the Standard Version. + + d) make other distribution arrangements with the Copyright Holder. + +4. You may distribute the programs of this Package in object code or executable +form, provided that you do at least ONE of the following: + + a) distribute a Standard Version of the executables and library files, + together with instructions (in the manual page or equivalent) on where to + get the Standard Version. + + b) accompany the distribution with the machine-readable source of the Package + with your modifications. + + c) accompany any non-standard executables with their corresponding Standard + Version executables, giving the non-standard executables non-standard + names, and clearly documenting the differences in manual pages (or + equivalent), together with instructions on where to get the Standard + Version. + + d) make other distribution arrangements with the Copyright Holder. + +5. You may charge a reasonable copying fee for any distribution of this +Package. You may charge any fee you choose for support of this Package. You +may not charge a fee for this Package itself. However, you may distribute this +Package in aggregate with other (possibly commercial) programs as part of a +larger (possibly commercial) software distribution provided that you do not +advertise this Package as a product of your own. + +6. The scripts and library files supplied as input to or produced as output +from the programs of this Package do not automatically fall under the copyright +of this Package, but belong to whomever generated them, and may be sold +commercially, and may be aggregated with this Package. + +7. C or perl subroutines supplied by you and linked into this Package shall not +be considered part of this Package. + +8. The name of the Copyright Holder may not be used to endorse or promote +products derived from this software without specific prior written permission. + +9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF +MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + +The End + diff --git a/bin/graphql b/bin/graphql index a94aa01..6afa771 100755 --- a/bin/graphql +++ b/bin/graphql @@ -13,6 +13,9 @@ use JSON::MaybeXS; our $VERSION = '999.999'; # VERSION +my $version; +my $help; +my $manual; my $url; my $transport = {}; my $query = '-'; @@ -21,22 +24,19 @@ my $operation_name; my $format = 'json:pretty'; my $unpack = 0; my $outfile; -my $version; -my $help; -my $manual; GetOptions( + 'version' => \$version, + 'help|h|?' => \$help, + 'manual|man' => \$manual, 'url|u=s' => \$url, 'query|mutation=s' => \$query, 'variables|vars|V=s' => \$variables, 'variable|var|d=s%' => \$variables, - 'operation-name=s' => \$operation_name, + 'operation-name|n=s' => \$operation_name, 'transport|t=s%' => \$transport, 'format|f=s' => \$format, 'unpack!' => \$unpack, 'output|o=s' => \$outfile, - 'version' => \$version, - 'help|h|?' => \$help, - 'manual|man' => \$manual, ) or pod2usage(2); if ($version) { @@ -53,6 +53,11 @@ if ($manual) { $url = shift if !$url; $query = shift if !$query || $query eq '-'; +if (!$url) { + print STDERR "The or --url option argument is required.\n"; + pod2usage(2); +} + $transport = expand_vars($transport); if (ref $variables) { @@ -63,7 +68,14 @@ else { } my $client = GraphQL::Client->new(url => $url); -$client->transport; # just make sure we can load the transport + +eval { $client->transport }; +if (my $err = $@) { + warn $err if $ENV{GRAPHQL_CLIENT_DEBUG}; + print STDERR "Could not construct a transport for URL: $url\n"; + print STDERR "Is this URL correct?\n"; + pod2usage(2); +} if (!$query || $query eq '-') { print STDERR "Interactive mode engaged! Waiting for a query on ...\n" @@ -71,7 +83,7 @@ if (!$query || $query eq '-') { $query = do { local $/; <> }; } -my $resp = $client->request($query, $variables, $operation_name, $transport); +my $resp = $client->execute($query, $variables, $operation_name, $transport); my $err = $resp->{errors}; $unpack = 0 if $err; my $data = $unpack ? $resp->{data} : $resp; @@ -206,8 +218,12 @@ END =head1 SYNOPSIS - graphql [--var key=value]... [--transport key=value]... - [--[no-]unpack] [--format json|json:pretty|yaml|csv|tsv] + graphql [ [--variables JSON] | [--variable KEY=VALUE]... ] + [--operation-name NAME] [--transport KEY=VALUE]... + [--[no-]unpack] [--format json|json:pretty|yaml|perl|csv|tsv|table] + [--output FILE] + + graphql --version|--help|--manual =head1 DESCRIPTION @@ -239,36 +255,37 @@ To hack on the code, clone the repo instead: =head1 OPTIONS -=head2 --url STR +=head2 C<--url URL> The URL of the GraphQL server endpoint. If no C<--url> option is given, the first argument is assumed to be the URL. +This option is required. + Alias: C<-u> -=head2 --query STR +=head2 C<--query STR> The query or mutation to execute. -If no C<--query> option is given, the first argument (after URL) is assumed to be the query. +If no C<--query> option is given, the next argument (after URL) is assumed to be the query. -If the value is C<-> (which is the default), the query will be read from C. +If the value is "-" (which is the default), the query will be read from C. See: L Alias: C<--mutation> -=head2 --variables JSON +=head2 C<--variables JSON> Provide the variables as a JSON object. Aliases: C<--vars>, C<-V> -=head2 --variable KEY=VALUE +=head2 C<--variable KEY=VALUE> -An alternative way to provide variables individually. Repeat this option to provide multiple -variables. +An alternative way to provide variables. Repeat this option to provide multiple variables. If used in combination with L, this option is silently ignored. @@ -276,25 +293,37 @@ See: L Aliases: C<--var>, C<-d> -=head2 --transport KEY=VALUE +=head2 C<--operation-name NAME> + +Inform the server which query/mutation to execute. + +Alias: C<-n> + +=head2 C<--output FILE> + +Write the response to a file instead of STDOUT. + +Alias: C<-o> + +=head2 C<--transport KEY=VALUE> Key-value pairs for configuring the transport (usually HTTP). Alias: C<-t> -=head2 --format STR +=head2 C<--format STR> Specify the output format to use. See L. Alias: C<-f> -=head2 --unpack +=head2 C<--unpack> -Enables C mode. +Enables unpack mode. By default, the response structure is printed as-is from the server, and the program exits 0. -When C mode is enabled, if the response completes with no errors, only the data section of +When unpack mode is enabled, if the response completes with no errors, only the data section of the response is printed and the program exits 0. If the response has errors, the whole response structure is printed as-is and the program exits 1. @@ -306,7 +335,7 @@ The C<--format> argument can be one of: =for :list * C - Comma-separated values (requires L) -* C - Pretty JSON (default) +* C - Human-readable JSON (default) * C - JSON * C - Perl code (requires L) * C - Table (requires L) @@ -379,11 +408,13 @@ Execute a query with variables: > } > END + graphql http://myserver/graphql --vars '{"episode":"JEDI"}' + Configure the transport: graphql http://myserver/graphql {hello} -t headers.authorization='Basic s3cr3t' -This example shows the effect of L<--unpack>: +This example shows the effect of L: graphql http://myserver/graphql {hello} @@ -407,5 +438,16 @@ Some environment variables affect the way C behaves: =for :list * C - Set to 1 to print diagnostic messages to STDERR. +* C - Set the HTTP user agent string. * C - Set table format backend; see L. +=head1 EXIT STATUS + +Here is a consolidated summary of what exit statuses mean: + +=for :list +* C<0> - Success +* C<1> - Client or server errors +* C<2> - Option usage is wrong +* C<3> - Could not format the response as requested + diff --git a/dist.ini b/dist.ini index 3937ffe..7b201e3 100644 --- a/dist.ini +++ b/dist.ini @@ -4,4 +4,41 @@ copyright_holder = Charles McGarvey copyright_year = 2020 license = Perl_5 -[@Author::CCM] +[@Filter] +-bundle = @Author::CCM +-remove = Test::Pod::No404s +PruneFiles.filename = maint + +[ConsistentVersionTest] + +[Run::Release] +run = %x maint%pbranch_solo.pl %v %d + +[RemovePhasedPrereqs] +remove_runtime = Data::Dumper +remove_runtime = HTTP::Tiny +remove_runtime = Pod::Usage +remove_runtime = Text::CSV +remove_runtime = Text::Table::Any +remove_runtime = YAML +[Prereqs / RuntimeRecommends] +HTTP::Tiny = 0 +Pod::Usage = 0 +[Prereqs / RuntimeSuggests] +Data::Dumper = 0 +Text::CSV = 0 +Text::Table::Any = 0 +YAML = 0 +[Prereqs / DevelopRecommends] +; for fatpack.pl +App::FatPacker = 0 +CPAN::Meta = 0 +Capture::Tiny = 0 +Config = 0 +File::pushd = 0 +Getopt::Long = 0 +MetaCPAN::API = 0 +Module::CoreList = 0 +Path::Tiny = 0 +Perl::Strip = 0 + diff --git a/lib/GraphQL/Client.pm b/lib/GraphQL/Client.pm index faa5eda..d204f01 100644 --- a/lib/GraphQL/Client.pm +++ b/lib/GraphQL/Client.pm @@ -6,18 +6,19 @@ use strict; use Module::Load qw(load); use Scalar::Util qw(reftype); -use Throw; +use namespace::clean; our $VERSION = '999.999'; # VERSION -sub _croak { use Carp; goto &Carp::croak } +sub _croak { require Carp; goto &Carp::croak } +sub _throw { GraphQL::Client::Error->throw(@_) } sub new { my $class = shift; bless {@_}, $class; } -sub request { +sub execute { my $self = shift; my ($query, $variables, $operation_name, $options) = @_; @@ -32,50 +33,48 @@ sub request { $operation_name ? (operationName => $operation_name) : (), }; - my $resp = $self->transport->request($request, $options); - return $self->_handle_response($resp); + return $self->_handle_result($self->transport->execute($request, $options)); } -my $ERROR_MESSAGE = 'The GraphQL server returned errors'; -sub _handle_response { +sub _handle_result { my $self = shift; - my ($resp) = @_; - - if (eval { $resp->isa('Future') }) { - return $resp->followed_by(sub { - my $f = shift; - if (my ($exception, $category, @details) = $f->failure) { - if (!$exception->{errors}) { - return Future->fail($exception, $category, @details); - } - if ($self->unpack) { - return Future->fail($ERROR_MESSAGE, 'graphql', $exception, @details); - } - return Future->done($exception); - } - else { - my ($resp, @other) = $f->get; - if ($self->unpack) { - if ($resp->{errors}) { - return Future->fail($ERROR_MESSAGE, 'graphql', $resp, @other); - } - return Future->done($resp->{data}); - } - return Future->done($resp); - } - }); - } - else { + my ($result) = @_; + + my $handle_result = sub { + my $result = shift; + my $resp = $result->{response}; + if (my $exception = $result->{error}) { + unshift @{$resp->{errors}}, { + message => "$exception", + }; + } if ($self->unpack) { if ($resp->{errors}) { - throw $ERROR_MESSAGE, { + _throw $resp->{errors}[0]{message}, { type => 'graphql', response => $resp, + details => $result->{details}, }; } return $resp->{data}; } return $resp; + }; + + if (eval { $result->isa('Future') }) { + return $result->transform( + done => sub { + my $result = shift; + my $resp = eval { $handle_result->($result) }; + if (my $err = $@) { + Future::Exception->throw("$err", $err->{type}, $err->{response}, $err->{details}); + } + return $resp; + }, + ); + } + else { + return $handle_result->($result); } } @@ -94,7 +93,7 @@ sub transport { $self->{transport} //= do { my $class = $self->_transport_class; eval { load $class }; - if ((my $err = $@) || !$class->can('request')) { + if ((my $err = $@) || !$class->can('execute')) { $err ||= "Loaded $class, but it doesn't look like a proper transport.\n"; warn $err if $ENV{GRAPHQL_CLIENT_DEBUG}; _croak "Failed to load transport for \"${class}\""; @@ -137,41 +136,96 @@ sub _expand_class { $class; } +{ + package GraphQL::Client::Error; + + use warnings; + use strict; + + use overload '""' => \&error, fallback => 1; + + sub new { bless {%{$_[2] || {}}, error => $_[1] || 'Something happened'}, $_[0] } + + sub error { "$_[0]->{error}" } + sub type { "$_[0]->{type}" } + + sub throw { + my $self = shift; + die $self if ref $self; + die $self->new(@_); + } +} + 1; __END__ =head1 SYNOPSIS - my $client = GraphQL::Client->new(); + my $graphql = GraphQL::Client->new(url => 'http://localhost:4000/graphql'); + + # Example: Hello world! - my $data = $client->request(q[ + my $response = $graphql->execute('{hello}'); + + # Example: Kitchen sink + + my $query = q[ query GetHuman { human(id: $human_id) { name height } } - ], { + ]; + my $variables = { human_id => 1000, + }; + my $operation_name = 'GetHuman'; + my $transport_options = { + headers => { + authorization => 'Bearer s3cr3t', + }, + }; + my $response = $graphql->execute($query, $variables, $operation_name, $transport_options); + + # Example: Asynchronous with Mojo::UserAgent (promisify requires Future::Mojo) + + my $ua = Mojo::UserAgent->new; + my $graphql = GraphQL::Client->new(ua => $ua, url => 'http://localhost:4000/graphql'); + + my $future = $graphql->execute('{hello}'); + + $future->promisify->then(sub { + my $response = shift; + ... }); =head1 DESCRIPTION +C provides a simple way to execute L queries and +mutations on a server. + +This module is the programmatic interface. There is also a L. + +GraphQL servers are usually served over HTTP. The provided transport, L, lets +you plug in your own user agent, so this client works naturally with L, +L, and more. You can also use L middleware. + =method new - $client = GraphQL::Client->new(%attributes); + $graphql = GraphQL::Client->new(%attributes); Construct a new client. -=method request +=method execute - $response = $client->request($query); - $response = $client->request($query, \%variables); - $response = $client->request($query, \%variables, $operation_name); - $response = $client->request($query, \%variables, $operation_name, \%transport_options); - $response = $client->request($query, \%variables, \%transport_options); + $response = $graphql->execute($query); + $response = $graphql->execute($query, \%variables); + $response = $graphql->execute($query, \%variables, $operation_name); + $response = $graphql->execute($query, \%variables, $operation_name, \%transport_options); + $response = $graphql->execute($query, \%variables, \%transport_options); -Get a response from the GraphQL server. +Execute a request on a GraphQL server, and get a response. By default, the response will either be a hashref with the following structure or a L that resolves to such a hashref, depending on the transport and how it is configured. @@ -193,8 +247,6 @@ Note: Setting the L attribute affects the response shape. The URL of a GraphQL endpoint, e.g. C<"http://myapiserver/graphql">. -This is required. - =attr class The package name of a transport. @@ -231,28 +283,39 @@ will be missing if the response completed without error. It is up to you to check for errors in the response, so your code might look like this: - my $response = $client->request(...); + my $response = $graphql->execute(...); if (my $errors = $response->{errors}) { - # handle errors + # handle $errors + } + else { + my $data = $response->{data}; + # do something with $data } - my $data = $response->{data}; - # do something with $data -If C is 1 (on), then L will return just the data if there were no errors, -otherwise it will throw an exception. So your code would look like this: +If C is 1 (on), then L will return just the data if there were no errors, +otherwise it will throw an exception. So your code would instead look like this: - my $data = eval { $client->request(...) }; + my $data = eval { $graphql->execute(...) }; if (my $error = $@) { # handle errors } - # do something with $data + else { + # do something with $data + } Or if you want to handle errors in a different stack frame, your code is simply this: - my $data = $client->request(...); + my $data = $graphql->execute(...); # do something with $data Both styles map to L responses intuitively. If C is 0, the response always resolves to the envelope structure. If C is 1, successful responses will resolve to just the data and errors will fail/reject. +=head1 SEE ALSO + +=for :list +* L - CLI program +* L - Perl implementation of a GraphQL server +* L - GraphQL project website + diff --git a/lib/GraphQL/Client/http.pm b/lib/GraphQL/Client/http.pm index b6e608f..9c89444 100644 --- a/lib/GraphQL/Client/http.pm +++ b/lib/GraphQL/Client/http.pm @@ -7,28 +7,36 @@ use strict; use HTTP::AnyUA::Util qw(www_form_urlencode); use HTTP::AnyUA; +use namespace::clean; our $VERSION = '999.999'; # VERSION +sub _croak { require Carp; goto &Carp::croak } + sub new { my $class = shift; - bless {@_}, $class; + my $self = @_ % 2 == 0 ? {@_} : $_[0]; + bless $self, $class; } -sub request { +sub execute { my $self = shift; my ($request, $options) = @_; my $url = delete $options->{url} || $self->url; my $method = delete $options->{method} || $self->method; + $request && ref($request) eq 'HASH' or _croak q{Usage: $http->execute(\%request)}; + $request->{query} or _croak q{Request must have a query}; + $url or _croak q{URL must be provided}; + my $data = {%$request}; if ($method eq 'GET' || $method eq 'HEAD') { $data->{variables} = $self->json->encode($data->{variables}) if $data->{variables}; my $params = www_form_urlencode($data); - my $sep = $url =~ /\?/ ? '&' : '?'; - $url .= "${sep}${params}"; + my $sep = $url =~ /^[^#]+\?/ ? '&' : '?'; + $url =~ s/#/${sep}${params}#/ or $url .= "${sep}${params}"; } else { my $encoded_data = $self->json->encode($data); @@ -44,59 +52,82 @@ sub _handle_response { my $self = shift; my ($resp) = @_; - my $handle_error = sub { - my $resp = shift; - - my $data = eval { $self->json->decode($resp->{content}) }; - if ($@) { - my $content = $resp->{content} // 'No content'; - my $reason = $resp->{reason} // ''; - $data = { - errors => [ - { - message => "HTTP transport returned $resp->{status} ($reason): $content", + if (eval { $resp->isa('Future') }) { + return $resp->followed_by(sub { + my $f = shift; + + if (my ($exception, $category, @other) = $f->failure) { + if (ref $exception eq 'HASH') { + my $resp = $exception; + return Future->done($self->_handle_error($resp)); + } + + return Future->done({ + error => $exception, + response => undef, + details => { + exception_details => [$category, @other], }, - ], - }; - } + }); + } - return ($data, 'graphql', $resp); - }; - my $handle_response = sub { - my $resp = shift; - - return $handle_error->($resp) if !$resp->{success}; - my $data = eval { $self->json->decode($resp->{content}) }; - if (my $err = $@) { - warn $err if $ENV{GRAPHQL_CLIENT_DEBUG}; - $data = { - errors => [ - { - message => 'HTTP transport failed to decode response from GraphQL server.', - }, - ], - }; - } - return $data; - }; - - if ($self->any_ua->response_is_future) { - return $resp->transform( - done => $handle_response, - fail => $handle_error, - ); + my $resp = $f->get; + return Future->done($self->_handle_success($resp)); + }); } else { - return $handle_response->($resp); + return $self->_handle_error($resp) if !$resp->{success}; + return $self->_handle_success($resp); } } +sub _handle_error { + my $self = shift; + my ($resp) = @_; + + my $data = eval { $self->json->decode($resp->{content}) }; + my $content = $resp->{content} // 'No content'; + my $reason = $resp->{reason} // ''; + my $message = "HTTP transport returned $resp->{status} ($reason): $content"; + + return { + error => $message, + response => $data, + details => { + http_response => $resp, + }, + }; +} + +sub _handle_success { + my $self = shift; + my ($resp) = @_; + + my $data = eval { $self->json->decode($resp->{content}) }; + if (my $exception = $@) { + return { + error => "HTTP transport failed to decode response: $exception", + response => undef, + details => { + http_response => $resp, + }, + }; + } + + return { + response => $data, + details => { + http_response => $resp, + }, + }; +} + sub ua { my $self = shift; $self->{ua} //= do { require HTTP::Tiny; HTTP::Tiny->new( - agent => "perl-graphql-client/$VERSION", + agent => $ENV{GRAPHQL_CLIENT_HTTP_USER_AGENT} // "perl-graphql-client/$VERSION", ); }; } @@ -134,7 +165,17 @@ __END__ method => 'POST', ); - my $data = $client->request($query, $variables, $operation_name, $options); + my $request = { + query => 'query Greet($name: String) { hello(name: $name) }', + operationName => 'Greet', + variables => { name => 'Bob' }, + }; + my $options = { + headers => { + authorization => 'Bearer s3cr3t', + }, + }; + my $response = $client->execute($request, $options); =head1 DESCRIPTION @@ -143,7 +184,7 @@ You probably shouldn't use this directly. Instead use L. C is a GraphQL transport for HTTP. GraphQL is not required to be transported via HTTP, but this is definitely the most common way. -This also serves as a reference implementation for future GraphQL transports. +This also serves as a reference implementation for C transports. =method new @@ -151,23 +192,33 @@ This also serves as a reference implementation for future GraphQL transports. Construct a new GraphQL HTTP transport. -=method request +See L. + +=method execute - $response = $client->request(\%data, \%options); + $response = $client->execute(\%request); + $response = $client->execute(\%request, \%options); Get a response from the GraphQL server. The C<%data> structure must have a C key whose value is the query or mutation string. It may -optionally have a C hashref an an C string. +optionally have a C hashref and an C string. -The C<%options> structure contains options passed through to the user agent. +The C<%options> structure is optional and may contain options passed through to the user agent. The +only useful options are C (which should have a hashref value) and C and C to +override the attributes of the same names. The response will either be a hashref with the following structure or a L that resolves to such a hashref: { - data => {...}, - errors => [...], + response => { # decoded response (may be undef if an error occurred) + data => {...}, + errors => [...], + }, + error => 'Something happened', # may be ommitted if no error occurred + details => { # optional information which may aide troubleshooting + }, } =attr ua @@ -186,6 +237,10 @@ See L. The L instance. Can be used to apply middleware if desired. +=attr url + +The http URL of a GraphQL endpoint, e.g. C<"http://myapiserver/graphql">. + =attr method The HTTP method to use when querying the GraphQL server. Can be one of: @@ -194,6 +249,10 @@ The HTTP method to use when querying the GraphQL server. Can be one of: * C * C (default) +GraphQL servers should be able to handle both, but you can set this explicitly to one or the other +if you're dealing with a server that is opinionated. You can also provide a different HTTP method, +but anything other than C and C are less likely to work. + =attr json The L (or compatible) object used for encoding and decoding data structures to and from diff --git a/lib/GraphQL/Client/https.pm b/lib/GraphQL/Client/https.pm index 56f2672..d0841d1 100644 --- a/lib/GraphQL/Client/https.pm +++ b/lib/GraphQL/Client/https.pm @@ -16,6 +16,10 @@ sub new { 1; __END__ +=head1 DESCRIPTION + +This is the same as L. + =head1 SEE ALSO L diff --git a/maint/branch_solo.pl b/maint/branch_solo.pl new file mode 100755 index 0000000..6c31aac --- /dev/null +++ b/maint/branch_solo.pl @@ -0,0 +1,61 @@ +#!/usr/bin/env perl + +# This script prepares the graphql script for standalone use and puts it in a new branch. + +use strict; +use warnings; +use autodie; + +use File::Copy; +use File::Path qw(make_path remove_tree); +use String::ShellQuote; + +my $version = shift or die 'Need version'; +my $distdir = shift or die 'Need distdir'; + +my $branch_name = 'solo'; +my $script_name = 'graphql'; + +my $branch_oldref = ''; +my $branch_oldref_origin = ''; + +open(my $fh, '-|', qw{git show-ref}, $branch_name); +while (my $line = <$fh>) { + chomp $line; + my ($hash, $ref) = split(/\s+/, $line); + $branch_oldref = $hash if $ref eq "refs/heads/$branch_name"; + $branch_oldref_origin = $hash if $ref eq "refs/remotes/origin/$branch_name"; +} +if ($branch_oldref_origin && $branch_oldref ne $branch_oldref_origin) { + # reset local branch + system(qw{git branch -f}, $branch_name, "origin/$branch_name"); + $branch_oldref = $branch_oldref_origin +} + +my $commit_msg = shell_quote("Release $version"); + +my $solodir = "solo_branch.$$"; +make_path($solodir); + +use Config; +system($Config{'perlpath'}, qw{maint/fatpack.pl --clean --dist}, $distdir); +move($script_name, "$solodir/$script_name"); + +copy("$distdir/README", "$solodir/README"); + +system(qw{git update-index --add}, glob("$solodir/*")); +my $tree_ref = `git write-tree --prefix=$solodir/`; +chomp $tree_ref; + +system(qw{git reset}); +remove_tree($solodir); + +my $branch_oldref_safe = shell_quote($branch_oldref); +my $tree_ref_safe = shell_quote($tree_ref); +my $parent = $branch_oldref ? "-p $branch_oldref_safe" : ''; +my $commit_ref = `git commit-tree -m $commit_msg $parent $tree_ref_safe`; +chomp $commit_ref; + +system(qw(git branch -f), $branch_name, $commit_ref); +system(qw(git tag -a -m), "Version $version", "$branch_name-$version", $commit_ref); + diff --git a/maint/fatpack.pl b/maint/fatpack.pl new file mode 100755 index 0000000..2748081 --- /dev/null +++ b/maint/fatpack.pl @@ -0,0 +1,238 @@ +#!/usr/bin/env perl + +=head1 NAME + + maint/fatpack.pl - Generate a fatpack version of graphql + +=head1 SYNOPSIS + + maint/fatpack.pl --dist-dir DIRPATH [--clean] + +=cut + +use 5.010001; +use strict; +use warnings; + +use CPAN::Meta; +use Capture::Tiny qw(capture_stdout); +use Config; +use File::pushd; +use Getopt::Long; +use MetaCPAN::API; +use Module::CoreList; +use Path::Tiny 0.089; + +my $core_version = '5.010001'; +my $plenv_version = '5.10.1'; +my %blacklist_modules = map { $_ => 1 } ( + 'perl', + 'Text::Table::ASV', # brought in by Text::Table::Any but not actually required + 'Unicode::GCString', # optional XS module +); +my @extra_modules = ( + 'Proc::Find::Parents', # used by Term::Detect::Software on some platforms +); + +my $clean = 0; +my $distdir; +GetOptions( + 'clean!' => \$clean, + 'dist=s' => \$distdir, +) or die "Invalid options.\n"; +$distdir && -d $distdir or die "Use --dist to specify path to a distribution directory.\n"; + +my $mcpan = MetaCPAN::API->new; + +run($distdir, $clean); +exit; + +sub install_modules { + my $path = path(shift); + my @modules = @_; + run_command('cpanm', '-n', "-L$path", @modules); +} + +sub run { + my $distdir = path(shift); + my $clean = shift; + + my $builddir = path('.build'); + my $fatlibdir = path('fatlib'); + + if ($clean) { + print STDERR "Cleaning...\n"; + $builddir->remove_tree({safe => 0}); + $fatlibdir->remove_tree({safe => 0}); + } + + $builddir->mkpath; + + my @modules = required_modules($distdir, $builddir->child('deps.txt')); + install_modules($builddir->child('local'), @modules); + pack_modules($builddir->child('local'), @modules); + + clean_fatlib($fatlibdir); + + # consolidate all modules into a new directory for packing + my $moduledir = $builddir->child('modules'); + $moduledir->remove_tree({safe => 0}); + $moduledir->mkpath; + system(qw{cp -r}, $fatlibdir, $distdir->child('lib'), "$moduledir/"); + + my $fatpack = do { + my $cd_builddir = pushd($moduledir); + + system('perlstrip', '--cache', '-v', find_modules('.')); + `fatpack file`; + }; + + generate_script($distdir->child('bin/graphql'), $fatpack, 'graphql'); +} + +sub required_modules { + my $path = path(shift); + my $cache_filepath = shift; + + print STDERR "Determining required modules...\n"; + + my $cachefile = $cache_filepath && path($cache_filepath); + if (my $contents = eval { $cachefile->slurp_utf8 }) { + chomp $contents; + return split(/\n/, $contents); + } + + my $meta = CPAN::Meta->load_file($path->child('META.json')); + + my $requires = CPAN::Meta::Requirements->new; + + for my $type (qw{requires recommends suggests}) { + my $reqs = $meta->effective_prereqs->requirements_for('runtime', $type); + for my $module ($reqs->required_modules) { + next if $blacklist_modules{$module}; + + my $core = $Module::CoreList::version{$core_version}{$module}; + print STDERR "skipping core: $module $core\n" if $core; + next if $core && $reqs->accepts_module($module, $core); + + $requires->add_string_requirement($module => $reqs->requirements_for_module($module)); + dependencies_for_module($requires, $module); + } + } + $requires->clear_requirement($_) for qw(Module::CoreList ExtUtils::MakeMaker Carp); + my @deps = $requires->required_modules; + + push @deps, @extra_modules; + + $cachefile->spew_utf8([map { "$_\n" } @deps]) if $cachefile; + + return @deps; +} + +sub dependencies_for_dist { + my $requires = shift; + my $name = shift; + + state %dists; + return if $dists{$name}++; + print STDERR "Finding dependencies for dist $name\n"; + + my $dist = $mcpan->release(distribution => $name); + + my $reqs = CPAN::Meta::Requirements->new; + + foreach my $dep (@{$dist->{dependency}}) { + next if $dep->{phase} ne 'runtime'; + next if $dep->{relationship} ne 'requires'; # && $dep->{relationship} ne 'recommends'; + + my $module = $dep->{module}; + next if $blacklist_modules{$module}; + + $reqs->add_minimum($dep->{module} => $dep->{version}); + my $core = $Module::CoreList::version{$core_version}{$module}; + print STDERR "skipping core: $module $core\n" if $core; + next if $core && $reqs->accepts_module($module, $core); + + $requires->add_string_requirement($module => $reqs->requirements_for_module($module)); + dependencies_for_module($requires, $dep->{module}); + } +} + +sub dependencies_for_module { + my $requires = shift; + my $name = shift; + + state %modules; + return if $modules{$name}++; + print STDERR "Finding dependencies for module $name\n"; + + my $module = $mcpan->module($name); + dependencies_for_dist($requires, $module->{distribution}); +} + +sub clean_fatlib { + my $path = path(shift); + $path->child($Config{archname})->remove_tree({safe => 0}); + $path->child('POD2')->remove_tree({safe => 0}); + $path->visit(sub { + local $_ = shift; + if (/\.p(od|l)$/ || /\.sample$/) { + print "rm $_\n"; + $_->remove; + } + }, {recurse => 1}); +} + +sub find_modules { + my $path = path(shift); + my @pm_filepaths; + $path->visit(sub { + local $_ = shift; + push @pm_filepaths, $_ if /\.pm$/; + }, {recurse => 1}); + return @pm_filepaths; +} + +sub pack_modules { + my ($path, @modules) = @_; + + my @filepaths = map { my $s = $_; $s =~ s!::!/!g; "$s.pm" } @modules; + + my $stdout = capture_stdout { + local $ENV{PERL5LIB} = $path->child('lib/perl5')->absolute; + system('fatpack', 'packlists-for', @filepaths); + }; + + my @packlists = split(/\n/, $stdout); + for my $packlist (@packlists) { + warn "Packing $packlist\n"; + } + + system('fatpack', 'tree', map { path($_)->absolute } @packlists); +} + +sub generate_script { + my ($input_filepath, $fatpack, $output_filepath) = @_; + + open(my $in, '<', $input_filepath) or die "open failed: $!"; + open(my $out, '>', "$output_filepath.tmp") or die "open failed: $!"; + + while (<$in>) { + s|^#!\h*perl|#!/usr/bin/env perl|; + s|^# FATPACK.*|$fatpack|; + print $out $_; + } + + unlink($output_filepath); + rename("$output_filepath.tmp", $output_filepath); + + path($output_filepath)->chmod(0755); + + print STDERR "Wrote fatpacked script: $output_filepath\n"; +} + +sub run_command { + local $ENV{PLENV_VERSION} = $plenv_version; + system('plenv', 'exec', @_); +} + diff --git a/t/client.t b/t/client.t new file mode 100755 index 0000000..4775b70 --- /dev/null +++ b/t/client.t @@ -0,0 +1,165 @@ +#!/usr/bin/env perl + +use warnings; +use strict; + +use FindBin '$Bin'; +use lib "$Bin/lib"; + +use Test::Exception; +use Test::More; + +use Future; +use GraphQL::Client; +use MockTransport; + +subtest 'transport' => sub { + my $client = GraphQL::Client->new(class => 'http'); + isa_ok($client->transport, 'GraphQL::Client::http', 'decide transport from class'); + + $client = GraphQL::Client->new(url => 'https://localhost:4000/graphql'); + isa_ok($client->transport, 'GraphQL::Client::http', 'decide transport from url'); + + $client = GraphQL::Client->new(class => 'not a real class'); + is($client->class, 'not a real class', 'class constructor works'); + throws_ok { $client->transport } qr/^Failed to load transport/, 'throws if invalid transport'; +}; + +subtest 'request to transport' => sub { + my $mock = MockTransport->new; + my $client = GraphQL::Client->new(transport => $mock); + + $client->execute('{hello}'); + my $req = ($mock->requests)[-1]; + is_deeply($req->[0], { + query => '{hello}', + }, 'query is passed to transport'); + + $client->execute('{hello}', {foo => 'bar'}); + $req = ($mock->requests)[-1]; + is_deeply($req->[0], { + query => '{hello}', + variables => {foo => 'bar'}, + }, 'vars passed to transport'); + + $client->execute('{hello}', {foo => 'bar'}, 'opname'); + $req = ($mock->requests)[-1]; + is_deeply($req->[0], { + query => '{hello}', + variables => {foo => 'bar'}, + operationName => 'opname', + }, 'operationName passed to transport'); + + $client->execute('{hello}', {foo => 'bar'}, 'opname', {baz => 'qux'}); + $req = ($mock->requests)[-1]; + is_deeply($req->[1], { + baz => 'qux', + }, 'transport options passed to transport'); + + $client->execute('{hello}', {foo => 'bar'}, {baz => 'qux'}); + $req = ($mock->requests)[-1]; + is_deeply($req->[1], { + baz => 'qux', + }, 'operation name can be ommitted with transport options'); +}; + +subtest 'success response' => sub { + my $mock = MockTransport->new; + my $client = GraphQL::Client->new(transport => $mock); + + $mock->response({ + response => { + data => { + hello => 'Hello world!', + }, + }, + }); + my $resp = $client->execute('{hello}'); + is_deeply($resp, { + data => {hello => 'Hello world!'}, + }, 'response is packed') or diag explain $resp; + { + local $client->{unpack} = 1; + my $resp = $client->execute('{hello}'); + is_deeply($resp, { + hello => 'Hello world!', + }, 'success response is unpacked') or diag explain $resp; + }; + + $mock->response(Future->done({ + response => { + data => { + hello => 'Hello world!', + }, + }, + })); + my $f = $client->execute('{hello}'); + is_deeply($f->get, { + data => {hello => 'Hello world!'}, + }, 'future response is packed') or diag explain $f->get; + { + local $client->{unpack} = 1; + my $f = $client->execute('{hello}'); + is_deeply($f->get, { + hello => 'Hello world!', + }, 'future success response is unpacked') or diag explain $f->get; + }; +}; + +subtest 'response with errors' => sub { + my $mock = MockTransport->new; + my $client = GraphQL::Client->new(transport => $mock); + + $mock->response({ + response => { + data => { + hello => 'Hello world!', + }, + errors => [ + { + message => 'Uh oh', + }, + ], + }, + }); + my $resp = $client->execute('{hello}'); + is_deeply($resp, { + data => {hello => 'Hello world!'}, + errors => [{message => 'Uh oh'}], + }, 'response is packed') or diag explain $resp; + { + local $client->{unpack} = 1; + throws_ok { $client->execute('{hello}') } qr/^Uh oh$/, 'error response thrown'; + my $err = $@; + is($err->error, 'Uh oh', 'error message is from first error'); + is($err->type, 'graphql', 'error type is "graphql"'); + my $resp = $err->{response}; + is_deeply($resp, { + data => {hello => 'Hello world!'}, + errors => [{message => 'Uh oh'}], + }, 'error includes the response') or diag explain $resp; + }; + + $mock->response({ + response => undef, + error => 'Transport error', + details => { + foo => 'bar', + }, + }); + $resp = $client->execute('{hello}'); + is_deeply($resp, { + errors => [{message => 'Transport error'}], + }, 'unpacked response munges error into response') or diag explain $resp; + { + local $client->{unpack} = 1; + throws_ok { $client->execute('{hello}') } qr/^Transport error$/, 'error response thrown'; + my $err = $@; + my $resp = $err->{response}; + is_deeply($resp, { + errors => [{message => 'Transport error'}], + }, 'error includes the constructed response') or diag explain $resp; + }; +}; + +done_testing; diff --git a/t/http.t b/t/http.t new file mode 100755 index 0000000..61a9ccf --- /dev/null +++ b/t/http.t @@ -0,0 +1,217 @@ +#!/usr/bin/env perl + +use warnings; +use strict; + +use FindBin '$Bin'; +use lib "$Bin/lib"; + +use Test::Deep; +use Test::Exception; +use Test::More; + +use Future; +use GraphQL::Client::http; + +HTTP::AnyUA->register_backend(MockUA => '+MockUA'); + +my $URL = 'http://localhost:4000/graphql'; + +subtest 'attributes' => sub { + my $http = GraphQL::Client::http->new; + + is($http->method, 'POST', 'default method is POST'); + is($http->url, undef, 'default url is undefined'); + + $http = GraphQL::Client::http->new(method => 'HEAD', url => $URL); + + is($http->method, 'HEAD', 'method getter returns correctly'); + is($http->url, $URL, 'url getter returns correctly'); +}; + +subtest 'bad arguments to execute' => sub { + my $http = GraphQL::Client::http->new(ua => 'MockUA'); + my $mock = $http->any_ua->backend; + + throws_ok { + $http->execute('blah'); + } qr/^Usage:/, 'first argument must be a hashref'; + + throws_ok { + $http->execute({}); + } qr/^Request must have a query/, 'request must have a query'; + + throws_ok { + $http->execute({query => '{hello}'}); + } qr/^URL must be provided/, 'request must have a URL'; +}; + +subtest 'POST request' => sub { + my $http = GraphQL::Client::http->new(ua => 'MockUA', url => $URL); + my $mock = $http->any_ua->backend; + + my $resp = $http->execute({ + query => '{hello}', + }); + my $req = ($mock->requests)[-1]; + + is($req->[0], 'POST', 'method is POST'); + is($req->[2]{content}, '{"query":"{hello}"}', 'encoded body as JSON'); + is($req->[2]{headers}{'content-type'}, 'application/json', 'set content-type to json'); +}; + +subtest 'GET request' => sub { + my $http = GraphQL::Client::http->new(ua => 'MockUA', url => $URL); + my $mock = $http->any_ua->backend; + + $http->execute({ + query => '{hello}', + }, { + method => 'GET', + }); + my $req = ($mock->requests)[-1]; + + is($req->[0], 'GET', 'method is GET'); + is($req->[1], "$URL?query=%7Bhello%7D", 'encoded query in params'); + is($req->[2]{content}, undef, 'no content'); + + $http->execute({ + query => '{hello}', + }, { + method => 'GET', + url => "$URL?foo=bar", + }); + $req = ($mock->requests)[-1]; + + is($req->[1], "$URL?foo=bar&query=%7Bhello%7D", 'encoded query in params with existing param'); +}; + +subtest 'plain response' => sub { + my $http = GraphQL::Client::http->new(ua => 'MockUA', url => $URL); + my $mock = $http->any_ua->backend; + + $mock->response({ + content => '{"data":{"foo":"bar"}}', + reason => 'OK', + status => 200, + success => 1, + }); + my $r = $http->execute({query => '{hello}'}); + my $expected = { + response => { + data => {foo => 'bar'}, + }, + details => { + http_response => $mock->response, + }, + }; + is_deeply($r, $expected, 'success response') or diag explain $r; + + $mock->response({ + content => '{"data":{"foo":"bar"},"errors":[{"message":"uh oh"}]}', + reason => 'OK', + status => 200, + success => 1, + }); + $r = $http->execute({query => '{hello}'}); + $expected = { + response => { + data => {foo => 'bar'}, + errors => [{message => 'uh oh'}], + }, + details => { + http_response => $mock->response, + }, + }; + is_deeply($r, $expected, 'response with graphql errors') or diag explain $r; + + $mock->response({ + content => 'The agent failed', + reason => 'Internal Exception', + status => 599, + success => '', + }); + my $resp = $http->execute({query => '{hello}'}); + $expected = { + error => 'HTTP transport returned 599 (Internal Exception): The agent failed', + response => undef, + details => { + http_response => $mock->response, + }, + }; + is_deeply($resp, $expected, 'response with http error') or diag explain $resp; + + $mock->response({ + content => 'not json', + reason => 'OK', + status => 200, + success => 1, + }); + $r = $http->execute({query => '{hello}'}); + $expected = { + error => re('^HTTP transport failed to decode response:'), + response => undef, + details => { + http_response => $mock->response, + }, + }; + cmp_deeply($r, $expected, 'response with invalid response') or diag explain $r; +}; + +subtest 'future response' => sub { + my $http = GraphQL::Client::http->new(ua => 'MockUA', url => $URL); + my $mock = $http->any_ua->backend; + + $mock->response(Future->done({ + content => '{"data":{"foo":"bar"}}', + reason => 'OK', + status => 200, + success => 1, + })); + my $f = $http->execute({query => '{hello}'}); + my $expected = { + response => { + data => {foo => 'bar'}, + }, + details => { + http_response => $mock->response->get, + }, + }; + is_deeply($f->get, $expected, 'success response') or diag explain $f->get; + + $mock->response(Future->done({ + content => '{"data":{"foo":"bar"},"errors":[{"message":"uh oh"}]}', + reason => 'OK', + status => 200, + success => 1, + })); + $f = $http->execute({query => '{hello}'}); + $expected = { + response => { + data => {foo => 'bar'}, + errors => [{message => 'uh oh'}], + }, + details => { + http_response => $mock->response->get, + }, + }; + is_deeply($f->get, $expected, 'response with graphql errors') or diag explain $f->get; + + $mock->response(Future->fail({ + content => 'The agent failed', + reason => 'Internal Exception', + status => 599, + success => '', + })); + $expected = { + error => 'HTTP transport returned 599 (Internal Exception): The agent failed', + response => undef, + details => { + http_response => ($mock->response->failure)[0], + }, + }; + $f = $http->execute({query => '{hello}'}); + is_deeply($f->get, $expected, 'response with http error') or diag explain $f->get; +}; + +done_testing; diff --git a/t/https.t b/t/https.t new file mode 100755 index 0000000..c125a50 --- /dev/null +++ b/t/https.t @@ -0,0 +1,13 @@ +#!/usr/bin/env perl + +use warnings; +use strict; + +use Test::More; + +use GraphQL::Client::https; + +isa_ok('GraphQL::Client::https', 'GraphQL::Client::http'); +can_ok('GraphQL::Client::https', qw(new execute)); + +done_testing; diff --git a/t/lib/MockTransport.pm b/t/lib/MockTransport.pm new file mode 100644 index 0000000..7e4159f --- /dev/null +++ b/t/lib/MockTransport.pm @@ -0,0 +1,38 @@ +package MockTransport; +# ABSTRACT: A backend for testing HTTP::AnyUA + +use warnings; +use strict; + +sub new { bless {}, shift } + +=method response + + $response = $backend->response; + $response = $backend->response($response); + +Get and set the response hashref or L that this backend will always respond with. + +=cut + +sub response { @_ == 2 ? $_[0]->{response} = pop : $_[0]->{response} } + +=method requests + + @requests = $backend->requests; + +Get the requests the backend has handled so far. + +=cut + +sub requests { @{$_[0]->{requests} || []} } + +sub execute { + my $self = shift; + + push @{$self->{requests} ||= []}, [@_]; + + return $self->response; +} + +1; diff --git a/t/lib/MockUA.pm b/t/lib/MockUA.pm new file mode 100644 index 0000000..3ee2d70 --- /dev/null +++ b/t/lib/MockUA.pm @@ -0,0 +1,48 @@ +package MockUA; +# ABSTRACT: HTTP::AnyUA backend for testing GraphQL::Client::http + +use warnings; +use strict; + +use Scalar::Util qw(blessed); +use namespace::clean; + +use parent 'HTTP::AnyUA::Backend'; + +=method response + + $response = $backend->response; + $response = $backend->response($response); + +Get and set the response hashref or L that this backend will always respond with. + +=cut + +sub response { @_ == 2 ? $_[0]->{response} = pop : $_[0]->{response} } + +=method requests + + @requests = $backend->requests; + +Get the requests the backend has handled so far. + +=cut + +sub requests { @{$_[0]->{requests} || []} } + +sub response_is_future { blessed($_[0]->{response}) && $_[0]->{response}->isa('Future') } + +sub request { + my $self = shift; + + push @{$self->{requests} ||= []}, [@_]; + + return $self->response || { + success => '', + status => 599, + reason => 'Internal Exception', + content => "No response mocked.\n", + }; +} + +1; -- 2.43.0