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

Laravel Postmangen Laravel Package

movemoveapp/laravel-postmangen

Laravel package that generates a Postman collection (JSON) from HTTP requests executed during PHPUnit tests. Configure via .env and phpunit.xml, install the PHPUnit extension and middleware to capture requests and export collections automatically.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require movemoveapp/laravel-postmangen
    
  2. Publish the config:
    php artisan vendor:publish --provider="MoveMoveIo\Postmangen\PostmangenServiceProvider"
    
  3. Configure .env:
    POSTMANGEN_TMP=postman/
    
  4. Update phpunit.xml: Add the extension under <extensions>:
    <extensions>
        <bootstrap class="MoveMoveIo\Postmangen\PostmangenPhpunitExtension">
            <parameter name="outputDir" value="postman/"/>
        </bootstrap>
    </extensions>
    
  5. Add middleware (place this first in app/Http/Kernel.php):
    protected $middleware = [
        \MoveMoveIo\Postmangen\Phpunit\Middleware\PostmangenMiddleware::class,
        // ... other middleware
    ];
    

First Use Case

Run PHPUnit with the config file:

./vendor/bin/phpunit -c phpunit.xml

A JSON Postman collection (<APP_NAME>.postman_collection.json) will be generated in postman/.


Implementation Patterns

Core Workflow

  1. Test-Driven API Capture:

    • Write PHPUnit tests that trigger HTTP requests (e.g., GET /api/users).
    • The middleware captures requests/responses during test execution.
    • Postman collection is auto-generated after successful test runs.
  2. Grouping Logic:

    • Requests are grouped by "URI key" (default: method + URI).
    • Use @postmangenMustCapture annotation to force-capture requests that wouldn’t group (e.g., dynamic routes):
      /** @postmangenMustCapture */
      public function test_dynamic_route() { ... }
      
  3. Output Customization:

    • Override outputDir in phpunit.xml to change the output path.
    • Extend the collection format by modifying the PostmangenPhpunitExtension or overriding the PostmangenMiddleware.

Integration Tips

  • Exclude Tests: Use phpunit --filter="TestClass" to avoid generating collections for subsets of tests (disabled by default in v1.1.2+).
  • Middleware Order: Place PostmangenMiddleware before auth/middleware that might alter requests (e.g., VerifyCsrfToken).
  • CI/CD: Add a post-test step to commit the generated collection to version control (e.g., for API documentation):
    git add postman/<APP_NAME>.postman_collection.json && git commit -m "Update Postman collection"
    

Example Test Structure

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class UserApiTest extends TestCase
{
    use RefreshDatabase;

    /** @postmangenMustCapture */ // Forces capture for dynamic route
    public function test_create_user()
    {
        $response = $this->post('/api/users', ['name' => 'John']);
        $response->assertCreated();
    }

    public function test_list_users()
    {
        $this->get('/api/users')->assertOk(); // Auto-captured (GET /api/users)
    }
}

Gotchas and Tips

Pitfalls

  1. Failed Tests:

    • Collections won’t generate if tests fail (v1.1.4+). Use --stop-on-failure to bypass this.
    • Workaround: Run tests with --verbose to debug failures before regenerating.
  2. Dynamic Routes:

    • Requests with identical methods/URIs but different parameters (e.g., /users/1 vs /users/2) may merge in the collection.
    • Fix: Use @postmangenMustCapture or customize the grouping logic in the middleware.
  3. Middleware Conflicts:

    • Middleware like VerifyCsrfToken or auth may alter requests before capture.
    • Tip: Place PostmangenMiddleware first in Kernel.php to capture raw requests.
  4. Non-Standard Responses:

    • Custom responses lacking statusCode()/statusText() (e.g., PSR-7 implementations) may break (fixed in v1.1.6).
    • Debug: Check logs for UndefinedMethodException if collection generation fails.
  5. Date Headers:

    • Date headers are ignored by default (v1.1.4+). Re-enable by modifying the middleware’s filterHeaders logic.

Debugging

  • Verify Capture: Add dd($this->app->make('postmangen')->getRequests()) in a test to inspect captured requests.
  • Log Middleware: Temporarily add logging to PostmangenMiddleware to confirm requests are being intercepted:
    \Log::debug('Postmangen captured:', ['uri' => $request->fullUrl()]);
    
  • Check Output Dir: Ensure POSTMANGEN_TMP in .env is writable and doesn’t conflict with other paths.

Extension Points

  1. Custom Collection Format: Override the PostmangenPhpunitExtension to modify the JSON structure:

    class CustomPostmangenExtension extends \MoveMoveIo\Postmangen\PostmangenPhpunitExtension
    {
        protected function transformRequest($request) { ... }
        protected function transformResponse($response) { ... }
    }
    

    Register it in phpunit.xml:

    <bootstrap class="App\Tests\CustomPostmangenExtension"/>
    
  2. Filter Requests: Extend PostmangenMiddleware to exclude specific routes or methods:

    public function handle($request, Closure $next)
    {
        if ($request->is('admin/*')) return $next($request);
        // ... rest of logic
    }
    
  3. Post-Processing: Use Laravel’s commands to process the generated JSON (e.g., validate schema or upload to Postman):

    Artisan::command('postmangen:validate', function () {
        $collection = file_get_contents('postman/collection.json');
        // Add validation logic
    });
    

Configuration Quirks

  • Case Sensitivity: The outputDir in phpunit.xml must match the .env POSTMANGEN_TMP path exactly (including trailing slashes).
  • PHPUnit Version: Tested with PHPUnit 9+. Older versions may require adjustments to the extension bootstrap.
  • Environment-Specific: Use .env.testing to override POSTMANGEN_TMP for test environments:
    POSTMANGEN_TMP=storage/postman/
    
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.
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
spatie/flare-daemon-runtime