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

Assert Laravel Package

testo/assert

Assertion plugin for the Testo PHP testing framework. Adds a fluent assert/expect facade, expectation lifecycle, and helpers for matching thrown exceptions. Reports comparisons through Testo’s standard pipeline. Install via Composer: testo/assert.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the package in your Laravel project (or Testo-based project):
    composer require --dev testo/assert
    
  2. Bootstrap Testo in your test environment. If using Laravel, ensure Testo is registered as a testing framework (may require custom configuration or a bridge package).
  3. Write your first assertion:
    use Testo\Assert\Assert;
    
    Assert::that($actualValue)->equals($expectedValue);
    
  4. Run tests via Testo’s CLI or Laravel’s test runner (if integrated).

Where to Look First

First Use Case

Replace a basic PHPUnit assertion with a fluent Testo assertion:

// Before (PHPUnit)
$this->assertArrayHasKey('data', $response);
$this->assertNotEmpty($response['data']);

// After (Testo)
Assert::that($response)
    ->arrayHasKey('data')
    ->isNotEmpty();

Implementation Patterns

Usage Patterns

  1. Fluent Assertions Chain methods for nested validations:

    Assert::that($user)
        ->isInstanceOf(User::class)
        ->hasAttribute('email', 'user@example.com')
        ->hasRole('admin');
    
  2. Exception Matching Assert exceptions with custom messages or types:

    Assert::that(fn() => $this->invalidOperation())
        ->throws(ValidationException::class)
        ->withMessage('The email field is required.');
    
  3. Collection Assertions Validate arrays/objects with diffs on failure:

    Assert::that($posts)
        ->isArray()
        ->hasCount(3)
        ->allMatch(fn($post) => Assert::that($post)->hasKey('title'));
    
  4. Lazy Assertions Defer evaluation until test failure (useful for setup/teardown):

    $lazyAssert = Assert::lazy($user)->isActive();
    // ... later in test ...
    $lazyAssert->assert();
    

Workflows

  • Test Setup: Use Assert::describe() to group related assertions for better reporting:
    Assert::describe('User Validation', function() {
        Assert::that($user)->isValid();
        Assert::that($user->roles)->contains('admin');
    });
    
  • Data-Driven Tests: Combine with Testo’s data providers for parameterized assertions.
  • Mock Integration: Use Testo’s mocking (if available) alongside assertions for side-effect testing.

Integration Tips

  • Laravel-Specific: If using Laravel, create a test helper to bridge Testo assertions with Laravel’s test responses:
    function assertResponseHasData($response) {
        Assert::that($response->json())
            ->arrayHasKey('data')
            ->isNotEmpty();
    }
    
  • Custom Matchers: Extend Assert by adding static methods for domain-specific checks:
    Assert::static('hasPermission', function($user, $permission) {
        return $user->permissions()->contains($permission);
    });
    
  • Testo Configuration: Ensure your testo.php config includes:
    'plugins' => [
        Testo\Assert\Assert::class,
    ],
    

Gotchas and Tips

Pitfalls

  1. Framework Lock-In

    • Testo’s low adoption means limited ecosystem support (e.g., no Laravel-specific plugins).
    • Mitigation: Evaluate if Testo’s features justify the risk.
  2. Assertion Exception Handling

    • Testo uses AssertionException and ComparisonFailure (not PHPUnit’s AssertionFailedError).
    • Tip: Catch exceptions explicitly if integrating with Laravel’s test listeners:
    try {
        Assert::that($user)->isActive();
    } catch (AssertionException $e) {
        $this->fail($e->getMessage());
    }
    
  3. Diff Output Quirks

    • ComparisonFailure diffs may not handle complex objects (e.g., DateTime, custom classes) intuitively.
    • Tip: Use ->toString() or custom __toString() for objects in assertions.
  4. IDE Autocompletion

    • PHPStorm may not recognize Testo’s fluent methods. Add a PHPStan baseline or custom stubs for autocomplete.
  5. Laravel Test Helpers Conflict

    • Laravel’s assertDatabaseHas() won’t work with Testo. Use Testo’s native DB assertions or create wrappers.

Debugging

  • Silent Failures: Ensure assertions are not wrapped in @test or try-catch without rethrowing.
  • Custom Messages: Add context to failures:
    Assert::that($user->age)->greaterThan(18)
        ->withMessage('User must be 18+ to access this feature.');
    
  • Log Assertions: For complex setups, log intermediate values before asserting:
    \Log::debug('Asserting on:', ['user' => $user->toArray()]);
    Assert::that($user)->isValid();
    

Config Quirks

  • Plugin Registration: If assertions fail silently, verify the plugin is loaded in testo.php:
    'plugins' => [
        Testo\Assert\Assert::class,
        // Other plugins...
    ],
    
  • PSR-4 Autoloading: Ensure testo/assert is in composer.json’s autoload-dev:
    "autoload-dev": {
        "psr-4": {
            "Testo\\": "vendor/testo/"
        }
    }
    

Extension Points

  1. Custom Assertions Extend the Assert class to add domain-specific methods:

    class DomainAssert extends Assert {
        public static function hasPermission($user, $permission) {
            return self::that($user->permissions)->contains($permission);
        }
    }
    
  2. Exception Matchers Override throws() behavior for custom exceptions:

    Assert::that(fn() => $this->action())
        ->throws(function($e) {
            return $e instanceof \RuntimeException
                && str_contains($e->getMessage(), 'timeout');
        });
    
  3. Testo Event Listeners Hook into Testo’s lifecycle to pre-process assertions (e.g., logging, mocking):

    Testo::listening(function($event) {
        if ($event instanceof AssertionPassed) {
            \Log::debug('Assertion passed:', [$event->assertion]);
        }
    });
    
  4. Laravel Test Events Bridge Testo assertions with Laravel’s test events (e.g., testsPassed):

    Testo::listening(function($event) {
        if ($event instanceof TestSuiteStarted) {
            \Log::info('Running Testo suite with custom assertions...');
        }
    });
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor