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

Net Mock Laravel Package

phrity/net-mock

Mocking layer for phrity/net-stream to simplify testing stream-based code. Drop-in compatible stream classes that can log all interactions via any PSR-3 logger and override behavior with callbacks. Includes PHPUnit expectation traits for asserting calls and parameters.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the package:

    composer require phrity/net-mock
    
  2. Replace real stream factory with mock in tests:

    use Phrity\Net\Mock\StreamFactory;
    
    // In your test setup
    $this->app->bind(\Phrity\Net\StreamFactory::class, function () {
        return new StreamFactory(); // Mock factory
    });
    
  3. First use case: Verify stream writes

    use Phrity\Net\Mock\ExpectSocketStreamTrait;
    
    class MyTest extends TestCase {
        use ExpectSocketStreamTrait;
    
        public function testStreamWrite() {
            $this->expectSocketStreamWrite()
                 ->addAssert(function (string $method, array $params) {
                     $this->assertEquals('test data', $params[0]);
                 });
    
            $stream = new SocketStream($resource);
            $stream->write('test data');
        }
    }
    

Where to Look First

  • Traits: Check ExpectSocketStreamTrait, ExpectContextTrait, etc., for available expectations.
  • Mock Class: Review Phrity\Net\Mock\Mock for global callbacks/logging.
  • StreamFactory: Understand how to swap real/mock implementations.

Implementation Patterns

Usage Patterns

  1. Dependency Injection

    // In Laravel service provider
    $this->app->when(\Your\StreamUsingClass::class)
               ->needs(\Phrity\Net\StreamFactory::class)
               ->give(function () {
                   return config('app.env') === 'testing'
                       ? new \Phrity\Net\Mock\StreamFactory()
                       : new \Phrity\Net\RealStreamFactory();
               });
    
  2. Logging Interactions

    use Phrity\Net\Mock\Mock;
    use Monolog\Logger;
    
    $logger = new Logger('stream_mock');
    Mock::setLogger($logger);
    
    // All stream calls will log to Monolog
    
  3. Callback-Based Mocking

    Mock::setCallback(function ($counter, $method, $params, $default) {
        if ($method === 'write') {
            $this->assertEquals('expected', $params[0]);
            return true; // Simulate success
        }
        return $default($params); // Fallback to real implementation
    });
    
  4. Expectation Stack in Tests

    use Phrity\Net\Mock\ExpectSocketStreamTrait;
    
    class MyTest {
        use ExpectSocketStreamTrait;
    
        public function testComplexScenario() {
            $this->expectSocketStreamWrite()
                 ->times(3)
                 ->addAssert(function ($method, $params) {
                     $this->assertStringStartsWith('prefix', $params[0]);
                 });
    
            $this->expectSocketStreamClose()->setReturn(true);
        }
    }
    

Workflows

  1. Test-Driven Development (TDD)

    • Write expectations first, then implement real logic.
    • Example: Verify a stream reads exactly 1024 bytes before processing.
  2. Debugging Production Issues

    • Enable logging in staging:
      Mock::setLogger(new \Monolog\Logger('stream_debug'));
      
    • Reproduce issues locally with mocked delays/errors.
  3. Integration Testing

    • Mock external streams (e.g., third-party APIs) while testing business logic.

Integration Tips

  • Laravel Service Container: Bind mock factory to an interface for easy swapping.
  • Pest/PHPUnit: Use traits in test classes for cleaner assertions.
  • Configuration: Store mock settings in config/testing.php:
    'stream_mock' => [
        'enabled' => env('STREAM_MOCK_ENABLED', false),
        'logger' => \Phrity\Net\Mock\EchoLogger::class,
    ],
    

Gotchas and Tips

Pitfalls

  1. Expectation Leaks

    • Forgetting tearDownStack() causes tests to fail silently.
    • Fix: Use setUp()/tearDown() in test classes.
  2. Version Mismatches

    • net-mock@2.4 requires net-stream@2.4. Always align versions.
    • Fix: Use composer require phrity/net-stream:^2.4 alongside the mock.
  3. Stateful Streams

    • Mocks don’t preserve real stream state (e.g., position, buffers).
    • Fix: Reset mocks between tests or use callbacks to manage state.
  4. Global Callbacks

    • Mock::setCallback() affects all tests. Overwrite carefully.
    • Fix: Set/unset callbacks in setUp()/tearDown().
  5. PHP 8.1+ Requirement

    • May conflict with older Laravel versions (e.g., Lumen 8.0).
    • Fix: Use Docker or adjust CI matrix.

Debugging

  • Enable Logging

    Mock::setLogger(new \Phrity\Net\Mock\EchoLogger());
    

    Outputs all method calls to stderr.

  • Inspect Stack

    $stack = Mock::getStack();
    print_r($stack->getExpectations());
    
  • Fallback to Real Implementation Use $default in callbacks to debug real behavior:

    Mock::setCallback(function ($counter, $method, $params, $default) {
        return $default($params); // Bypass mock
    });
    

Tips

  1. Partial Mocking Mock only specific methods:

    $this->expectSocketStreamWrite()->setReturn(true);
    // Other methods use real implementation
    
  2. Dynamic Returns

    $this->expectSocketStreamRead()->setReturn(function () {
        return 'dynamic_' . time();
    });
    
  3. Laravel Facades Create a facade for Mock to simplify usage:

    // app/Facades/StreamMock.php
    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class StreamMock extends Facade {
        protected static function getFacadeAccessor() {
            return 'stream.mock';
        }
    }
    
  4. Performance

    • Mocks add overhead. Disable in production:
      if (app()->environment('production')) {
          $factory = new \Phrity\Net\RealStreamFactory();
      }
      
  5. Extending Mocks Create custom traits for domain-specific expectations:

    trait ExpectCustomStreamTrait {
        public function expectCustomStream() {
            return $this->expect('customStream', 'method');
        }
    }
    
  6. CI/CD Optimization

    • Run tests with mocks in CI to avoid flakiness.
    • Example .github/workflows/test.yml:
      steps:
        - run: composer require phrity/net-mock
        - run: php artisan test --env=testing
      
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