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
    

    Ensure this is added to your dev dependencies only.

  2. First Use Case: Extend the provided abstract test classes in your custom cache adapter tests. For example:

    use Laminas\Cache\Storage\Adapter\Test\AbstractCacheItemPoolIntegrationTest;
    
    class MyRedisAdapterTest extends AbstractCacheItemPoolIntegrationTest
    {
        protected function createCacheItemPool(): CacheItemPoolInterface
        {
            return new MyRedisAdapter(); // Your custom adapter
        }
    }
    
  3. Where to Look First:

    • Browse the documentation for abstract test class details.
    • Check the source code for available test classes like:
      • AbstractCacheItemPoolIntegrationTest
      • AbstractSimpleCacheIntegrationTest
      • AbstractCacheItemIntegrationTest

Implementation Patterns

Usage Patterns

  1. Extending Abstract Test Classes:

    • Use AbstractCacheItemPoolIntegrationTest for testing CacheItemPoolInterface implementations (e.g., Redis, Memcached).
    • Use AbstractSimpleCacheIntegrationTest for testing Psr\SimpleCache\CacheInterface implementations.
    • Use AbstractCacheItemIntegrationTest for testing individual CacheItemInterface behavior.

    Example:

    class MyMemcachedAdapterTest extends AbstractCacheItemPoolIntegrationTest
    {
        protected function createCacheItemPool(): CacheItemPoolInterface
        {
            return new MemcachedAdapter(); // Your custom adapter
        }
    }
    
  2. Integration Testing:

    • The package provides pre-built test cases for common cache operations like:
      • Item storage/retrieval.
      • Expiration handling.
      • Flushing/clearing.
      • Key validation (e.g., maximum key length).
    • Override methods like testHasItemReturnsFalseWhenDeferredItemIsExpired to customize behavior.
  3. PSR Compliance:

    • Tests for both PSR-6 (CacheItemPoolInterface) and PSR-16 (SimpleCacheInterface) are included.
    • Use AbstractSimpleCacheIntegrationTest for PSR-16 compliance:
      class MySimpleCacheTest extends AbstractSimpleCacheIntegrationTest
      {
          protected function createCache(): CacheInterface
          {
              return new MySimpleCacheAdapter(); // Your PSR-16 adapter
          }
      }
      
  4. Type Safety:

    • The package enforces type safety for cache keys and values. Ensure your adapter adheres to these constraints.

Workflows

  1. Test-Driven Development (TDD):

    • Write tests for your custom cache adapter using the provided abstract classes before implementing the adapter.
    • Example workflow:
      • Extend AbstractCacheItemPoolIntegrationTest.
      • Implement createCacheItemPool() to return your adapter.
      • Run tests to identify missing functionality.
  2. Regression Testing:

    • Use the shared test suite to ensure new releases of your adapter maintain compatibility with Laminas Cache standards.
    • Example:
      class MyAdapterRegressionTest extends AbstractCacheItemIntegrationTest
      {
          protected function createCacheItem(): CacheItemInterface
          {
              return $this->createCacheItemPool()->getItem('test-key');
          }
      }
      
  3. Custom Test Cases:

    • Extend or override test methods to add adapter-specific assertions.
    • Example:
      public function testCustomAdapterBehavior()
      {
          $this->assertTrue($this->createCacheItemPool()->getItem('test')->isHit());
          // Custom assertion for your adapter
      }
      

Integration Tips

  1. Leverage Sleep Timer:

    • Use the sleepTimer feature (introduced in v4.1.0) to speed up tests with expiry times:
      $this->sleepTimer = 0.1; // Reduce sleep time for faster tests
      
  2. PSR-6/PSR-16 Dual Support:

    • If your adapter supports both PSR-6 and PSR-16, create separate test classes extending the respective abstract classes.
  3. Mocking Dependencies:

    • Mock external dependencies (e.g., Redis client) in your test class to isolate adapter logic:
      use PHPUnit\Framework\TestCase;
      
      class MyAdapterTest extends TestCase
      {
          public function testAdapterWithMockedClient()
          {
              $mockClient = $this->createMock(Redis::class);
              $adapter = new MyRedisAdapter($mockClient);
              // Test assertions
          }
      }
      
  4. CI/CD Integration:

    • Include the test suite in your CI pipeline to catch regressions early. Example GitHub Actions workflow:
      jobs:
        test:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - run: composer install
            - run: vendor/bin/phpunit --testdox-html coverage.html
      

Gotchas and Tips

Pitfalls

  1. Non-Static Data Providers:

    • Older versions of PHPUnit (<10) may fail if data providers are not static. Ensure compatibility by using static data providers (as of v3.0.0+):
      public static function dataProviderForTest(): array
      {
          return [
              ['key1', 'value1'],
              ['key2', 'value2'],
          ];
      }
      
  2. Cache Pool Reference Issues:

    • Avoid reusing existing cache pools in tests. The package ensures this by design (since v3.0.0), but custom adapters may inadvertently share pools. Always create a new pool per test:
      protected function createCacheItemPool(): CacheItemPoolInterface
      {
          return new MyAdapter(); // New instance per test
      }
      
  3. Key Validation:

    • The package enforces strict key validation (e.g., maximum length). Ensure your adapter rejects invalid keys early:
      public function getItem($key)
      {
          if (strlen($key) > 255) {
              throw new InvalidArgumentException('Key too long');
          }
          // ...
      }
      
  4. Expiry Timeouts:

    • Tests with expiry times may hang if the sleep timer is too long. Use the sleepTimer property to optimize:
      protected $sleepTimer = 0.01; // 10ms sleep for expiry tests
      
  5. PHPUnit Version Mismatch:

    • The package is tested with PHPUnit 10+. If using an older version, expect failures (e.g., non-static data providers). Upgrade PHPUnit or pin to a compatible version:
      composer require --dev phpunit/phpunit:^9.5
      

Debugging

  1. Failed Assertions:

    • If a test fails unexpectedly, check the adapter's implementation against the PSR-6 or PSR-16 specs.
    • Example debug output:
      public function testGetItem()
      {
          $item = $this->createCacheItemPool()->getItem('test');
          $this->assertInstanceOf(CacheItemInterface::class, $item);
          $this->assertFalse($item->isHit()); // Debug: Is this expected?
      }
      
  2. Slow Tests:

    • Slow tests are often due to long expiry times or network latency (e.g., Redis). Use the sleepTimer property to reduce wait times:
      protected $sleepTimer = 0.1; // 100ms sleep for expiry checks
      
  3. Type Errors:

    • Ensure your adapter returns the correct types (e.g., CacheItemInterface, bool, null). Use PHP 8's strict typing or runtime checks:
      public function getItem($key): CacheItemInterface
      {
          return new MyCacheItem($key); // Must return CacheItemInterface
      }
      

Config Quirks

  1. Adapter-Specific Config:

    • The package does not enforce adapter-specific configurations (e.g., Redis host/port). Handle this in your adapter's constructor:
      class MyRedisAdapter implements CacheItemPoolInterface
      {
          public function __construct(private string $host, private int $port) {}
          // ...
      }
      
  2. Test Isolation:

    • Ensure tests are isolated by clearing the cache between runs. The package flushes the cache after each test by default (since v2.0.0), but custom adapters may need explicit clearing:
      protected function tearDown(): void
      {
          $this->createCacheItemPool()->clear();
          parent::tearDown();
      }
      

Extension Points

  1. Custom Test Cases:
    • Add adapter-specific test methods by extending the abstract classes:
      class MyAdapterTest extends AbstractCache
      
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai