pest icon indicating copy to clipboard operation
pest copied to clipboard

[4.x] Github Workflow crashes: Could not read XML from file "--cache-directory"

Open Mareddie opened this issue 1 year ago • 4 comments

What Happened

I have a CI pipeline set up in GitHub Actions to run my Pest tests. While everything works as expected on my local machine, the pipeline fails with the following error:

INFO Could not read XML from file "--cache-directory".

The pipeline exits immediately after this error. I have attempted to change the cache directory and disable the cache altogether, but neither approach resolved the issue.

name: Test backend

on:
  pull_request:
    types: [opened, synchronize, reopened]
    branches:
      - pre-main
  workflow_dispatch:

concurrency:
  group: ${{ github.event_name == 'pull_request' && 'pr-test-' || 'dispatch-test-' }}${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.workflow_run.id }}
  cancel-in-progress: true

jobs:
  run-backend-tests:
    name: Run backend tests
    runs-on: ubuntu-latest

    services:
      mysql:
        image: mysql:8.4
        env:
          MYSQL_ALLOW_EMPTY_PASSWORD: false
          MYSQL_ROOT_PASSWORD: root
          MYSQL_DATABASE: ci_test
        ports:
          - 3306/tcp
        options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.3'
          coverage: pcov
          ini-values: memory_limit=512M, upload_max_filesize=64M, post_max_size=80M, max_execution_time=90
          tools: composer, phpstan
        env:
          fail-fast: true

      - name: Get composer cache directory
        id: composer-cache
        run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT

      - name: Cache dependencies
        uses: actions/cache@v4
        with:
          path: ${{ steps.composer-cache.outputs.dir }}
          key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
          restore-keys: ${{ runner.os }}-composer-

      - name: Install dependencies
        run: composer install --prefer-dist --optimize-autoloader --classmap-authoritative

      - name: Run migrations
        run: |
          php bin/console doctrine:migrations:migrate --no-interaction --env test
        env:
          # Suffix _test is automatically appended for test environment. See config/doctrine.yaml
          DATABASE_URL: mysql://root:[email protected]:${{ job.services.mysql.ports['3306'] }}/ci

      - name: Run tests
        run: |
          ./vendor/bin/pest --ci
        env:
          # Suffix _test is automatically appended for test environment. See config/doctrine.yaml
          DATABASE_URL: mysql://root:[email protected]:${{ job.services.mysql.ports['3306'] }}/ci

How to Reproduce

Run pest in Github Action

Sample Repository

No response

Pest Version

3.6.0

PHP Version

8.3.14

Operation System

Linux

Notes

From my observations, when Pest is executed, it generates a configuration file .pest.xml in the current directory, containing the PHPUnit configuration in use. After the tests are completed, Pest deletes this file.

In the GitHub Action environment, it seems that Pest cannot generate or access this file, leading to the error mentioned above.

Is there a known workaround to ensure Pest can generate and use the .pest.xml file in the pipeline environment? If this behavior is intentional (i.e., not a bug but a feature), a more descriptive error message would be very helpful to guide users toward a resolution.

For further reference, here's my Pest configuration:

<?php

declare(strict_types=1);

use App\Tests\Api\BaseApiCase;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Dotenv\Dotenv;

if (method_exists(Dotenv::class, 'bootEnv')) {
    if (is_array($_ENV) && array_key_exists('APP_ENV', $_ENV) === false) {
        $_ENV['APP_ENV'] = 'test';
    }

    if (is_array($_SERVER) && array_key_exists('APP_ENV', $_SERVER) === false) {
        $_SERVER['APP_ENV'] = 'test';
    }

    (new Dotenv())->bootEnv(dirname(__DIR__).'/.env');
}

/*
|--------------------------------------------------------------------------
| Test Case
|--------------------------------------------------------------------------
|
| The closure you provide to your test functions is always bound to a specific PHPUnit test
| case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may
| need to change it using the "uses()" function to bind a different classes or traits.
|
*/
pest()
    ->extends(KernelTestCase::class)
    ->in('Unit');

pest()
    ->extends(KernelTestCase::class)
    ->in('Integration');

pest()
    ->extends(BaseApiCase::class)
    ->in('Api');

/*
|--------------------------------------------------------------------------
| Functions
|--------------------------------------------------------------------------
|
| While Pest is very powerful out-of-the-box, you may have some testing code specific to your
| project that you don't want to repeat in every file. Here you can also expose helpers as
| global functions to help you to reduce the number of lines of code in your test files.
|
*/

Mareddie avatar Dec 09 '24 11:12 Mareddie

Hi @Mareddie , I am experiencing the same issue on a project using Pest with GitHub Actions. Interestingly, I have other projects with a similar structure where the GitHub Actions workflow works fine.

To troubleshoot the problem, I am currently analyzing the PHP configuration of the runner and the PHP extensions being used. My initial thought was that the runner's PHP environment might be missing the XML extension, which could explain the issue.

I will also explore other configurations to better understand the root cause. My current approach is to align the configuration as closely as possible with my other projects where the GitHub Actions workflows are working as expected.

I will update here in case I will be able to find a proper configuration.

roberto-butti avatar Jan 19 '25 09:01 roberto-butti

Hi @Mareddie ,

I am sharing some feedback here since I experienced the same issue. Maybe my solution can help you solve it or at least better understand the problem.

I was a bit hesitant to share my solution at first because it turned out to be my own mistake 🤣 due to a configuration oversight in phpunit.xml and .gitignore. However, if it helps someone, I’m happy to share.

In my case, I had a phpunit.xml file locally that was ignored by Git due to .gitignore. Locally, the tests ran fine because they were automatically reading the local phpunit.xml. However, in the workflow that checked out the repository, the phpunit.xml file was missing, resulting in that "cryptic" error.

What I did to fix it was:

  • Create a phpunit.xml.dist file (with public configuration details suitable for the repository).
  • Commit this file to the repository.
  • Update the action to explicitly specify the configuration file using the --configuration option:
            - name: running tests
              run: vendor/bin/pest --configuration=phpunit.xml.dist

I hope this helps! Feel free to let me know if you have any questions.

roberto-butti avatar Jan 22 '25 09:01 roberto-butti

Thanks for your suggestions, and I apologize for my late response. We've temporarily resolved this issue by dumping Pest's underlying PHPUnit config and committing it. While this helped, it doesn't fully solve the problem since we still depend on both PHPUnit and Pest configurations. It would be ideal if Pest could function without requiring a PHPUnit config file—or if that's not possible, the documentation should clearly explain why it's necessary.

Though Pest is excellent, it's not as stable as PHPUnit. Due to these inconsistencies and limited documentation, we're seriously considering switching back to PHPUnit.

Mareddie avatar Mar 11 '25 10:03 Mareddie

Details from Claude figuring this issue out on my package.... a bit over my head on the true mechanics other than it is not being called due to a config issue. Sorry it seems a bit rude in its explanation lol. Hope it helps:

------ From Claude -----

Found the actual root cause of this — it's not related to XML/config content, cache directories, or .gitignore; it's a zend.assertions ini setting.

Root cause: src/Plugins/Configuration.php's fromGeneratedConfigurationFile() writes the generated PHPUnit config via:

assert(is_int(file_put_contents($path, $contents)));

When zend.assertions=-1 (PHP's official php.ini-production default, and also shivammathur/setup-php's own ini-file: production default on GitHub Actions), PHP compiles assert() calls — including their argument expressions — out entirely. file_put_contents() never executes, so .pest.xml is never written. handleArguments() then does:

return $this->pushArgument((string) realpath($this->fromGeneratedConfigurationFile()), $arguments);

realpath() on the now-nonexistent path returns false, which casts to '', so Pest hands PHPUnit an empty --configuration value. Combined with src/Plugins/Cache.php's own argument-pushing (same unguarded (string) realpath(...) pattern), this surfaces as the confusingly-unrelated --cache-directory in the final error text rather than the actual empty --configuration.

Reproduce directly, no CI needed:

php -d zend.assertions=-1 vendor/bin/pest

reproduces this instantly on any machine, and confirms .pest.xml is never created.

Immediate workaround (no repo changes needed, unlike the phpunit.xml.dist workarounds above): pin the ini value back to development mode for the test job. With shivammathur/setup-php:

- uses: shivammathur/setup-php@v2
  with:
    ini-values: zend.assertions=1

Real fix: don't rely on assert() to perform a required side effect — check file_put_contents()'s return value directly and throw if it fails, independent of the zend.assertions ini setting. The same unguarded (string) realpath(...) pattern also exists in src/Plugins/Cache.php and is worth hardening the same way.

Confirmed on Pest 4.7.0/4.7.8, PHP 8.3/8.4, both Linux (GitHub Actions ubuntu-24.04) and macOS (via -d zend.assertions=-1) — so this is purely ini-triggered, not OS- or version-specific to what's reported above (originally filed against 3.6.0).

Coyote6 avatar Aug 17 '26 22:08 Coyote6