Browse Source

Normalize the constructor:

Allow a service to be provided, while we're at it.
Sawyer X 5 years ago
parent
commit
96d5487244
3 changed files with 49 additions and 10 deletions
  1. 2 1
      Makefile.PL
  2. 14 9
      lib/HBase/JSONRest.pm
  3. 33 0
      t/constructor.t

+ 2 - 1
Makefile.PL

@ -15,7 +15,8 @@ WriteMakefile(
15 15
        'ExtUtils::MakeMaker' => 0,
16 16
    },
17 17
    BUILD_REQUIRES => {
18
        'Test::More' => 0,
18
        'Test::More'  => 0,
19
        'Test::Fatal' => 0,
19 20
    },
20 21
    PREREQ_PM => {
21 22
        'HTTP::Tiny'   => 0,

+ 14 - 9
lib/HBase/JSONRest.pm

@ -3,15 +3,12 @@ package HBase::JSONRest;
3 3
use strict;
4 4
use warnings;
5 5
6
use Carp;
6 7
use HTTP::Tiny;
7
8 8
use URI::Escape;
9
10 9
use MIME::Base64;
11 10
use JSON::XS qw(decode_json encode_json);
12
13 11
use Time::HiRes qw(gettimeofday time);
14
15 12
use Data::Dumper;
16 13
17 14
our $VERSION = "0.001";
@ -28,14 +25,22 @@ sub new {
28 25
    my $class  = shift;
29 26
    my %params = @_;
30 27
31
    die "Need a service host!"
32
        if ! defined $params{host};
28
    # default port
29
    $params{'port'} ||= 8080;
33 30
34
    $params{port} ||= 8080;
31
    # missing service, we'll create it ourselves
32
    if ( ! defined $params{'service'} ) {
33
        # but we need a host for that
34
        defined $params{'host'}
35
            or croak 'Must provide a service, or a host and port';
35 36
36
    $params{service} = "http://" . $params{host} . ":" . $params{port};
37
        # set it up
38
        $params{'service'} =
39
            sprintf 'http://%s:%d', @params{qw<host port>};
40
    }
37 41
38
    return bless {%params}, $class;
42
    # we only care about the service, and we assured it exists
43
    return bless { service => $params{'service'} }, $class;
39 44
}
40 45
41 46

+ 33 - 0
t/constructor.t

@ -0,0 +1,33 @@
1
#!perl
2
3
use strict;
4
use warnings;
5
6
use Test::Fatal;
7
use HBase::JSONRest;
8
use Test::More tests => 7;
9
10
like(
11
    exception { HBase::JSONRest->new },
12
    qr/^Must provide a service, or a host and port/,
13
    'Fails without a service or data to build a service',
14
);
15
16
{
17
    my $hb = HBase::JSONRest->new( service => 'MyService' );
18
    isa_ok( $hb, 'HBase::JSONRest' );
19
    is( $hb->{'service'}, 'MyService', 'Stored the service' );
20
}
21
22
{
23
    my $hb = HBase::JSONRest->new( host => 'MyHost' );
24
    isa_ok( $hb, 'HBase::JSONRest' );
25
    is( $hb->{'service'}, 'http://MyHost:8080', 'Created correct service' );
26
}
27
28
{
29
    my $hb = HBase::JSONRest->new( host => 'MyHost', port => 2020 );
30
    isa_ok( $hb, 'HBase::JSONRest' );
31
    is( $hb->{'service'}, 'http://MyHost:2020', 'Created correct service' );
32
}
33