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

Pest Plugin Drift Laravel Package

pestphp/pest-plugin-drift

Pest Plugin Drift adds drift detection to your Pest test suite, helping catch behavioral changes and flaky differences across runs. Install alongside Pest to track and report unexpected output or snapshot mismatches during testing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the plugin to your composer.json:

    composer require --dev pestphp/pest-plugin-drift
    

    Enable the plugin in pest.php:

    plugins([
        Pest\DriftPlugin::make(),
    ]);
    
  2. First Use Case Write a test with drift detection:

    test('user can login', function () {
        $response = $this->post('/login', ['email' => 'user@example.com', 'password' => 'password']);
    
        $response->assertOk();
        $response->assertDrift(); // <-- Drift detection
    })->drift(10); // Allow 10% drift
    
  3. Where to Look First

    • Plugin Documentation (if available)
    • tests/Feature/DriftTest.php (if included in the package)
    • vendor/pestphp/pest-plugin-drift/src/DriftPlugin.php (core logic)

Implementation Patterns

Common Workflows

  1. Drift Detection in API Tests

    test('GET /api/users returns paginated results', function () {
        $response = $this->get('/api/users');
    
        $response->assertOk()
                ->assertDrift()
                ->assertJsonStructure([...]);
    })->drift(5); // 5% allowed drift
    
  2. Conditional Drift Checks

    test('database-heavy endpoints tolerate drift', function () {
        if (config('app.env') === 'staging') {
            $this->get('/reports')->assertDrift(15);
        } else {
            $this->get('/reports')->assertNoDrift();
        }
    });
    
  3. Custom Drift Calculators

    use Pest\DriftPlugin\Drift;
    
    test('custom drift logic', function () {
        $actual = $this->get('/analytics')->json();
        $expected = file_get_contents('tests/data/analytics.json');
    
        Drift::assertDrift($actual, $expected, function ($a, $b) {
            return abs($a - $b) <= 0.1; // Custom tolerance
        });
    });
    
  4. Drift in Feature Tests

    test('livewire component renders with drift', function () {
        $this->livewire(AnalyticsDashboard::class)
              ->assertDrift(10)
              ->assertSee('Total Users');
    });
    

Integration Tips

  • Pair with Pest Plugins: Combine with pest-plugin-laravel for seamless Laravel integration.
  • CI/CD Pipelines: Use drift checks in staging to catch regressions early.
  • Mocking: Mock external APIs with known drift thresholds:
    $this->mock(Http::class, function ($mock) {
        $mock->shouldReceive('get')
             ->andReturn(response()->json(['data' => 100]), 200);
    });
    
    test('handles mocked drift')->assertDrift(20);
    

Gotchas and Tips

Pitfalls

  1. False Positives

    • Drift checks may flag legitimate changes (e.g., timestamps, UUIDs).
    • Fix: Exclude dynamic fields:
      $response->assertDrift()->ignore('created_at', 'updated_at');
      
  2. Performance Overhead

    • Drift calculations add runtime. Avoid in performance-critical tests.
    • Fix: Use sparingly or disable in CI for non-critical paths.
  3. Strict Mode Conflicts

    • assertNoDrift() + assertExactJson() may conflict.
    • Fix: Use one or the other per test.
  4. Floating-Point Precision

    • Floating-point comparisons can fail unexpectedly.
    • Fix: Round values or use custom calculators:
      Drift::assertDrift(round($actual, 2), round($expected, 2));
      

Debugging

  • Inspect Drift Details:
    $response->assertDrift()->dumpDifferences();
    
  • Log Drift Events: Enable verbose logging in pest.php:
    plugins([
        Pest\DriftPlugin::make()->logDriftEvents(),
    ]);
    

Configuration Quirks

  1. Global Drift Settings Override defaults in pest.php:

    plugins([
        Pest\DriftPlugin::make()->defaultDrift(5)->strictMode(false),
    ]);
    
  2. Environment-Specific Drift Use .env to toggle drift checks:

    test('drift enabled in staging')->drift(config('app.drift_threshold', 0));
    

Extension Points

  1. Custom Assertions Extend the plugin’s DriftAssertions trait:

    use Pest\DriftPlugin\DriftAssertions;
    
    trait CustomDriftAssertions {
        use DriftAssertions;
    
        public function assertCustomDrift($expected, $actual, $threshold = 10) {
            // Custom logic
        }
    }
    
  2. Pre-Test Hooks Modify drift behavior dynamically:

    beforeEach(function () {
        if ($this->actingAs('admin')) {
            $this->enableDrift(20); // Higher tolerance for admins
        }
    });
    
  3. Database Snapshots Combine with pest-plugin-database for drift-aware DB tests:

    test('database consistency')->assertDrift()->assertDatabaseHas(...);
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
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