matchOrigin matcher

This commit is contained in:
Pavel 2021-05-25 10:49:29 +03:00
parent 321650388e
commit b4142304ab
2 changed files with 68 additions and 0 deletions

View File

@ -43,6 +43,7 @@ use Pock\Traits\JsonDecoderTrait;
use Pock\Traits\JsonSerializerAwareTrait;
use Pock\Traits\XmlSerializerAwareTrait;
use Psr\Http\Client\ClientInterface;
use RuntimeException;
use Throwable;
/**
@ -129,6 +130,33 @@ class PockBuilder
return $this->addMatcher(new HostMatcher($host));
}
/**
* Matches request by origin.
*
* @param string $origin
*
* @return self
* @throws \RuntimeException
*/
public function matchOrigin(string $origin): self
{
$parsed = parse_url($origin);
if (!is_array($parsed)) {
throw new RuntimeException('Malformed origin: ' . $origin);
}
if (array_key_exists('scheme', $parsed) && !empty($parsed['scheme'])) {
$this->matchScheme($parsed['scheme']);
}
if (array_key_exists('host', $parsed) && !empty($parsed['host'])) {
$this->matchHost($parsed['host']);
}
return $this;
}
/**
* Matches request by the whole URI.
*

View File

@ -151,6 +151,46 @@ class PockBuilderTest extends PockTestCase
self::assertEquals('Successful', $response->getBody()->getContents());
}
public function testMatchOriginFailure(): void
{
$incorrectOrigin = RequestScheme::HTTPS . ':///' . self::TEST_HOST;
$this->expectExceptionMessage($incorrectOrigin);
$builder = new PockBuilder();
$builder->matchMethod(RequestMethod::GET)
->matchOrigin($incorrectOrigin)
->reply(200)
->withHeader('Content-Type', 'text/plain')
->withBody('Successful');
$builder->getClient()->sendRequest(
self::getPsr17Factory()
->createRequest(RequestMethod::GET, 'https://another-example.com')
);
}
public function testMatchOrigin(): void
{
$origin = RequestScheme::HTTPS . '://' . self::TEST_HOST;
$builder = new PockBuilder();
$builder->matchMethod(RequestMethod::GET)
->matchOrigin($origin)
->reply(200)
->withHeader('Content-Type', 'text/plain')
->withBody('Successful');
$response = $builder->getClient()->sendRequest(
self::getPsr17Factory()
->createRequest(RequestMethod::GET, $origin)
);
self::assertEquals(200, $response->getStatusCode());
self::assertEquals(['Content-Type' => ['text/plain']], $response->getHeaders());
self::assertEquals('Successful', $response->getBody()->getContents());
}
public function testMatchExactHeader(): void
{
$builder = new PockBuilder();