Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laminas Cache Storage Adapter Test Laravel Package

laminas/laminas-cache-storage-adapter-test

Test adapter for Laminas Cache storage. Provides a lightweight in-memory storage implementation useful for unit tests and CI, enabling predictable cache behavior without external services or persistent backends.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require --dev laminas/laminas-cache-storage-adapter-test
    

    Add to your composer.json under require-dev to ensure it’s only installed in testing environments.

  2. First Use Case: Extend the provided abstract test classes to test your custom cache adapters. For example, for a PSR-16 (SimpleCache) adapter:

    use Laminas\Cache\Storage\Adapter\Test\AbstractSimpleCacheIntegrationTest;
    
    class MyRedisCacheTest extends AbstractSimpleCacheIntegrationTest
    {
        protected function createCachePool(): \Psr\SimpleCache\CacheInterface
        {
            return new MyRedisCacheAdapter();
        }
    }
    
  3. Where to Look First:

    • Review the documentation for abstract test classes like:
      • AbstractCacheItemPoolIntegrationTest (for PSR-6 adapters)
      • AbstractSimpleCacheIntegrationTest (for PSR-16 adapters)
    • Check the releases for compatibility notes (e.g., PHP 8.3 support, PSR-16/PSR-6 v3).

Implementation Patterns

Usage Patterns

  1. Extending Abstract Test Classes: Override createCachePool() to return an instance of your custom cache adapter. This is the core pattern for leveraging the package.

    class MyFileCacheTest extends AbstractCacheItemPoolIntegrationTest
    {
        protected function createCachePool(): \Psr\Cache\CacheItemPoolInterface
        {
            return new \Laminas\Cache\Storage\Adapter\Filesystem();
        }
    }
    
  2. Testing Edge Cases: Use built-in test methods to verify:

    • Key length limits (testMaximumKeyLength).
    • Expiry behavior (testHasItemReturnsFalseWhenDeferredItemIsExpired).
    • Serialization/deserialization of PHP data types (e.g., DateTime, arrays).
    public function testCustomEdgeCase()
    {
        $this->assertTrue($this->cachePool->hasItem('key'));
        $this->assertEquals('value', $this->cachePool->getItem('key')->get());
    }
    
  3. Integration with Laravel:

    • Use the package to test Laravel’s cache drivers (e.g., FileCache, RedisCache).
    • Example for Laravel’s Cache facade:
      use Illuminate\Support\Facades\Cache;
      use Laminas\Cache\Storage\Adapter\Test\AbstractSimpleCacheIntegrationTest;
      
      class LaravelRedisCacheTest extends AbstractSimpleCacheIntegrationTest
      {
          protected function createCachePool(): \Psr\SimpleCache\CacheInterface
          {
              return Cache::store('redis');
          }
      }
      
  4. Data Providers: Leverage static data providers (e.g., dataProviderForGetItem) for parameterized tests:

    /**
     * @dataProvider dataProviderForGetItem
     */
    public function testGetItem($key, $expectedValue, $expectedMetadata = null)
    {
        $this->cachePool->set($key, $expectedValue, $expectedMetadata);
        $this->assertEquals($expectedValue, $this->cachePool->get($key));
    }
    
  5. PSR Compliance: Test both PSR-6 (CacheItemPoolInterface) and PSR-16 (CacheInterface) adapters by extending the appropriate abstract class. The package ensures compatibility with PSR versions 2 and 3.


Workflows

  1. Test-Driven Development (TDD):

    • Write tests for a new cache adapter using the abstract classes before implementing the adapter.
    • Example workflow:
      # 1. Add the package to dev dependencies.
      composer require --dev laminas/laminas-cache-storage-adapter-test
      
      # 2. Create a test class extending the abstract test.
      php artisan make:test MyCacheAdapterTest
      
      # 3. Implement the adapter to pass tests.
      
  2. Regression Testing:

    • Use the package to maintain a suite of tests for existing adapters (e.g., after upgrading Laravel or PHP versions).
    • Example:
      // Test suite for all cache adapters in a Laravel app.
      class AllCacheAdaptersTest extends \Tests\TestCase
      {
          public function testFileCache()
          {
              (new MyFileCacheTest())->testHasItemReturnsFalseWhenItemIsMissing();
          }
      
          public function testRedisCache()
          {
              (new MyRedisCacheTest())->testGetItem();
          }
      }
      
  3. CI/CD Integration:

    • Run the test suite in CI to catch adapter-specific issues early.
    • Example .github/workflows/ci.yml:
      jobs:
        test:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - run: composer install
            - run: composer test  # Runs PHPUnit with the test suite.
      

Integration Tips

  1. Laravel-Specific:

    • Mock Laravel’s Cache facade or use the real store in tests:
      use Illuminate\Foundation\Testing\RefreshDatabase;
      
      class LaravelCacheTest extends AbstractSimpleCacheIntegrationTest
      {
          use RefreshDatabase;
      
          protected function createCachePool(): \Psr\SimpleCache\CacheInterface
          {
              return Cache::store('database'); // Uses Laravel's database driver.
          }
      }
      
  2. Custom Adapters:

    • For adapters with unique behavior (e.g., custom tags or namespaces), extend the abstract test and add custom assertions:
      class MyTaggedCacheTest extends AbstractCacheItemPoolIntegrationTest
      {
          public function testTagOperations()
          {
              $this->cachePool->set('key', 'value', ['tag1', 'tag2']);
              $this->assertEquals(['value'], $this->cachePool->getItemsByTag('tag1'));
          }
      }
      
  3. Performance Testing:

    • Use the sleepTimer feature (introduced in v4.1.0) to speed up tests with long expiry times:
      protected function setUp(): void
      {
          parent::setUp();
          $this->sleepTimer = 0.1; // Reduce sleep time for expiry tests.
      }
      
  4. Type Safety:

    • Ensure your adapter handles type-safe keys (e.g., rejects invalid UTF-8 or excessively long keys). The package includes tests for this (testInvalidKeys).

Gotchas and Tips

Pitfalls

  1. PHPUnit Version Compatibility:

    • The package requires PHPUnit 10+ (since v3.0.0). Ensure your phpunit.xml config matches:
      <phpunit bootstrap="vendor/autoload.php">
          <extensions>
              <extension class="Laminas\Cache\Storage\Adapter\Test\PHPUnit\Extensions\SleepTimerExtension"/>
          </extensions>
      </phpunit>
      
    • Gotcha: Older PHPUnit versions may fail with DataProvider errors (e.g., non-static methods).
  2. Cache Pool Isolation:

    • Each test method runs in isolation, but shared state between tests can cause flakiness. Use flush() or clear() in tearDown() if needed:
      protected function tearDown(): void
      {
          $this->cachePool->clear();
          parent::tearDown();
      }
      
  3. Expiry Timing:

    • Tests with expiry times (e.g., set($key, $value, 1)) may fail if the test runner is slow. Use the sleepTimer to adjust:
      // In your test class:
      protected $sleepTimer = 0.01; // 10ms sleep per second of expiry time.
      
  4. Key Validation:

    • The package tests for maximum key length (e.g., 255 bytes). Ensure your adapter enforces this:
      // Example of a failing test:
      $this->expectException(\Psr\Cache\InvalidArgumentException::class);
      $this->cachePool->set(str_repeat('a', 300), 'value');
      
  5. PSR Version Mismatches:

    • PSR-6 (CacheItemPoolInterface) and PSR-16 (CacheInterface) have different methods. Ensure you extend the correct abstract class:
      • Wrong: Extending AbstractSimpleCacheIntegrationTest for a PSR-6 adapter.
      • Right: Extend AbstractCacheItemPoolIntegrationTest for PSR-6.
  6. Serialization Issues:

    • Some PHP data types (e.g., DateTime, Resource) may not serialize/deserialize correctly. Test with:
      $date = new \DateTime();
      $this->cachePool->set('date', $date);
      $this->assertInstanceOf(\DateTime::class, $this->cachePool->get('
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport