TT#68300 Load the configuration file from the constructor

We should not be running code that loads a configuration file in
a BEGIN block, as that will execute just by loading the module.

This makes using this module conditionally in other programs or testing
that code more difficult, as we would need to mock either this module
or the configuration file.

Just load the configuration file once in the constructor and cache
its contents, to avoid the overhead.

Change-Id: I86986dc81eaa32833b738ffa6df2a5de30159482
changes/03/34103/4
Guillem Jover 6 years ago
parent 155873d532
commit 97c0fb6412

@ -1,6 +1,8 @@
package NGCP::API::Client;
use strict;
use warnings;
use feature qw(state);
use English qw(-no_match_vars);
use Config::Tiny;
use JSON::XS;
@ -9,15 +11,34 @@ use LWP::UserAgent;
use Readonly;
use URI;
my $config;
sub _load_config_defaults {
my $cfg_file = '/etc/default/ngcp-api';
my $cfg;
$cfg = Config::Tiny->read($cfg_file)
or die "Cannot read $cfg_file: $ERRNO";
Readonly my $config => {
host => $cfg->{_}->{NGCP_API_IP},
port => $cfg->{_}->{NGCP_API_PORT},
iface => $cfg->{_}->{NGCP_API_IFACE},
sslverify => $cfg->{_}->{NGCP_API_SSLVERIFY} || 'yes',
sslverify_lb => $cfg->{_}->{NGCP_API_SSLVERIFY_LOOPBACK} || 'no',
read_timeout => $cfg->{_}->{NGCP_API_READ_TIMEOUT} || 180,
page_rows => $cfg->{_}->{NGCP_API_PAGE_ROWS} // 10,
auth_user => $cfg->{_}->{AUTH_SYSTEM_LOGIN},
auth_pass => $cfg->{_}->{AUTH_SYSTEM_PASSWORD},
verbose => 0,
};
return $config;
}
BEGIN {
my $cfg_file = "/etc/default/ngcp-api";
$config = Config::Tiny->read($cfg_file)
or die "Cannot read $cfg_file: $ERRNO";
};
sub _get_config_defaults {
state $config = _load_config_defaults();
Readonly::Scalar my $cfg => $config;
return $config;
}
my %opts = ();
@ -83,18 +104,12 @@ sub new {
my $class = shift;
my $self = {};
$opts{host} = $cfg->{_}->{NGCP_API_IP};
$opts{port} = $cfg->{_}->{NGCP_API_PORT};
$opts{iface} = $cfg->{_}->{NGCP_API_IFACE};
$opts{sslverify} = $cfg->{_}->{NGCP_API_SSLVERIFY} || 'yes';
$opts{sslverify_lb} = $cfg->{_}->{NGCP_API_SSLVERIFY_LOOPBACK} || 'no';
$opts{read_timeout} = $cfg->{_}->{NGCP_API_READ_TIMEOUT} || 180;
$opts{auth_user} = $cfg->{_}->{AUTH_SYSTEM_LOGIN};
$opts{auth_pass} = $cfg->{_}->{AUTH_SYSTEM_PASSWORD};
$opts{verbose} = 0;
bless $self, $class;
$self->set_page_rows($cfg->{_}->{NGCP_API_PAGE_ROWS} // 10);
my $default_opts = _get_config_defaults();
foreach my $opt (keys %{$default_opts}) {
$opts{$opt} //= $default_opts->{$opt};
}
$self->_create_ua();
return $self;

Loading…
Cancel
Save