Mojo-Pg-Che

 view release on metacpan or  search on metacpan

t/06-base-pubsub.t  view on Meta::CPAN

use Mojo::Base -strict;

BEGIN { $ENV{MOJO_REACTOR} = 'Mojo::Reactor::Poll' }

use Test::More;

#~ plan skip_all => 'set TEST_ONLINE to enable this test' unless $ENV{TEST_ONLINE};
plan skip_all => 'set env TEST_PG="dbname=<...>/<pg_user>/<passwd>" to enable this test' unless $ENV{TEST_PG};
my ($dsn, $user, $pw) = split m|[/]|, $ENV{TEST_PG};

use Mojo::IOLoop;
use Mojo::JSON 'true';
use Mojo::Pg::Che;

# Notifications with event loop
#~ my $pg = Mojo::Pg->new($ENV{TEST_ONLINE});
my $pg = Mojo::Pg::Che->connect($dsn, $user, $pw)->pg;
my ($db, @all, @test);
$pg->pubsub->on(reconnect => sub { $db = pop });
$pg->pubsub->listen(
  pstest => sub {
    my ($pubsub, $payload) = @_;
    push @test, $payload;
    Mojo::IOLoop->next_tick(sub { $pubsub->pg->db->notify(pstest => 'stop') });
    Mojo::IOLoop->stop if $payload eq 'stop';
  }
);
$db->on(notification => sub { push @all, [@_[1, 3]] });
$pg->db->notify(pstest => '♥test♥');
Mojo::IOLoop->start;
is_deeply \@test, ['♥test♥', 'stop'], 'right messages';
is_deeply \@all, [['pstest', '♥test♥'], ['pstest', 'stop']],
  'right notifications';

# JSON
#~ $pg = Mojo::Pg->new($ENV{TEST_ONLINE});
$pg = Mojo::Pg::Che->connect($dsn, $user, $pw)->pg;
my (@json, @raw);
$pg->pubsub->json('pstest')->listen(
  pstest => sub {
    my ($pubsub, $payload) = @_;
    push @json, $payload;
    Mojo::IOLoop->stop if ref $payload eq 'HASH' && $payload->{msg} eq 'stop';
  }
);
$pg->pubsub->listen(
  pstest2 => sub {
    my ($pubsub, $payload) = @_;
    push @raw, $payload;
  }
);
Mojo::IOLoop->next_tick(sub {
  $pg->db->notify(pstest => 'fail');
  $pg->pubsub->notify('pstest')->notify(pstest => {msg => '♥works♥'})
    ->notify(pstest => [1, 2, 3])->notify(pstest => true)
    ->notify(pstest2 => '♥works♥')->notify(pstest => {msg => 'stop'});
});
Mojo::IOLoop->start;
is_deeply \@json,
  [undef, undef, {msg => '♥works♥'}, [1, 2, 3], true, {msg => 'stop'}],
  'right data structures';
is_deeply \@raw, ['♥works♥'], 'right messages';

# Unsubscribe
#~ $pg = Mojo::Pg->new($ENV{TEST_ONLINE});
$pg = Mojo::Pg::Che->connect($dsn, $user, $pw)->pg;
$db = undef;
$pg->pubsub->on(reconnect => sub { $db = pop });
@all = @test = ();



( run in 0.952 second using v1.01-cache-2.11-cpan-71847e10f99 )