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

Philarmony Api Tester Bundle Laravel Package

deozza/philarmony-api-tester-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require deozza/philarmony-api-tester-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Deozza\PhilarmonyApiTesterBundle\PhilarmonyApiTesterBundle::class => ['all' => true],
    ];
    
  2. Configure Database Update .env.test (or .env for local testing) with a dedicated test database:

    DATABASE_URL="mysql://user:pass@127.0.0.1:3306/your_test_db"
    

    Or for SQLite:

    DATABASE_URL="sqlite:///%kernel.project_dir%/var/test.db"
    
  3. First Test Case Create a test class extending PhilarmonyApiTesterBundle\Test\ApiTestCase:

    namespace App\Tests;
    
    use PhilarmonyApiTesterBundle\Test\ApiTestCase;
    
    class UserApiTest extends ApiTestCase
    {
        public function testGetUsers()
        {
            $response = $this->get('/api/users');
            $this->assertEquals(200, $response->getStatusCode());
        }
    }
    
  4. Run Tests

    php bin/phpunit
    

Where to Look First

  • Bundle Docs: Review the README for setup and folder structure.
  • TestCase Base Class: Inspect PhilarmonyApiTesterBundle\Test\ApiTestCase for built-in assertions and helpers.
  • Fixtures: Use doctrine/doctrine-fixtures-bundle for test data setup (see example).

Implementation Patterns

Core Workflows

  1. Test Setup

    • Database Reset: The bundle auto-resets the test database after each test. Override setUp() to load fixtures:
      protected function setUp(): void
      {
          $this->loadFixtures([
              UserFixtures::class,
              RoleFixtures::class,
          ]);
          parent::setUp();
      }
      
    • Authentication: Use built-in helpers for API auth (e.g., JWT, API tokens):
      $this->authenticateAsUser($user); // If supported by the bundle.
      
  2. API Testing Patterns

    • HTTP Methods:
      $response = $this->get('/api/users');
      $response = $this->post('/api/users', ['name' => 'John']);
      $response = $this->put('/api/users/1', ['name' => 'Updated']);
      $response = $this->delete('/api/users/1');
      
    • Assertions:
      $this->assertStatusCode(201, $response);
      $this->assertJson($response->getContent());
      $this->assertEquals(['id' => 1, 'name' => 'John'], $response->toArray());
      
  3. Scenario Testing

    • Chain requests to test workflows:
      public function testUserCreationWorkflow()
      {
          // Create user.
          $createResponse = $this->post('/api/users', ['name' => 'Alice']);
          $this->assertStatusCode(201, $createResponse);
      
          // Fetch user.
          $userId = $createResponse->toArray()['id'];
          $fetchResponse = $this->get("/api/users/{$userId}");
          $this->assertStatusCode(200, $fetchResponse);
      }
      
  4. Integration with Fixtures

    • Use doctrine/doctrine-fixtures-bundle to preload test data:
      # config/packages/test/doctrine.yaml
      imports:
          - { resource: ../fixtures/test.yaml }
      
      Example fixture:
      // src/DataFixtures/UserFixtures.php
      namespace App\DataFixtures;
      
      use Doctrine\Bundle\FixturesBundle\Fixture;
      use Doctrine\Persistence\ObjectManager;
      use App\Entity\User;
      
      class UserFixtures extends Fixture
      {
          public function load(ObjectManager $manager)
          {
              $user = new User();
              $user->setName('Test User');
              $manager->persist($user);
              $manager->flush();
          }
      }
      
  5. Mocking External Services

    • Override createClient() to mock HTTP clients (e.g., Guzzle):
      protected function createClient(array $options = [], array $server = [])
      {
          $client = parent::createClient($options, $server);
          $client->getContainer()->set('test.guzzle.client', $this->createMockClient());
          return $client;
      }
      

Gotchas and Tips

Pitfalls

  1. Database Reset Overhead

    • The bundle resets the entire database after each test, which can slow down test suites. For large datasets, consider:
      • Using SQLite for faster resets.
      • Grouping related tests into a single test class to minimize resets.
      • Disabling resets for specific tests (if the bundle supports it; check docs).
  2. Fixture Loading Order

    • Fixtures are loaded in alphabetical order by default. Explicitly set dependencies:
      // src/DataFixtures/AppFixtures.php
      namespace App\DataFixtures;
      
      use Doctrine\Bundle\FixturesBundle\Fixture;
      use Doctrine\Persistence\ObjectManager;
      
      class AppFixtures extends Fixture
      {
          public function load(ObjectManager $manager)
          {
              $this->addReference('role_admin', $this->createRole('Admin'));
          }
      
          private function createRole(string $name): Role
          {
              $role = new Role();
              $role->setName($name);
              $manager->persist($role);
              return $role;
          }
      }
      
      Then reference them in other fixtures:
      $user->setRole($this->getReference('role_admin'));
      
  3. Authentication Quirks

    • If the bundle doesn’t support your auth method (e.g., custom JWT), manually set headers:
      $response = $this->get('/api/protected', [], [
          'HTTP_Authorization' => 'Bearer ' . $this->getToken(),
      ]);
      
  4. Assertion Limitations

    • The bundle may lack specific assertions (e.g., for nested JSON). Extend the base test case:
      use PhilarmonyApiTesterBundle\Test\ApiTestCase;
      
      class CustomApiTest extends ApiTestCase
      {
          protected function assertNestedJson(array $expected, $response)
          {
              $actual = $response->toArray();
              $this->assertArraySubset($expected, $actual);
          }
      }
      
  5. Environment Configuration

    • Ensure .env.test is loaded during tests. Add this to phpunit.xml:
      <php>
          <env name="APP_ENV" value="test"/>
          <env name="APP_DEBUG" value="true"/>
      </php>
      

Debugging Tips

  1. Enable Debug Mode Set APP_DEBUG=1 in .env.test to see detailed error logs.

  2. Inspect Responses Dump raw responses for debugging:

    $response = $this->get('/api/debug');
    file_put_contents('debug_response.json', $response->getContent());
    
  3. Database State Use a tool like Laravel Debugbar (if Symfony-compatible) or doctrine:schema:validate to check schema integrity:

    php bin/console doctrine:schema:validate
    
  4. Slow Tests Profile test execution with Xdebug or --stop-on-failure:

    php bin/phpunit --stop-on-failure
    

Extension Points

  1. Custom Assertions Extend the base test case to add reusable assertions:

    class ExtendedApiTest extends ApiTestCase
    {
        protected function assertApiError($response, string $field, string $message)
        {
            $data = $response->toArray();
            $this->assertArrayHasKey('errors', $data);
            $this->assertArrayHasKey($field, $data['errors']);
            $this->assertEquals($message, $data['errors'][$field][0]);
        }
    }
    
  2. Hooks for Pre/Post-Test Actions Override setUp() and tearDown():

    protected function setUp(): void
    {
        parent::setUp();
        $this->enableFeatureFlags(['new_ui']);
    }
    
    protected function tearDown(): void
    {
        $this->disableFeatureFlags(['new_ui']);
        parent::tearDown();
    }
    
  3. Custom Fixture Loaders Implement a custom loader

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