realflash has asked for the wisdom of the Perl Monks concerning the following question:

I'm a writing a module to interact with a REST API. It is OAuth2 authenticated, of which one of the steps is to print a callback URL and wait for it to be called by the REST API when the user has authenticated. My problem is in my test scripts. Tests need to start some kind of mock HTTP server to serve the callback URL, then wait for it to be called once, then continue.

The mock HTTP modules I have found (quite logically) have you write an anonymous subroutine to be called when the request comes in, then start the server, at which point the tests continue regardless. I would like the whole thing to be self-contained - a tester shouldn't have to manually start a server before running the tests.

I have tried Test::Fake::HTTPD and then sleep till it fills out a global-ish variable with the contents of the incoming request, but the act of sleeping seems to terminate the child HTTPD process, resulting in:

[Test::TCP] Child process does not block(PID: 156297, PPID: 156296) at /usr/local/share/perl/5.30.0/Test/TCP.pm line 103.

What is the right way to go about this?

Replies are listed 'Best First'.
Re: Waiting on an asynchronous call during a test
by pryrt (Abbot) on Dec 13, 2021 at 21:48 UTC

    Instead of starting a real or fake server, you might consider just intercepting the HTTP request in your test and passing mocked data without it having to connect to a server.

    For WWW::KeePassHttp, the module needs an HTTP server at the other end, and is using HTTP::Tiny to access that; for the test suite, I just mock the HTTP::Tiny::get() subroutine, and tell the fake-get what data to return to my module, so I can continue testing the module. (Basically, I just grabbed the HTTP responses from a live server, and saved those in my test script to be used for the mocked version.)

    See, for example, https://github.com/pryrt/WWW-KeePassHttp/blob/main/t/workflow.t

Re: Waiting on an asynchronous call during a test
by zentara (Cardinal) on Dec 14, 2021 at 16:54 UTC
    Timely node, synchronous :-) . I was just trying to figure out websockets and RESTful servers myself. Good leads.

    I'm not really a human, but I play one on earth. ..... an animated JAPH