Test::...r::TCP(3pm)

๐Ÿ“ฆ
version 1.20 ยท 5 versions
, in ubuntu noble, ubuntu resolute, ubuntu stonking

okay bestie, sit down, hydrate, because this is Test::POE::Server::TCP(3pm) from the User Contributed Perl Documentation and she is serving ๐Ÿ’… a whole POE component that hands you a ready-made TCP server so you never have to roll your own for a test case. no cap, this is the good stuff. ๐Ÿซถ


โœจ NAME โœจ

Test::POE::Server::TCP โ€” a POE Component providing TCP server services for test cases. that's the name, that's the whole assignment, and she ate. ๐Ÿ‘‘


๐ŸŒธ VERSION ๐ŸŒธ

version 1.20 โ€” noted, catalogued, on the record. ๐Ÿ’–


๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

okay so first up, a very simple echo server with logging of requests by each client. this is the whole vibe:

use strict;
use POE;
use Test::POE::Server::TCP;

POE::Session->create(
  package_states => [
     'main' => [qw(
                     _start
                     testd_connected
                     testd_disconnected
                     testd_client_input
     )],
  ],
);

$poe_kernel->run();
exit 0;

sub _start {
  # Spawn the Test::POE::Server::TCP server.
  $_[HEAP]->{testd} = Test::POE::Server::TCP->spawn(
     address => '127.0.0.1',
     port => 0,
  );
  return;
}

sub testd_connected {
  my ($heap,$id) = @_[HEAP,ARG0];

  # A client connected the unique ID is in ARG0
  # Create a blank arrayref for this client on *our* heap

  $heap->{clients}->{ $id } = [ ];

  return;
}

sub testd_client_input {
  my ($kernel,$heap,$sender,$id,$input) = @_[KERNEL,HEAP,SENDER,ARG0,ARG1];

  # The client sent us a line of input
  # lets store it

  push @{ $heap->{clients}->{ $id } }, $input;

  # Okay, we are an echo server so lets send it back to the client
  # We know the SENDER so can always obtain the server object.

  my $testd = $sender->get_heap();
  $testd->send_to_client( $id, $input );

  # Or even

  # $sender->get_heap()->send_to_client( $id, $input );

  # Alternatively we could just post back to the SENDER

  # $kernel->post( $sender, 'send_to_client', $id, $input );

  return;
}

sub testd_disconnected {
  my ($heap,$id) = @_[HEAP,ARG0];

  # Client disconnected for whatever reason
  # We need to free up our storage

  delete $heap->{clients}->{ $id };

  return;
}

and then, using the module in a testcase โ€” this is the main character energy right here:

use strict;
use Test::More;
use POE qw(Wheel::SocketFactory Wheel::ReadWrite Filter::Line);
use Test::POE::Server::TCP;

plan tests => 5;

my @data = (
  'This is a test',
  'This is another test',
  'This is the last test',
);

POE::Session->create(
  package_states => [
     'main' => [qw(
                     _start
                     _sock_up
                     _sock_fail
                     _sock_in
                     _sock_err
                     testd_connected
                     testd_disconnected
                     testd_client_input
     )],
  ],
  heap => { data => \@data, },
);

$poe_kernel->run();
exit 0;

sub _start {
  $_[HEAP]->{testd} = Test::POE::Server::TCP->spawn(
     address => '127.0.0.1',
     port => 0,
  );
  return;
}

sub testd_registered {
  my ($heap,$object) = @_[HEAP,ARG0];
  $heap->{port} = $object->port();
  $heap->{factory} = POE::Wheel::SocketFactory->new(
     RemoteAddress  => '127.0.0.1',
     RemotePort     => $heap->{port},
     SuccessEvent   => '_sock_up',
     FailureEvent   => '_sock_fail',
  );
  return;
}

sub _sock_up {
  my ($heap,$socket) = @_[HEAP,ARG0];
  delete $heap->{factory};
  $heap->{socket} = POE::Wheel::ReadWrite->new(
     Handle => $socket,
     InputEvent => '_sock_in',
     ErrorEvent => '_sock_err',
  );
  $heap->{socket}->put( $heap->{data}->[0] );
  return;
}

sub _sock_fail {
  my $heap = $_[HEAP];
  delete $heap->{factory};
  $heap->{testd}->shutdown();
  return;
}

sub _sock_in {
  my ($heap,$input) = @_[HEAP,ARG0];
  my $data = shift @{ $heap->{data} };
  ok( $input eq $data, 'Data matched' );
  unless ( scalar @{ $heap->{data} } ) {
    delete $heap->{socket};
    return;
  }
  $heap->{socket}->put( $heap->{data}->[0] );
  return;
}

sub _sock_err {
  delete $_[HEAP]->{socket};
  return;
}

sub testd_connected {
  my ($heap,$state,$id) = @_[HEAP,STATE,ARG0];
  pass($state);
  return;
}

sub testd_disconnected {
  pass($_[STATE]);
  $poe_kernel->post( $_[SENDER], 'shutdown' );
  return;
}

sub testd_client_input {
  my ($sender,$id,$input) = @_[SENDER,ARG0,ARG1];
  my $testd = $_[SENDER]->get_heap();
  $testd->send_to_client( $id, $input );
  return;
}

๐Ÿ’œ DESCRIPTION ๐Ÿ’œ

so Test::POE::Server::TCP is a POE component that gives you a TCP server framework you can drop straight into your client component test cases โ€” instead of having to roll your own. which, respectfully, you don't want to do. let the component cook. ๐ŸŽ€

once you're registered with the component, a session will receive events about client connects, disconnects, input and flushed output. every single one of those events refers to a unique client ID, and you use that ID to talk back to the component whenever you want to send data to the client or disconnect a client connection. iykyk. ๐Ÿ’…

and lowkey important: if AF_INET6 sockets are supported, the component will create an AF_INET socket and an AF_INET6 socket. two sockets, one legend. โœจ


๐Ÿ‘‘ CONSTRUCTOR ๐Ÿ‘‘

๐ŸŽ€ spawn ๐ŸŽ€

takes a number of optional arguments, bestie. here they all are:

  • 'alias' โ€” set an alias on the component;
  • 'address' โ€” bind the listening socket to a particular address;
  • 'port' โ€” listen on a particular port, default is 0, assign a random port;
  • 'options' โ€” a hashref of POE::Session options;
  • 'filter' โ€” specify a POE::Filter to use for client connections, default is POE::Filter::Line;
  • 'inputfilter' โ€” specify a POE::Filter for client input;
  • 'outputfilter' โ€” specify a POE::Filter for output to clients;
  • 'prefix' โ€” specify a different prefix than 'testd' for events;

the semantics for filter, inputfilter and outputfilter are the same as for POE::Component::Server::TCP โ€” you can hand it either a SCALAR, an ARRAYREF or an OBJECT. pick your fighter. ๐Ÿซถ

and if the component gets spawned inside another session, it will automatically register the parent session to receive all events. yes, automatically. it's giving thoughtful. ๐Ÿ’–


๐Ÿ’… METHODS ๐Ÿ’…

๐Ÿ’ซ session_id

returns the POE::Session ID of the component. your little serial number. ๐ŸŒธ

๐Ÿ’ซ shutdown

terminates the component. shuts down the listener and disconnects connected clients. bye bestie, everyone's leaving the group chat. ๐Ÿ˜ญ

๐Ÿ’ซ send_to_client

send some output to a connected client. first parameter must be a valid client id. second parameter is a string of text to send. the second parameter may also be an arrayref of items to send to the client. and heads up โ€” if the filter you've used requires an arrayref as input, you gotta nest that arrayref within another arrayref. arrayref in arrayref, it's layers. ๐Ÿงš

๐Ÿ’ซ send_to_all_clients

send some output to all connected clients. the parameter is a string of text to send. the parameter may also be an arrayref of items to send to the clients. and same deal as before: if the filter you've used requires an arrayref as input, nest that arrayref within another arrayref. ๐Ÿ‘‘

๐Ÿ’ซ client_info

retrieve socket information of a given client. requires a valid client ID as a parameter. in a list context it returns a list consisting of, in order, the client address, the client TCP port, our address and our TCP port. in a scalar context it returns a HASHREF with these keys:

  • 'peeraddr' โ€” the client address;
  • 'peerport' โ€” the client TCP port;
  • 'sockaddr' โ€” our address;
  • 'sockport' โ€” our TCP port;

๐Ÿ’ซ client_wheel

retrieve the POE::Wheel::ReadWrite object of a given client. requires a valid client ID as a parameter. this is your backstage pass โ€” it lets you manipulate that POE::Wheel::ReadWrite object, like switching the POE::Filter. slay. โœจ

๐Ÿ’ซ disconnect

places a client connection in pending disconnect state. requires a valid client ID as a parameter. set this, then send an applicable message to the client using send_to_client() and the client connection will be terminated. give them a little goodbye speech first, that's the point. ๐ŸŽ€

๐Ÿ’ซ terminate

immediately disconnects a client connection. requires a valid client ID as a parameter. no goodbye, just gone. ๐Ÿ’€

๐Ÿ’ซ pause_listening

stops the underlying listening socket from accepting new connections. this lets you test whether you handle the connection timing out gracefully. dramatic, but necessary. ๐Ÿซถ

๐Ÿ’ซ resume_listening

the companion of pause_listening. the other half of the duo. ๐ŸŒˆ

๐Ÿ’ซ getsockname

access to the POE::Wheel::SocketFactory method of the underlying listening AF_INET socket.

๐Ÿ’ซ port

returns the port that the component is listening on.

๐Ÿ’ซ getsockname6

access to the POE::Wheel::SocketFactory method of the underlying listening AF_INET6 socket.

๐Ÿ’ซ port6

returns the port that the component is listening on for AF_INET6.

๐Ÿ’ซ start_listener

if the listener fails on listen you can attempt to restart it with this. second chances, we love to see it. ๐Ÿ’–

๐Ÿ’Œ INPUT EVENTS ๐Ÿ’Œ

okay so here's the tea bestie โ€” these are the events your component will actually accept. like, the ones you can throw at it:

  • register โ€” takes N arguments, which is just a list of the event names your session wants to listen for, minus the testd_ prefix. ๐Ÿซถ and if you register for all? it'll just send you every single TESTD-related event that exists. easiest way to do it, no cap, that's the move.
  • unregister โ€” also takes N arguments: a list of event names you don't wanna receive anymore. so if you previously did a register for some event you've now decided you don't care about, this is how you tell the POP3D to stop sending them your way. (and if you never registered for it in the first place? it just ignores you. no big deal, we move.) ๐Ÿ’…
  • shutdown โ€” terminates the component, periodt. shuts down the listener AND disconnects all the connected clients. it's giving full lights-off ๐Ÿ•ฏ๏ธ
  • send_to_client โ€” sends some output to a connected client. first parameter has to be a valid client id, second parameter is a string of text to send. and plot twist: that second parameter can also be an arrayref of items to send to the client. if the filter you've used requires an arrayref as input, then you nest that arrayref inside another arrayref. arrayref-ception, iykyk. ๐Ÿช†
  • send_to_all_clients โ€” same energy, but to every connected client. the parameter is a string of text to send, and it may also be an arrayref of items to send to the clients. and yes bestie, same rule applies: if your filter needs an arrayref as input, nest that arrayref within another arrayref. โœจ
  • disconnect โ€” puts a client connection into pending disconnect state. needs a valid client ID as a parameter. the whole ritual is: set this, then send an applicable message to the client using send_to_client(), and the client connection gets terminated. it's a two-step goodbye ๐Ÿฅ€
  • terminate โ€” immediately disconnects a client connection. requires a valid client ID as a parameter. no waiting, no ceremony, just gone. ๐Ÿ’€
  • start_listener โ€” if the listener fails on listen, you can attempt to restart it with this. little respawn button, very demure ๐ŸŽ€

๐ŸŒˆ OUTPUT EVENTS ๐ŸŒˆ

so this is the other direction โ€” the component sends these following events to registered sessions. oh and heads up: if you changed the prefix option in spawn, then swap out testd for whatever event prefix you specified. keep that in mind or you'll be waiting for events that never come ๐Ÿ˜ญ

  • testd_registered โ€” this event gets sent to a registering session. ARG0 is the Test::POE::Server::TCP object. hi bestie, nice to meet u ๐Ÿซถ
  • testd_listener_failed โ€” generated if the component can't either start a listener or there's a problem accepting client connections. ARG0 contains the name of the operation that failed. ARG1 and ARG2 hold numeric and string values for $!, respectively. and if the operation was listen, the component will remove the listener โ€” at which point you may attempt to start it again using start_listener. so like, it's not over over. ๐Ÿ˜ฎโ€๐Ÿ’จ
  • testd_connected โ€” generated whenever a client connects to the component. ARG0 is the client ID, ARG1 is the client's IP address, ARG2 is the client's TCP port, ARG3 is our IP address and ARG4 is our socket port. new friend acquired ๐Ÿฆ‹
  • testd_disconnected โ€” generated whenever a client disconnects. ARG0 was the client ID, ARG1 was the client's IP address, ARG2 was the client's TCP port, ARG3 was our IP address and ARG4 was our socket port. past tense because they're gone, bestie, we're in the mourning era ๐Ÿฅฒ
  • testd_client_input โ€” generated whenever a client sends us some traffic. ARG0 is the client ID, ARG1 is the data sent ( tokenised by whatever POE::Filter you specified ). the filter is doing the heavy lifting here, iconic ๐ŸŒธ
  • testd_client_flushed โ€” generated whenever anything we send to the client is actually flushed down the 'line'. ARG0 is the client ID. it's out there now, living its best life out in the world โœจ

๐Ÿ† CREDITS ๐Ÿ†

this module uses code borrowed from POE::Component::Server::TCP by Rocco Caputo, Ann Barcomb and Jos Boumans. giving credit where credit is due, always ๐Ÿ’–

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

  • POE
  • POE::Component::Server::TCP

๐Ÿ‘‘ AUTHOR ๐Ÿ‘‘

Chris Williams <chris@bingosnet.co.uk>

this software is copyright (c) 2016 by Chris Williams, Rocco Caputo, Ann Barcomb and Jos Boumans.

this is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. free as in go wild, bestie ๐ŸŽ‰


and that's the whole thing, babes โœจ this was part of perl v5.36.0, dated 2022-10-14, and the page is Test::...r::TCP(3pm). go forth, spawn some TCP, slay ๐Ÿ’…๐ŸŒธ๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from