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, providing utilities for testing cache implementations. Useful in CI and unit tests to verify behavior of cache adapters and storage plugins within Laminas applications.

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 to test your custom cache adapter. For example:

    use Laminas\Cache\Storage\Adapter\Test\AbstractCacheItemPoolIntegrationTest;
    
    class MyRedisAdapterTest extends AbstractCacheItemPoolIntegrationTest
    {
        protected function createCachePool(): \Psr\Cache\CachePoolInterface
        {
            return new \Laminas\Cache\Storage\Adapter\RedisAdapter();
        }
    }
    
  3. Key Files to Explore:

    • src/AbstractCacheItemPoolIntegrationTest.php (for PSR-16 CachePool tests)
    • src/AbstractSimpleCacheIntegrationTest.php (for PSR-6 SimpleCache tests)
    • src/AbstractStorageIntegrationTest.php (for Laminas Cache Storage tests)

Implementation Patterns

Usage Patterns

  1. Testing PSR-16 CachePool Adapters: Extend AbstractCacheItemPoolIntegrationTest and implement createCachePool() to return your adapter instance.

    class RedisCachePoolTest extends AbstractCacheItemPoolIntegrationTest
    {
        protected function createCachePool(): \Psr\Cache\CachePoolInterface
        {
            return new \Laminas\Cache\Storage\Adapter\RedisAdapter([
                'host' => 'localhost',
                'port' => 6379,
            ]);
        }
    }
    
  2. Testing PSR-6 SimpleCache Adapters: Extend AbstractSimpleCacheIntegrationTest and implement createCache().

    class FilesystemSimpleCacheTest extends AbstractSimpleCacheIntegrationTest
    {
        protected function createCache(): \Psr\SimpleCache\CacheInterface
        {
            return new \Laminas\Cache\Storage\Adapter\FilesystemAdapter([
                'directory' => sys_get_temp_dir(),
            ]);
        }
    }
    
  3. Testing Laminas Cache Storage Adapters: Extend AbstractStorageIntegrationTest and implement createCacheStorage().

    class MemcachedStorageTest extends AbstractStorageIntegrationTest
    {
        protected function createCacheStorage(): \Laminas\Cache\Storage\StorageInterface
        {
            return new \Laminas\Cache\Storage\Adapter\MemcachedAdapter();
        }
    }
    
  4. Customizing Test Data: Override getTestData() to provide custom test data if needed.

    protected function getTestData(): array
    {
        return [
            'key1' => 'value1',
            'key2' => ['nested' => 'data'],
        ];
    }
    

Workflows

  1. Integration Testing: Use these abstract classes to verify your adapter's compliance with PSR-16, PSR-6, or Laminas Cache Storage interfaces. Run tests with:

    phpunit
    
  2. Edge Case Testing: Leverage built-in test cases for:

    • Cache expiration (testItemExpiration).
    • Key collisions (testKeyCollisionHandling).
    • Serialization/deserialization (testSerialization).
  3. Performance Testing: Use the sleepTimer feature (introduced in v4.1.0) to speed up tests involving expiry times:

    $this->sleepTimer = 0.1; // Reduce sleep time for faster tests
    

Integration Tips

  1. Leverage Laravel's Cache: If using Laravel, integrate your tested adapter into Laravel's cache config (config/cache.php):

    'stores' => [
        'redis' => [
            'driver' => 'redis',
            'connection' => 'cache',
            'options' => [
                'adapter' => \App\Cache\RedisAdapter::class,
            ],
        ],
    ],
    
  2. Mocking Adapters: For unit tests, mock the adapter and use the abstract test classes to validate behavior:

    $mockAdapter = $this->createMock(\Psr\Cache\CachePoolInterface::class);
    $test = new AbstractCacheItemPoolIntegrationTest();
    $test->setCachePool($mockAdapter);
    
  3. CI/CD Integration: Add the package to your composer.json under require-dev and include it in your CI pipeline to ensure adapter compliance.


Gotchas and Tips

Pitfalls

  1. Non-Static Data Providers: In PHPUnit 10+, data providers must be static. The package enforces this (see PR #52). Fix: Ensure your test classes extend the abstract classes correctly and avoid non-static data providers.

  2. Cache Pool References: The package ensures new cache pools are created for each test to avoid shared state issues (see PR #55). Tip: Avoid manually reusing cache pool instances across tests.

  3. Type-Safety: Invalid keys (e.g., non-string keys) are automatically filtered out (see PR #54). Tip: Ensure your adapter handles type-safe keys as expected.

  4. Unavailable Cache Adapters: Clearing an unavailable cache adapter (e.g., during tests) may throw errors (see PR #61). Fix: Implement graceful degradation or mock the adapter in such scenarios.

  5. PHPUnit 10 Migration: The package is fully compatible with PHPUnit 10 (see PR #51). Tip: Update your phpunit.xml to use PHPUnit 10 if not already done.

Debugging

  1. Slow Tests Due to Expiry: Use the sleepTimer property to reduce sleep durations in expiry-related tests:

    protected $sleepTimer = 0.01; // 10ms instead of default 1s
    
  2. Key Length Validation: The package includes tests for maximum key length (see PR #25). Debug Tip: If tests fail, check your adapter's key length handling logic.

  3. Serialization Issues: If tests fail due to serialization/deserialization, verify your adapter's serialize()/unserialize() methods:

    // Example debug method
    public function testSerialization()
    {
        $data = ['complex' => ['nested' => new \stdClass()]];
        $serialized = serialize($data);
        $unserialized = unserialize($serialized);
        $this->assertEquals($data, $unserialized);
    }
    

Config Quirks

  1. Adapter-Specific Config: Ensure your adapter's configuration matches the expected format in the abstract test classes. For example:

    // For RedisAdapter
    $adapter = new \Laminas\Cache\Storage\Adapter\RedisAdapter([
        'host' => '127.0.0.1',
        'port' => 6379,
        'database' => 0,
    ]);
    
  2. Environment-Specific Tests: Use Laravel's environment-specific configurations to test different adapter setups:

    // config/cache.php
    'stores' => [
        'local' => [
            'driver' => 'file',
            'path' => storage_path('framework/cache'),
        ],
        'redis' => [
            'driver' => 'redis',
            'connection' => env('CACHE_REDIS_CONNECTION', 'cache'),
        ],
    ],
    

Extension Points

  1. Custom Test Cases: Extend the abstract classes and add your own test methods:

    class CustomAdapterTest extends AbstractCacheItemPoolIntegrationTest
    {
        public function testCustomFeature()
        {
            $this->assertTrue($this->cachePool->hasItem('custom_key'));
        }
    }
    
  2. Mocking Dependencies: Use Laravel's mocking tools to test adapters with mocked dependencies:

    use Illuminate\Foundation\Testing\RefreshDatabase;
    
    class MockedAdapterTest extends TestCase
    {
        use RefreshDatabase;
    
        public function testWithMockedDependency()
        {
            $mock = Mockery::mock(\Psr\Cache\CacheItemInterface::class);
            $this->app->instance(\Psr\Cache\CacheItemInterface::class, $mock);
            // Test logic here
        }
    }
    
  3. Parallel Testing: The package is designed for parallel test execution. Ensure your adapter handles concurrent operations safely:

    // In phpunit.xml
    <phpunit>
        <extensions>
            <extension class
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony