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

πŸ“¦
version 1.26 Β· 4 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– NAME πŸ’–

Test::POE::Client::TCP β€” bestie, it's a POE component that hands you TCP client services for your test cases. That's the whole vibe. It's a User Contributed Perl Documentation page, and it's here to save you from writing your own client junk from scratch. 🫢


✨ VERSION ✨

version 1.26


πŸ¦‹ SYNOPSIS πŸ¦‹

okay so here's the whole thing in action, no cap:

  use strict;
  use Socket;
  use Test::More tests => 15;
  use POE qw(Wheel::SocketFactory Wheel::ReadWrite Filter::Line);
  use Test::POE::Client::TCP;

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

  POE::Session->create(
    package_states => [
        'main' => [qw(
                        _start
                        _accept
                        _failed
                        _sock_in
                        _sock_err
                        testc_registered
                        testc_connected
                        testc_disconnected
                        testc_input
                        testc_flushed
        )],
    ],
    heap => { data => \@data, },
  );

  $poe_kernel->run();
  exit 0;

  sub _start {
    my ($kernel,$heap) = @_[KERNEL,HEAP];
    $heap->{listener} = POE::Wheel::SocketFactory->new(
        BindAddress    => '127.0.0.1',
        SuccessEvent   => '_accept',
        FailureEvent   => '_failed',
        SocketDomain   => AF_INET,             # Sets the socket() domain
        SocketType     => SOCK_STREAM,         # Sets the socket() type
        SocketProtocol => 'tcp',               # Sets the socket() protocol
        Reuse          => 'on',                # Lets the port be reused
    );
    $heap->{testc} = Test::POE::Client::TCP->spawn();
    return;
  }

  sub _accept {
    my ($kernel,$heap,$socket) = @_[KERNEL,HEAP,ARG0];
    my $wheel = POE::Wheel::ReadWrite->new(
        Handle       => $socket,
        InputEvent   => '_sock_in',
        ErrorEvent   => '_sock_err',
    );
    $heap->{wheels}->{ $wheel->ID } = $wheel;
    return;
  }

  sub _failed {
    my ($kernel,$heap,$operation,$errnum,$errstr,$wheel_id) = @_[KERNEL,HEAP,ARG0..ARG3];
    die "Wheel $wheel_id generated $operation error $errnum: $errstr\n";
    return;
  }

  sub _sock_in {
    my ($heap,$input,$wheel_id) = @_[HEAP,ARG0,ARG1];
    pass('Got input from client');
    $heap->{wheels}->{ $wheel_id }->put( $input ) if $heap->{wheels}->{ $wheel_id };
    return;
  }

  sub _sock_err {
    my ($heap,$wheel_id) = @_[HEAP,ARG3];
    pass('Client disconnected');
    delete $heap->{wheels}->{ $wheel_id };
    return;
  }

  sub testc_registered {
    my ($kernel,$sender,$object) = @_[KERNEL,SENDER,ARG0];
    pass($_[STATE]);
    my $port = ( sockaddr_in( $_[HEAP]->{listener}->getsockname() ) )[0];
    $kernel->post( $sender, 'connect', { address => '127.0.0.1', port => $port } );
    return;
  }

  sub testc_connected {
    my ($kernel,$heap,$sender) = @_[KERNEL,HEAP,SENDER];
    pass($_[STATE]);
    $kernel->post( $sender, 'send_to_server', $heap->{data}->[0] );
    return;
  }

  sub testc_flushed {
    pass($_[STATE]);
    return;
  }

  sub testc_input {
    my ($heap,$input) = @_[HEAP,ARG0];
    pass('Got something back from the server');
    my $data = shift @{ $heap->{data} };
    ok( $input eq $data, "Data matched: '$input'" );
    unless ( scalar @{ $heap->{data} } ) {
      $heap->{testc}->terminate();
      return;
    }
    $poe_kernel->post( $_[SENDER], 'send_to_server', $heap->{data}->[0] );
    return;
  }

  sub testc_disconnected {
    my ($heap,$state) = @_[HEAP,STATE];
    pass($state);
    delete $heap->{wheels};
    delete $heap->{listener};
    $heap->{testc}->shutdown();
    return;
  }

🌸 DESCRIPTION 🌸

So Test::POE::Client::TCP is literally a POE component that gives you a whole TCP client framework you can drop straight into your client component test cases. The way that you don't have to roll your own?? Iconic. πŸ’…

Once a session is registered with the component, bestie, it starts receiving events about connections made, disconnects, flushed output, and input from the server you specified. That's the whole tea. πŸ“


πŸŽ€ CONSTRUCTOR πŸŽ€

spawn

Takes a whole lil menu of optional arguments, no cap:

  • 'alias' β€” set an alias on the component
  • 'address' β€” the remote address to connect to
  • 'port' β€” the remote port to connect to
  • '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
  • 'localaddr' β€” specify that connections be made from a particular local address
  • 'localport' β€” specify that connections be made from a particular port
  • 'autoconnect' β€” set to a true value to make the poco connect immediately
  • 'prefix' β€” specify an event prefix other than the default of 'testc'
  • 'timeout' β€” specify number of seconds to wait for socket timeouts
  • 'context' β€” anything that can fit into a scalar, such as a ref, etc.
  • 'usessl' β€” enable SSL/TLS if POE::Component::SSLify is available
  • 'sslctx' β€” set to a SSL Context to configure the SSL Connection
  • 'sslcert' β€” set to a x509 Certificate(PEM encoded) to connect using a client cert
  • 'sslkey' β€” set to a private Key(PEM encoded) to connect using a client cert

The semantics for filter, inputfilter and outputfilter are the same as for POE::Component::Server::TCP β€” you can hand it a SCALAR, an ARRAYREF or an OBJECT. Pick your fighter. ✨

If the component gets spawned inside another session, it will automatically register the parent session to receive all events. Sweet deal honestly.

address and port are optional inside spawn, but if you don't specify them here, they must be provided to the subsequent connects. And if autoconnect is specified, then address and port must also be defined. Rules are rules. 🫢

usessl is dependent on whether POE::Component::SSLify is available. Just so you know. πŸ‘‘

πŸ’… METHODS πŸ’…

connect

Initiates a connection to the given server. Takes a bunch of parameters:

  • 'address' β€” the remote address to connect to
  • 'port' β€” the remote port to connect to
  • 'localaddr' β€” specify that connections be made from a particular local address, optional
  • 'localport' β€” specify that connections be made from a particular port, optional
  • 'usessl' β€” enable SSL/TLS if POE::Component::SSLify is available

address and port are optional if they've already been specified during spawn. iykyk.

session_id

Returns the POE::Session ID of the component. That's it, that's the method. πŸŽ€

shutdown

Terminates the component. It will terminate any pending connects or connections too β€” no loose threads left hanging, periodt. πŸ”₯

server_info

Retrieves socket information about the current connection. In a list context it returns a list consisting of, in order, the server address, the server TCP port, our address and our TCP port. In a scalar context it returns a HASHREF with these keys:

  • 'peeraddr' β€” the server address
  • 'peerport' β€” the server TCP port
  • 'sockaddr' β€” our address
  • 'sockport' β€” our TCP port

send_to_server

Send some output to the connected server. The first parameter is a string of text to send. This parameter may also be an arrayref of items to send to the client. And bestie, listen β€” if the filter you used requires an arrayref as input, you gotta nest that arrayref within another arrayref. Yes really. πŸ™ˆ

disconnect

Places the server connection into pending disconnect state. So you set this, then send an applicable message to the server using send_to_server(), and then the server connection gets terminated. Polite little goodbye. πŸ’œ

terminate

Immediately disconnects a server connection. No goodbye, just gone. πŸ’€

wheel

Returns the underlying POE::Wheel::ReadWrite object if we're currently connected to a server, and undef otherwise. You can use this method to call methods on the wheel object to switch filters, etc.

Exercise caution. Fr fr. Be careful with that thing. ⚠️

alias

Returns the currently configured alias.

context

Returns whatever was provided as context when the component was spawned. If nothing was provided, then it returns nothing. Ghosted. πŸ‘»


🌈 INPUT EVENTS 🌈

These are the events the component will accept, bestie:

register

Takes N arguments: a list of event names that your session wants to listen for, minus the 'testc_' prefix.

Registering for 'all' will cause it to send all TESTC-related events to you β€” and honestly that's the easiest way to handle it. Just do that. πŸ’…

unregister

Takes N arguments: a list of event names which you don't want to receive. If you've previously done a 'register' for a particular event that you no longer care about, this event tells the poco to stop sending them to you. (And if you haven't registered for it? It just ignores you. No big deal, bestie. 🫢)

connect

Initiates a connection to the given server. Takes a number of parameters:

  • 'address' β€” the remote address to connect to
  • 'port' β€” the remote port to connect to
  • 'localaddr' β€” specify that connections be made from a particular local address, optional
  • 'localport' β€” specify that connections be made from a particular port, optional

address and port are optional if they've already been specified during spawn.

shutdown

Terminates the component. It will terminate any pending connects or connections. Slay, clean exit. ✨

send_to_server

Send some output to the connected server. The first parameter is a string of text to send. This parameter may also be an arrayref of items to send to the client. If the filter you have used requires an arrayref as input, nest that arrayref within another arrayref. (Same deal as up top, queen. πŸ‘‘)

disconnect

Places the server connection into pending disconnect state. Set this, then send an applicable message to the server using send_to_server(), and the server connection will be terminated.

terminate

Immediately disconnects a server connection. Rude but efficient. πŸ’€

✨ OUTPUT EVENTS ✨

okay so this is the other direction β€” the stuff we send out into the world πŸ’Œ. The component fires these events off to whatever sessions are registered. And bestie, quick note: if you went and changed the prefix option back in spawn, then just swap testc out for whatever prefix you picked, iykyk πŸŽ€


🌸 testc_registered

This one gets sent to a session that's registering. ARG0 is the Test::POE::Client::TCP object β€” that's your whole little guy right there 🫢

πŸ’€ testc_socket_failed

Fired when the component literally cannot make a socket connection. ARG0 holds the name of the operation that failed. ARG1 and ARG2 carry the numeric and string values for $!, respectively. So yeah, when it all falls apart, at least it tells you how 😭

🌈 testc_connected

Generated every single time a connection gets established. ARG0 is the server's IP address, ARG1 is the server's TCP port. ARG3 is our IP address and ARG4 is our socket port. Look at us, being all networked and iconic ✨

πŸ¦‹ testc_disconnected

Generated whenever we disconnect from the server. Sad girl hours, but make it graceful πŸ’…

πŸ’– testc_input

Generated whenever the server sends us some traffic. ARG0 is the data that came in β€” tokenised by whatever POE::Filter you specified. no cap, that filter is doing the heavy lifting here 🧚

πŸ”₯ testc_flushed

Generated whenever anything we send to the server is actually flushed down the 'line'. Like, for real for real sent. The moment of truth ⭐


πŸ‘‘ KUDOS πŸ‘‘

Contains code borrowed from POE::Component::Server::TCP by Rocco Caputo, Ann Barcomb and Jos Boumans. Shoutout to the elders, fr fr 🫢


🌟 SEE ALSO 🌟

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

πŸ’œ AUTHOR πŸ’œ

Chris Williams <chris@bingosnet.co.uk>


This software is copyright (c) 2018 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.


and that's the whole page bestie, we made it to the end πŸŽ‰ this was Test::POE::Client::TCP(3pm), living in the User Contributed Perl Documentation section, generated with perl v5.36.0 and dated 2022-12-01. go forth and test your TCP things, you absolute main character πŸ’…βœ¨

πŸ“¦ where this page comes from