Kubernetes-REST
view release on metacpan or search on metacpan
t/lib/Test/Kubernetes/Mock.pm view on Meta::CPAN
package Test::Kubernetes::Mock;
# Mock HTTP responses for Kubernetes::REST tests
use strict;
use warnings;
use JSON::MaybeXS;
use Path::Tiny qw(path);
use Exporter 'import';
our @EXPORT_OK = qw(mock_api live_api is_live record_response);
my $MOCK_DIR = path(__FILE__)->parent->parent->parent->parent->child('mock');
my $json = JSON::MaybeXS->new->pretty->canonical;
# Keep kubeconfig object alive so temp cert files aren't deleted
my $_kubeconfig;
# Check if we should use live cluster
# Requires TEST_KUBERNETES_REST_KUBECONFIG to be set explicitly (safety measure)
sub is_live {
return 0 unless $ENV{TEST_KUBERNETES_REST_KUBECONFIG};
return 1;
}
# Get API - either mock or live based on environment
sub mock_api {
require Kubernetes::REST;
require Kubernetes::REST::Server;
require Kubernetes::REST::AuthToken;
return Kubernetes::REST->new(
server => Kubernetes::REST::Server->new(endpoint => 'http://mock.local'),
credentials => Kubernetes::REST::AuthToken->new(token => 'MockToken'),
resource_map_from_cluster => 0,
io => Test::Kubernetes::Mock::IO->new,
);
}
sub live_api {
require Kubernetes::REST::Kubeconfig;
die "TEST_KUBERNETES_REST_KUBECONFIG must be set for live tests"
unless $ENV{TEST_KUBERNETES_REST_KUBECONFIG};
my %args = (kubeconfig_path => $ENV{TEST_KUBERNETES_REST_KUBECONFIG});
$args{context_name} = $ENV{TEST_KUBERNETES_REST_CONTEXT} if $ENV{TEST_KUBERNETES_REST_CONTEXT};
# Keep kubeconfig alive so temp cert files aren't deleted
$_kubeconfig = Kubernetes::REST::Kubeconfig->new(%args);
return $_kubeconfig->api;
}
# Record a response to mock file
sub record_response {
my ($name, $data) = @_;
my $file = $MOCK_DIR->child("$name.json");
$file->spew_utf8($json->encode($data));
return $file;
}
# Load mock response
sub load_response {
my ($name) = @_;
my $file = $MOCK_DIR->child("$name.json");
return undef unless $file->exists;
return $json->decode($file->slurp_utf8);
}
# Mock IO class that returns recorded responses
package Test::Kubernetes::Mock::IO;
use Moo;
with 'Kubernetes::REST::Role::IO';
has responses => (
is => 'ro',
default => sub { {} },
);
has watch_events => (
is => 'ro',
default => sub { {} },
);
has log_lines => (
is => 'ro',
default => sub { {} },
);
sub add_response {
my ($self, $method, $path, $data) = @_;
my $key = lc($method) . $path;
$key =~ s{/}{_}g;
$key =~ s{_+}{_}g;
$key =~ s{^_}{};
$self->responses->{$key} = $data;
( run in 0.531 second using v1.01-cache-2.11-cpan-524268b4103 )