PHPUnit CAPTCHA Tests: Fresh Tokens and Windows Time Limits

phpunit captcha - PHPUnit CAPTCHA Tests: Fresh Tokens and Windows Time Limits

A PHPUnit CAPTCHA test needs one CapSkip client for the whole test class and a fresh solve inside every test, because a token works once. What PHPUnit changes is time. Its own time limit relies on the pcntl extension, and PHP for Windows has none, so no PHPUnit setting stops a test that waits on a slow solve. This guide builds a test class for PHP CAPTCHA solving with CapSkip, shows what PHPUnit 9.6 to 13.4 did on Windows, and sets the limits that do work.

What you need

  • Windows with CapSkip installed and its reCAPTCHA solver turned on. Install steps are in the setup guide.
  • PHP 8.0 or newer with curl and mbstring switched on in a php.ini of your own. The package capskip/capskip 1.8.0 declares PHP 8.0, curl and json, and PHPUnit needs mbstring. For an https login page, curl.cainfo must also point at a CA bundle file such as cacert.pem from curl.se, or the request fails in setUp with a certificate error (confirmed on 8.0.30 with a plain curl call). My runs used http, so the https path itself was not run.
  • PHPUnit, in the major Composer picks for your PHP (table below).
  • A staging login page with a reCAPTCHA v2 checkbox. My runs used a mock page.
  • An address for CapSkip: 127.0.0.1 in Local mode, or the network address of its PC once Server mode is on. Pick Local or Server under the connection settings of the setup guide.
PHPPHPUnit installedLowest PHP it accepts
8.0.309.6.397.3
8.1.3310.5.678.1
8.2.2911.5.588.2
8.3.2812.5.458.3
8.4.1513.4.88.4.1
8.5.013.4.88.4.1

So PHP 8.0 meets only PHPUnit 9.6, and PHPUnit 12 and 13 need a newer PHP than the SDK does (floors from each composer.json).

Every number below is a mock number on Windows 11, from two small servers I wrote: a stand-in for CapSkip and a login page. Every rule of the page is mine. The real app got three invalid requests that create no task: ERROR_BAD_PARAMETERS for a missing googlekey, ERROR_PAGEURL for a bad address and ERROR_UPLOAD for an unknown method (real app, version unconfirmed). No real solve ran.

Build the test class

Step 1: install the packages and the config

Run these in an empty folder.

# In PowerShell, in a new folder. Composer picks the PHPUnit that fits your PHP.
composer require capskip/capskip
composer require --dev phpunit/phpunit

Save the next block as phpunit.xml and create a folder named tests beside it.

<?xml version="1.0" encoding="UTF-8"?>
<!-- phpunit.xml, next to composer.json -->
<phpunit bootstrap="vendor/autoload.php" colors="true">
    <testsuites>
        <testsuite name="captcha">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
</phpunit>

Step 2: write the test class

Save the next two blocks, one after the other, as one file named tests\LoginCaptchaTest.php. The first holds the client and the helpers.

<?php
// tests/LoginCaptchaTest.php
declare(strict_types=1);

use CapSkip\CapSkip;
use CapSkip\Exceptions\ApiException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

final class LoginCaptchaTest extends TestCase
{
    private static CapSkip $solver;
    private string $sitekey;

    // Runs once for the whole class, so the one CapSkip client lives here.
    public static function setUpBeforeClass(): void
    {
        $host = getenv('CAPSKIP_HOST') ?: '127.0.0.1';
        $port = (int) (getenv('CAPSKIP_PORT') ?: 8080);
        // CapSkip has no ping endpoint, so try a plain connection first.
        $probe = @fsockopen($host, $port, $errno, $error, 3);
        if ($probe === false) {
            self::markTestSkipped("CapSkip is not running on $host:$port ($error)");
        }
        fclose($probe);
        // The SDK stops polling after 60 s here. Its default for reCAPTCHA is 300 s.
        self::$solver = new CapSkip([
            'host' => $host,
            'port' => $port,
            'apiKey' => getenv('CAPSKIP_API_KEY') ?: 'capskip',
            'recaptchaTimeout' => 60,
        ]);
    }

    // Runs before every test: a fresh page and sitekey. It does not solve.
    protected function setUp(): void
    {
        [, $html] = $this->send(null);
        self::assertSame(1, preg_match('/data-sitekey="([^"]+)"/', $html, $found), 'no sitekey on the page');
        $this->sitekey = $found[1];
    }

    private function loginUrl(): string
    {
        return getenv('LOGIN_URL') ?: 'https://example.com/login';
    }

    /** @return array{0: int, 1: string} the status and the body, a 403 included */
    private function send(?array $form): array
    {
        $ch = curl_init($this->loginUrl());
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_REFERER => $this->loginUrl(),  // curl sends no Referer by itself
        ]);
        if ($form !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($form));
        }
        $body = curl_exec($ch);
        self::assertIsString($body, curl_error($ch));

        return [curl_getinfo($ch, CURLINFO_RESPONSE_CODE), $body];
    }

setUpBeforeClass is static and runs once per class, so it holds the client and the check that CapSkip is listening. The class reads CAPSKIP_HOST, CAPSKIP_PORT and CAPSKIP_API_KEY from the environment, and falls back to 127.0.0.1, 8080 and the SDK default key, so set the key only if API Key Validation is on. CapSkip has no ping endpoint, so a plain connection stands in. With nothing listening, the check took 2.0 seconds and skipped the whole class with exit code 0 on all six setups. Use 127.0.0.1, because localhost added 2 seconds to the check against my IPv4-only mock. setUp runs before each test and only reads the sitekey from a fresh page, since a solve there would charge every test for a token.

    // One solve per call, because a token works once. An unsolvable answer
    // is the one failure worth a second solve.
    private function freshToken(): string
    {
        for ($attempt = 1; ; $attempt++) {
            try {
                return self::$solver->recaptcha($this->sitekey, $this->loginUrl())['code'];
            } catch (ApiException $e) {
                if ($attempt === 2 || !str_contains($e->getMessage(), 'ERROR_CAPTCHA_UNSOLVABLE')) {
                    throw $e;
                }
            }
        }
    }

    public static function logins(): array
    {
        // Plain data only. PHPUnit calls this while it builds the list of
        // tests, before any test body runs.
        return [
            'right password' => ['secret', 200, 'Welcome'],
            'wrong password' => ['wrong', 403, 'Invalid email or password'],
        ];
    }

    /** @dataProvider logins */
    #[DataProvider('logins')]
    public function testLogin(string $password, int $status, string $text): void
    {
        $token = $this->freshToken();  // solve last, then post at once
        [$gotStatus, $body] = $this->send([
            'email' => '[email protected]',
            'password' => $password,
            'g-recaptcha-response' => $token,
        ]);
        self::assertSame($status, $gotStatus);
        self::assertStringContainsString($text, $body);
    }
}

freshToken asks for a new solve on every call, and asks once more only for ERROR_CAPTCHA_UNSOLVABLE, which means a solve failed this time. Any other error, such as ERROR_PAGEURL, would fail again, so it is thrown. With the first task unsolvable, the two tests used three tasks and passed on all six setups. The test solves last and posts at once, because a token does not keep (see reCAPTCHA token expiration). Adapt the pattern, field names and texts to your page.

Step 3: run it

# Point the test at your own login page, then run it
$env:LOGIN_URL = "https://staging.example.com/login"
.\vendor\bin\phpunit

Against the mock with a 1 second solve, the two tests took 3.6 to 3.9 seconds on PHP 8.0.30 to 8.5.0, because the SDK reads the result at 0, 0.25, 0.75 and 1.75 seconds.

Solve inside each test, not in setUpBeforeClass

Solving once in setUpBeforeClass and sharing the token fails. Two tests posted one token: the first signed in and the second got the mock’s token already used refusal, with one task for two tests (9.6.39 on 8.0.30 and 13.4.8 on 8.5.0). A retry cannot repair it, because it never runs setUpBeforeClass again: with the retry option of PHPUnit 13.4.8 the second test ran three times, with no new task and the same refusal.

Data providers run before any test

PHPUnit calls a provider while it builds the test list, so a provider that solves mints every token before the first test body runs. With three data sets and a 1 second mock solve, the first test body began about 5.6 seconds after the provider started, and its token was about 3.7 seconds old. A run filtered to another class still ran the provider, giving four tasks for one test, and the list-tests option ran it too, with three tasks. When CapSkip dropped the connection inside the provider, PHPUnit 13.4.8 reported an invalid data provider and ran none of that class, exit code 2, and 9.6.39 reported one error, exit code 2. So the provider returns plain data and each data set solves for itself.

PHPUnit 9.6 reads a provider only from the docblock, 12.5 and 13.4 only from the attribute, and 10.5 and 11.5 from both. The block carries both, and gave three tests and three tasks on all six setups.

PHPUnit cannot stop a solve on Windows

The PHPUnit time limit

PHPUnit has an enforce time limit setting, a default limit and the Small, Medium and Large size attributes. All of them use pcntl, which the PHP manual lists as unavailable on Windows, and my six builds had no pcntl library. In the source, PHPUnit warns when the extension is missing and runs the test unbounded. With a 2 second limit and a 6 second mock solve, which the SDK noticed at 7.75 seconds, every version let it finish.

PHPUnit on PHPWhat it printedSolve returned afterExit code
9.6.39 on 8.0.30An error line before the run7.8 s0
10.5.67 on 8.1.33A runner warning7.9 s1
11.5.58 on 8.2.29A runner warning7.8 s1
12.5.45 on 8.3.28A runner warning7.8 s1
13.4.8 on 8.4.15A runner warning7.8 s1
13.4.8 on 8.5.0A runner warning7.8 s1

Every test passed, so on 10.5 and later the setting only turned the exit code to 1. A Small attribute does nothing until the enforce option is on (13.4.8 on 8.5.0: no warning, a 7.9 second solve, exit code 0), and then it gives the same warning and exit code 1. PHPUnit 13.4 adds a timeout option for the whole run, checked after each test: with three tests of 3.8 seconds and a limit of 5, two ran for 7.6 seconds, the third did not run and the exit code was 124. The commands, all run for this guide:

# Windows PowerShell. Each line was run for this guide.
# The PHPUnit time limit: it warns and never stops a solve
.\vendor\bin\phpunit --enforce-time-limit --default-time-limit 2
# PHPUnit 13.4 only: a wall-clock limit for the whole run, checked after each test
.\vendor\bin\phpunit --timeout 60
# PHPUnit 13.4 only: run a failed test again, up to 3 attempts
.\vendor\bin\phpunit --retry 3
# A PHP time limit is a hard stop, and it prints no summary
php -d max_execution_time=6 vendor\bin\phpunit

What does stop a solve

The SDK timeout fails the test with an exception, and the next test runs. Step 2 sets recaptchaTimeout to 60. The SDK checks its deadline only when it wakes between polls (sleeps of 0.25 up to 5 seconds, per the source), so it is late by up to 5 seconds. Against a mock that never answered, a timeout of 5 ended after 7.9 seconds on 9.6.39 and 7.8 on 13.4.8, and a timeout of 10 after 12.9 and 12.8.

The PHP limit is harsher. In the command line max_execution_time reads 0 even when php.ini says 30. With the last command of the block, a limit of 6 and an SDK timeout of 30, PHP died with a fatal error after about 8 seconds: exit code 255 and no summary on 9.6.39. PHPUnit 12.5.45 added one line naming the test, exit code 2 and no summary. On 13.4.8 with PHP 8.5.0 the fatal error also printed about 20 lines of stack trace before that line. Keep the SDK timeout plus 5 seconds below any PHP limit.

A stopped run leaves its solve behind

A failing assertion comes after the solve returned, so nothing is in flight. A run that dies is different. The SDK source has no call that cancels a task, so CapSkip is not told. Against a one-slot mock, a 20 second task whose PHP process was stopped at 8 seconds kept the slot, and the next run’s 3 second solve returned after about 18 seconds on 9.6.39 and on 13.4.8. The slot rule is the mock’s; whether the real app frees a thread is untested.

Retries and parallel runs

What a retry costs

Of my six setups, only PHPUnit 13.4.8 has a retry, as an option and, per its source, an attribute. Its help text says to attempt each test up to N times, stopping at the first success. With the first task unsolvable and no helper retry, a limit of 3 gave one retried test, two tasks and exit code 0, and a test that always fails used three tasks, one per attempt. The other majors answered Unknown option, so there the retry lives in freshToken.

ParaTest and the CapSkip thread limit

PHPUnit 13.4.8 has no parallel option. ParaTest adds one and ran on Windows: 7.29.0 on PHP 8.5.0, which it needs at 8.4 or newer, and 6.11.1 on PHP 8.0.30. The test was eight classes of two tests, 16 solves of 3 seconds, against a mock whose Max. Threads I set to 4.

# ParaTest hands whole test classes to worker processes, at most -p at a time
composer require --dev brianium/paratest
.\vendor\bin\paratest -p 4
ProcessesRun time, PHP 8.5.0Run time, PHP 8.0.30Most tasks at CapSkip at once
161.8 s64.2 s1
231.4 s31.5 s2
415.9 s15.8 s4
816.2 s16.1 s8 sent, 4 running

The gain stops at the limit: with 8 processes four tasks waited for a thread. Per the setup guide, Max. Threads is how many tasks of a type CapSkip solves at once and the Wait Timeout is how long a task may wait for a thread. It states no default, so read yours in CapSkip and keep the process count at or below it. I did not model a task giving up. ParaTest hands whole classes to workers, so four classes on 8 processes took 8.2 seconds, and setUpBeforeClass ran once per class. With its functional option it ran 16 times for 16 tests.

Deprecations and stubs

PHP 8.5 and the curl_close deprecation

PHP 8.5 deprecates curl_close, and SDK 1.8.0 still calls it at Http.php line 105 after every request to CapSkip. PHPUnit 13.4.8 on 8.5.0 ended with OK, but there were issues, one deprecation and exit code 0. The display option shows it 5 times per test, one submit and four reads. The fail on deprecation switch gave exit code 1. Naming your own code in a source element and ignoring indirect deprecations silenced it (13.4.8 only). A solve inside setUpBeforeClass printed the raw Deprecated line outside the report.

<?xml version="1.0" encoding="UTF-8"?>
<!-- phpunit.xml: name your own code, so that code in vendor counts as indirect -->
<phpunit bootstrap="vendor/autoload.php" colors="true">
    <testsuites>
        <testsuite name="captcha">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
    <source ignoreIndirectDeprecations="true">
        <include>
            <directory>src</directory>
        </include>
    </source>
</phpunit>

A stub for the tests around the solve

A PHPUnit stub of the SDK class returns the same array shape, and it ran with nothing listening on all six setups, sending no task.

<?php
// tests/StubbedSolverTest.php: runs with CapSkip closed
declare(strict_types=1);

use CapSkip\CapSkip;
use PHPUnit\Framework\TestCase;

final class StubbedSolverTest extends TestCase
{
    // Stands in for your own code, which takes a solver and returns a token.
    private function tokenFrom(CapSkip $solver): string
    {
        return $solver->recaptcha('KEY', 'https://example.com/login')['code'];
    }

    public function testTokenComesFromTheSolver(): void
    {
        // A stub skips the constructor, so no connection is ever made.
        $solver = $this->createStub(CapSkip::class);
        $solver->method('recaptcha')->willReturn(['captchaId' => '1', 'code' => 'tok-1']);

        self::assertSame('tok-1', $this->tokenFrom($solver));
    }
}

Common errors

Every row was triggered in this harness against the mock, except the two marked real app.

What you seeCauseFix
The pcntl extension is required for enforcing time limitsWindows has no pcntl, so the PHPUnit time limit cannot runRemove the setting and rely on the SDK timeout
Fatal error: Maximum execution timeA PHP limit set with a -d option ended the runRemove the limit, or keep the SDK timeout well below it
Premature end of PHP process when runningThe fatal error from the row above, with the test named by PHPUnit 12.5 and 13.4Apply the fix of that row
Unknown optionThe retry or timeout option on a PHPUnit older than 13.4Retry inside freshToken
token already usedOne token was posted twice (the mock’s wording, a real site words it its own way)Solve inside each test
An invalid data providerThe provider threw, for example because CapSkip was downReturn plain data from providers
TimeoutExceptionNo answer within recaptchaTimeout, or CapSkip stopped during a poll (seen with limits of 5 and 10)Check the task in CapSkip, then raise the value
no sitekey on the pageLOGIN_URL still holds the example address, or your pattern missed the sitekeySet LOGIN_URL to your own login page
ERROR_BAD_PARAMETERS (real app, version unconfirmed)CapSkip got a request without a googlekeyPrint the sitekey read in setUp and check it is not empty
ERROR_PAGEURL (real app, version unconfirmed)A page address that is not a URLPass the full address of the login page
Deprecated: Function curl_close() is deprecatedSDK 1.8.0 on PHP 8.5Use the source setting above

FAQ

Can a hosted CI runner run these tests?

Only if it can reach CapSkip, which means Server mode. That mode needs CapSkip to run as administrator and starts with its port open to every address, so a narrower allow rule from you changes nothing. To keep the port to the machines that run your tests, add a Windows Firewall block rule for all the others, and switch on API Key Validation. On the test machine set CAPSKIP_HOST to the address of the CapSkip PC and CAPSKIP_API_KEY to your key. I did not run a remote setup.

A PHPUnit CAPTCHA suite is one client per class, one solve per test, an SDK timeout that fails fast and a process count at or below the thread limit. CapSkip runs on your own PC as a local captcha solver, so a suite that solves on every test has no per-solve fee.