Weave 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

Http Laravel Package

psr-mock/http

psr-mock/http is a tiny PHP package for mocking PSR-7 HTTP messages in tests. Create predictable request/response objects without a full HTTP client, helping you unit test middleware, clients, and services with minimal setup.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • PSR-7 Compliance: The package aligns perfectly with Laravel’s PSR-7 adoption (via symfony/http-foundation or nyholm/psr7), reducing friction in middleware, route handler, and HTTP client testing.
  • Test Isolation: Eliminates dependency on external HTTP servers (e.g., HttpFoundation mocks or Guzzle clients) for unit tests, improving speed and determinism.
  • Middleware Testing: Directly supports Laravel’s middleware pipeline testing (e.g., Illuminate\Http\Middleware) by providing mock ServerRequest/Response objects with preconfigured attributes.
  • Edge Case Coverage: Useful for testing Laravel’s validation, authentication middleware, or API response transformations without mocking entire HTTP stacks.

Integration Feasibility

  • Low Coupling: Minimal dependencies (PSR-7 only) ensure compatibility with Laravel’s existing PSR-7 implementations (e.g., nyholm/psr7).
  • Laravel-Specific Gaps: May lack Laravel-specific features (e.g., Request facade methods like input(), ajax()), requiring wrappers or extensions.
  • Tooling Synergy: Integrates seamlessly with Laravel’s testing tools (e.g., HttpTests, RefreshDatabase) when combined with Mockery or PHPUnit.

Technical Risk

  • False Positives/Negatives: Over-reliance on mocks might miss real-world HTTP quirks (e.g., chunked encoding, connection timeouts). Mitigate by pairing with integration tests.
  • Maintenance Burden: Custom wrappers for Laravel-specific Request features could diverge from upstream updates.
  • Performance Overhead: Mocks are lightweight, but excessive use in high-scale tests may slow CI pipelines (unlikely given the package’s design).

Key Questions

  1. Laravel-Specific Needs: Does the team require mocks for Laravel’s Request facade methods (e.g., old(), session())? If so, how will these be bridged?
  2. Test Strategy: Will this replace existing mocking approaches (e.g., createMock(ServerRequestInterface::class)), or supplement them for specific scenarios?
  3. Middleware Complexity: Are there middleware dependencies on non-PSR-7 features (e.g., Symfony\Component\HttpFoundation\File\UploadedFile) that this package doesn’t cover?
  4. CI/CD Impact: How will test speed improvements (or potential slowdowns from new mocks) affect CI feedback loops?
  5. Long-Term Support: Given the package’s low stars, is there a risk of stagnation? Are there active maintainers or forks (e.g., Laravel-specific versions)?

Integration Approach

Stack Fit

  • Core Use Case: Ideal for Laravel’s unit testing of HTTP layers, including:
    • Middleware (e.g., auth, CORS, rate limiting).
    • Route handlers/controllers (e.g., API responses, form submissions).
    • Service containers bound to Illuminate\Http\Request/Response.
  • Complementary Tools:
    • PHPUnit/Mockery: Use alongside existing mocking for hybrid approaches.
    • PestPHP: Can leverage the package’s fluent API for cleaner test syntax.
    • Laravel Dusk: For integration tests; this package targets unit tests only.
  • Avoid For:
    • Full-stack feature tests (use Dusk/BrowserKit).
    • Database-heavy tests (use Laravel’s DatabaseMigrations trait).

Migration Path

  1. Pilot Phase:
    • Replace 1–2 critical test suites (e.g., auth middleware) with psr-mock/http and compare:
      • Test readability.
      • Execution speed.
      • False positive/negative rates.
    • Example migration:
      // Before (Manual Mock)
      $request = $this->createMock(ServerRequestInterface::class);
      $request->method('getUri')->willReturn(new Uri('/test'));
      $request->method('getServerParams')->willReturn([]);
      
      // After (psr-mock/http)
      $request = (new MockRequest())
          ->withUri('/test')
          ->withServerParams([]);
      
  2. Wrapper Layer:
    • Create a thin facade (e.g., tests/TestHelpers) to extend mocks with Laravel-specific methods:
      class LaravelRequest extends MockRequest {
          public function withInput(array $input): self {
              return $this->withParsedBody($input);
          }
      }
      
  3. Gradual Adoption:
    • Start with new tests; refactor legacy tests incrementally.
    • Deprecate old mocking patterns via static analysis (e.g., PHPStan rules).

Compatibility

  • PSR-7 Implementations: Works with Laravel’s default (nyholm/psr7) or symfony/http-foundation.
  • Laravel Versions: Compatible with LTS versions (8.x–10.x); test against the oldest supported version.
  • Dependency Conflicts: No known conflicts with Laravel’s core packages or popular testing libraries.

Sequencing

  1. Phase 1: Middleware and route handler tests (high ROI, isolated components).
  2. Phase 2: Service layer tests interacting with Request/Response.
  3. Phase 3: Edge cases (e.g., file uploads, cookies, custom headers).
  4. Phase 4: Replace global test helpers (e.g., createTestRequest()) with package instances.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Cuts down on repetitive mock setup code.
    • Consistent Fixtures: Centralized mock generation reduces test flakiness.
    • MIT License: No legal barriers to adoption or modification.
  • Cons:
    • Custom Extensions: Laravel-specific wrappers may need updates with package changes (monitor for releases).
    • Documentation Gaps: Limited examples for Laravel use cases; may require internal docs.

Support

  • Debugging:
    • Mocks simplify debugging by providing predictable inputs, but complex middleware chains may still require logging or dd().
    • Use var_dump($request->getBody()->getContents()) for inspection.
  • Community:
    • Low-star package implies limited community support; rely on:
      • PSR-7 spec documentation.
      • Laravel’s existing middleware testing guides.
      • GitHub issues for package-specific bugs.
  • Fallbacks:
    • Always retain the ability to fall back to manual mocks or HttpFoundation for unsupported cases.

Scaling

  • Test Suite Growth:
    • Positive: Faster unit tests reduce CI bottlenecks (e.g., 50% reduction in mock setup time).
    • Negative: Over-mocking may obscure integration issues; balance with end-to-end tests.
  • Team Onboarding:
    • Ramp-Up: Developers familiar with PSR-7 will adopt quickly; others may need 1–2 hours of training.
    • Documentation: Create a TESTING.md guide with:
      • Common patterns (e.g., testing JSON APIs).
      • Anti-patterns (e.g., mocking database queries in HTTP tests).
  • Performance:
    • Mocks add negligible runtime overhead; focus on test parallelization (e.g., Pest’s --parallel).

Failure Modes

Risk Mitigation Detection
Over-mocking Enforce a rule: "No mocks for external services" (use HTTP clients instead). Code reviews, test naming conventions.
Laravel-specific gaps Maintain a LaravelRequest wrapper class. Test coverage reports.
Test flakiness Pair with integration tests (e.g., HttpTestCase). CI test stability metrics.
Package abandonment Fork or create a Laravel-specific version if needed. Monitor GitHub activity.
CI slowdowns Cache mock instances or use Pest’s --min-threads. CI benchmarking.

Ramp-Up

  • For Developers:
    • Training: 30-minute workshop on:
      • PSR-7 basics.
      • Package API (e.g., MockRequest::withJsonBody()).
      • Laravel integration patterns.
    • Cheat Sheet: Quick reference for common test scenarios (e.g., "How to test a middleware with a 401 response").
  • For TPM:
    • Metrics to Track:
      • Test execution time (pre/post-adoption).
      • Test creation velocity (e.g., lines of test code per sprint).
      • Defect escape rate (regressions caught in integration vs. unit tests).
    • Success Criteria:
      • 30% reduction in test setup time.
      • 90% of middleware tests migrated within 2 sprints.
      • No increase in test flakiness.
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.
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin