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

Data Tester Laravel Package

draw/data-tester

Lightweight PHP data testing helper for validating arrays/objects against expected shapes and values. Useful for unit tests and quick assertions, with simple matchers and readable failure messages to spot mismatches fast.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require --dev draw/data-tester
    

    Requires PHPUnit (v5.7, 6.0, or 7.0) and Symfony PropertyAccess.

  2. First Test Case Create a test class extending DataTester (or use traits if preferred):

    use Draw\DataTester\DataTester;
    
    class UserTest extends DataTester
    {
        public function testUserData()
        {
            $user = new User(['name' => 'John', 'email' => 'john@example.com']);
    
            $this->assert($user)
                ->hasProperty('name')
                ->isEqualTo('John')
                ->hasProperty('email')
                ->isEmail();
        }
    }
    
  3. Key Entry Points

    • assert($data): Start fluent assertions on any data structure (objects, arrays, collections).
    • Documentation: ReadTheDocs (archived but functional).

Implementation Patterns

Core Workflows

  1. Fluent Assertions for Data Validation Chain assertions for nested structures:

    $this->assert($user)
        ->hasProperty('address')
        ->isArray()
        ->hasKey('city')
        ->isEqualTo('Paris');
    
  2. Testing Collections Useful for Eloquent collections or arrays:

    $this->assert($users)
        ->isIterable()
        ->hasCount(3)
        ->each(function ($user) {
            $this->assert($user)->hasProperty('id');
        });
    
  3. Custom Assertions Extend DataTester or use traits to add domain-specific checks:

    trait AssertsUser
    {
        protected function assertUser($user)
        {
            return $this->assert($user)
                ->hasProperty('roles')
                ->isArray()
                ->hasCountBetween(1, 5);
        }
    }
    
  4. Integration with Laravel

    • Service Container: Bind the tester for reusable assertions:
      $this->app->singleton(DataTester::class, function ($app) {
          return new DataTester($app['property_access']);
      });
      
    • Test Helpers: Create a base test case:
      abstract class TestCase extends \Tests\TestCase
      {
          use DataTester;
      }
      
  5. Testing API Responses Validate JSON responses from controllers:

    $response = $this->get('/api/users/1');
    $this->assert(json_decode($response->getContent(), true))
        ->hasKey('data')
        ->hasKey('meta')
        ->hasProperty('data.id')
        ->isEqualTo(1);
    

Gotchas and Tips

Common Pitfalls

  1. Property Access Issues

    • Symfony PropertyAccess: The package relies on this for nested property access. If properties are private/protected, ensure they’re accessible or use __get() magic methods.
    • Debugging: Use ->dump() to inspect data structures mid-assertion:
      $this->assert($user)->dump()->hasProperty('name');
      
  2. Deprecated PHPUnit Features

    • The package was last updated in 2017 and may not support newer PHPUnit features (e.g., constraints in v9+). Stick to assertions like isEqualTo() over constraints.
  3. Performance with Large Data

    • Avoid deep nesting in assertions for large datasets (e.g., each() over 10,000 items). Pre-filter data if needed.
  4. False Positives in isEmail()

    • The built-in isEmail() may not cover all edge cases (e.g., internationalized emails). Extend with a custom validator:
      $this->assert($user)->hasProperty('email')->custom(function ($email) {
          return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
      });
      

Pro Tips

  1. Reusable Assertion Groups Create methods for common patterns (e.g., validating API responses):

    protected function assertApiSuccessResponse($response)
    {
        return $this->assert(json_decode($response->getContent(), true))
            ->hasKey('success', true)
            ->isEqualTo(true)
            ->hasKey('data');
    }
    
  2. Soft Assertions for Partial Validation Use ->soft() to continue testing after a failure (useful for optional fields):

    $this->assert($user)
        ->soft()
        ->hasProperty('middleName') // Fails silently
        ->hasProperty('name')       // Continues
        ->isEqualTo('John');
    
  3. Testing with Factories Combine with Laravel’s factories for consistent test data:

    $user = User::factory()->create();
    $this->assert($user)->hasProperty('created_at')->isInstanceOf(DateTime::class);
    
  4. Custom Error Messages Override default messages for clarity:

    $this->assert($user)
        ->hasProperty('name', 'User must have a name')
        ->isEqualTo('John', 'Name must be "John"');
    
  5. Legacy Code Workarounds

    • For private properties, use __call() in your test class:
      public function __call($method, $args)
      {
          if (str_starts_with($method, 'assertPrivate')) {
              $property = substr($method, 14);
              return $this->assertProperty($this->getObject(), $property, ...$args);
          }
      }
      
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony