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

Testing Laravel Package

atlas/testing

Atlas.Testing provides lightweight helpers and utilities for testing Atlas packages, aimed at simplifying test setup and improving consistency across Atlas-related projects. Suitable for package authors who need reusable testing support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require atlas/testing --dev
    

    Ensure it’s added to require-dev in composer.json to avoid production bloat.

  2. First Use Case: Extend AtlasTestCase to test Atlas-specific functionality. Example: Testing a many-to-many relationship:

    use Atlas\Testing\AtlasTestCase;
    
    class PostCategoryTest extends AtlasTestCase
    {
        public function test_many_to_many_relationship()
        {
            $post = $this->createPost(['title' => 'Atlas Testing']);
            $category = $this->createCategory(['name' => 'Laravel']);
    
            // Attach and assert relationship
            $post->categories()->attach($category);
            $this->assertCount(1, $post->categories);
            $this->assertCount(1, $category->posts);
        }
    }
    
  3. Where to Look First:

    • AtlasTestCase: Base class with helper methods like create{Model}, assertTableSchema, and assertCascadeDelete.
    • Changelog: Focus on 1.1.0 (many-to-many support) and 1.2.0 (tables without primary keys) for edge-case testing.
    • Example Tests: Clone the repo and inspect the tests directory for real-world usage patterns.

Implementation Patterns

Usage Patterns

  1. Model and Relationship Testing:

    • Creation: Use create{Model} helpers (e.g., createUser(), createPost()) to scaffold test data with relationships.
      $user = $this->createUser(['name' => 'Test User']);
      $this->createPost(['user_id' => $user->id, 'title' => 'Test Post']);
      
    • Assertions: Validate relationships with Atlas-specific methods:
      $this->assertRelatedTo($post, $user, 'user'); // 1:1 or 1:N
      $this->assertManyToManyRelation($post, $category); // M:N
      
  2. Schema Validation:

    • Verify table structures, including edge cases like tables without primary keys:
      $this->assertTableSchema('posts', [
          'columns' => ['id', 'user_id', 'title', 'created_at'],
          'primaryKey' => 'id', // or null for no PK
      ]);
      
  3. Cascade Operations:

    • Test cascading deletes or updates:
      $this->assertCascadeDelete($parent, $child); // Child deleted when parent is deleted
      
  4. Dynamic Data Manipulation:

    • Use AtlasTestCase’s query builders to simulate complex operations:
      $result = $this->query('SELECT * FROM posts WHERE user_id = ?', [$user->id]);
      $this->assertCount(1, $result);
      

Workflows

  1. Test-Driven Development (TDD) for Atlas:

    • Write tests for Atlas-specific logic (e.g., custom relationships) before implementing the feature.
    • Example: Test a polymorphic relationship before building it:
      public function test_polymorphic_relation()
      {
          $commentable = $this->createPost(['title' => 'Polymorphic Test']);
          $comment = $this->createComment(['commentable_id' => $commentable->id, 'commentable_type' => Post::class]);
      
          $this->assertInstanceOf(Post::class, $comment->commentable);
      }
      
  2. Regression Testing:

    • Use the package to automate regression tests for Atlas migrations or schema changes:
      public function test_schema_migration()
      {
          $this->assertTableExists('posts');
          $this->assertColumnExists('posts', 'user_id');
          $this->assertColumnDoesNotExist('posts', 'old_column');
      }
      
  3. Integration with Laravel Testing:

    • Combine with Laravel’s RefreshDatabase or DatabaseMigrations for full-stack tests:
      use Illuminate\Foundation\Testing\RefreshDatabase;
      
      class UserTest extends AtlasTestCase
      {
          use RefreshDatabase;
      
          public function test_user_creation()
          {
              $user = $this->createUser(['email' => 'test@example.com']);
              $this->assertDatabaseHas('users', ['email' => 'test@example.com']);
          }
      }
      

Integration Tips

  1. Custom Helpers:

    • Extend AtlasTestCase to add project-specific helpers:
      class CustomAtlasTestCase extends AtlasTestCase
      {
          protected function createAdminUser(array $attributes = [])
          {
              return $this->createUser(array_merge(['role' => 'admin'], $attributes));
          }
      }
      
  2. Mocking Atlas:

    • Use the package’s mocking capabilities to isolate Atlas logic in unit tests:
      $mockAtlas = $this->mockAtlas();
      $mockAtlas->shouldReceive('query')->once()->andReturn([$expectedRecord]);
      
  3. CI/CD Pipeline:

    • Add the package to your test suite in phpunit.xml or pest.php:
      <testsuites>
          <testsuite name="Atlas Tests">
              <directory>./tests/Atlas</directory>
          </testsuite>
      </testsuites>
      

Gotchas and Tips

Pitfalls

  1. Stagnant Package:

    • Issue: Last release in 2020; no active maintenance.
    • Fix: Fork the package and maintain it internally. Monitor Atlas updates for breaking changes.
    • Workaround: Use the package for stable features (e.g., relationship testing) but avoid relying on undocumented or edge-case functionality.
  2. Atlas Version Lock:

    • Issue: The package may not support newer Atlas versions.
    • Fix: Pin the Atlas version in composer.json to match the package’s compatibility:
      "require": {
          "atlasphp/atlas": "1.2.*"
      }
      
  3. Limited Documentation:

    • Issue: No comprehensive docs; changelog is minimal.
    • Fix: Create internal docs with examples for your team. Refer to the test directory for usage patterns.
  4. Database State Leaks:

    • Issue: Tests may interfere if not properly isolated (e.g., shared database state).
    • Fix: Use AtlasTestCase’s transactions or Laravel’s RefreshDatabase:
      use Illuminate\Foundation\Testing\RefreshDatabase;
      
      class PostTest extends AtlasTestCase
      {
          use RefreshDatabase;
      }
      
  5. Assertion Overhead:

    • Issue: Custom assertions may slow down tests.
    • Fix: Benchmark critical tests. Use simpler assertions (e.g., Laravel’s assertDatabaseHas) where possible.

Debugging Tips

  1. Enable Query Logging:

    • Debug SQL queries generated by Atlas:
      $this->app['db']->enableQueryLog();
      $this->createUser(['name' => 'Test']);
      dd($this->app['db']->getQueryLog());
      
  2. Inspect Test Data:

    • Dump test data to verify state:
      $user = $this->createUser(['name' => 'Debug User']);
      dd($user->fresh()->toArray());
      
  3. Isolate Flaky Tests:

    • If a test fails intermittently, add retries or isolate it:
      $this->retry(3, function () {
          $this->assertCount(1, $user->posts);
      }, 100); // Retry 3 times with 100ms delay
      

Config Quirks

  1. Database Configuration:

    • Ensure your .env.testing or phpunit.xml points to a clean test database:
      <env name="DB_DATABASE" value="atlas_testing"/>
      
  2. Timezone Handling:

    • Atlas may use UTC by default. Set a consistent timezone in tests:
      $this->app->setTimezone('UTC');
      
  3. Primary Key Assumptions:

    • The package supports tables without primary keys (added in 1.2.0), but some assertions may assume PKs exist. Explicitly handle edge cases:
      $this->assertTableSchema('log_entries', [
          'columns' => ['message', 'created_at'],
          'primaryKey' => null, // No PK
      ]);
      

Extension Points

  1. Custom Assertions:
    • Extend the package by creating custom assertions. Example:
      class CustomAssertions extends AtlasTestCase
      {
          public function assertSoftDeletes($model, $deletedAt = null)
          {
              $deletedAt = $deletedAt ?? now();
              $this->assertSoftDeleted($model, $deletedAt);
              $this->assertNull($
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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