Skip to content

Commit

Permalink
Merge pull request #282 from saloonphp/feature/prevent-stray-requests
Browse files Browse the repository at this point in the history
Feature | V2 Prevent Stray Requests
  • Loading branch information
Sammyjo20 committed Sep 3, 2023
2 parents f5dfb18 + ce5ba51 commit 1080111
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Exceptions/StrayRequestException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Saloon\Exceptions;

class StrayRequestException extends SaloonException
{
public function __construct()
{
parent::__construct('Attempted to make a real API request! Make sure to use a mock response or fixture.');
}
}
16 changes: 16 additions & 0 deletions src/Helpers/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
namespace Saloon\Helpers;

use Saloon\Contracts\Sender;
use Saloon\Contracts\PendingRequest;
use Saloon\Http\Senders\GuzzleSender;
use Saloon\Exceptions\StrayRequestException;
use Saloon\Contracts\MiddlewarePipeline as MiddlewarePipelineContract;

final class Config
Expand Down Expand Up @@ -101,4 +103,18 @@ public static function resetDefaultSender(): void
{
self::$defaultSender = self::DEFAULT_SENDER;
}

/**
* Throw an exception if a request without a MockClient is made.
*
* @return void
*/
public static function preventStrayRequests(): void
{
self::middleware()->onRequest(static function (PendingRequest $pendingRequest) {
if (! $pendingRequest->hasMockClient()) {
throw new StrayRequestException;
}
});
}
}
12 changes: 12 additions & 0 deletions tests/Unit/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
use Saloon\Http\Senders\GuzzleSender;
use Saloon\Exceptions\StrayRequestException;
use Saloon\Tests\Fixtures\Senders\ArraySender;
use Saloon\Tests\Fixtures\Requests\UserRequest;
use Saloon\Tests\Fixtures\Connectors\TestConnector;
Expand Down Expand Up @@ -68,3 +69,14 @@

expect($sender)->toBeInstanceOf(GuzzleSender::class);
});

test('you can prevent stray api requests', function () {
Config::preventStrayRequests();

$this->expectException(StrayRequestException::class);
$this->expectExceptionMessage('Attempted to make a real API request! Make sure to use a mock response or fixture.');

TestConnector::make()->send(new UserRequest);

Config::resetMiddleware();
});

0 comments on commit 1080111

Please sign in to comment.