Skip to content

Commit 86cf1f2

Browse files
committed
add test helper for querying ES
1 parent 23b4179 commit 86cf1f2

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

t/lib/MetaCPAN/Server/Test.pm

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,21 @@ use strict;
44
use warnings;
55
use feature qw(state);
66

7+
use Carp qw( croak );
78
use HTTP::Request::Common qw( DELETE GET POST ); ## no perlimports
9+
use MetaCPAN::ESConfig qw( es_doc_path );
810
use MetaCPAN::Model ();
911
use MetaCPAN::Server ();
1012
use MetaCPAN::Server::Config ();
1113
use MetaCPAN::Types::TypeTiny qw( ES );
14+
use MetaCPAN::Util qw( hit_total );
1215
use Plack::Test; ## no perlimports
1316

1417
use base 'Exporter';
1518
our @EXPORT_OK = qw(
1619
POST GET DELETE
1720
es
21+
es_result
1822
model
1923
test_psgi app
2024
query
@@ -57,6 +61,28 @@ sub query {
5761
state $query = MetaCPAN::Query->new( es => es() );
5862
}
5963

64+
sub es_result {
65+
my ( $type, $query, $size ) = @_;
66+
$size //= wantarray ? 999 : 1;
67+
if ( !wantarray && $size != 1 ) {
68+
croak "multiple results requested with scalar return!";
69+
}
70+
my $res = es()->search(
71+
es_doc_path($type),
72+
body => {
73+
size => ( wantarray ? 999 : 1 ),
74+
query => $query,
75+
},
76+
);
77+
my @hits = map $_->{_source}, @{ $res->{hits}{hits} };
78+
if ( !wantarray ) {
79+
croak "query did not return a single result"
80+
if hit_total($res) != 1;
81+
return $hits[0];
82+
}
83+
return @hits;
84+
}
85+
6086
1;
6187

6288
=pod

0 commit comments

Comments
 (0)