MetadataResolverのFixtureを更新する仕組みを追加

This commit is contained in:
shibafu 2020-08-22 13:04:46 +09:00
parent 4360144d6f
commit f8952474b5
2 changed files with 56 additions and 7 deletions

View File

@ -9,6 +9,9 @@ LOG_CHANNEL=stack
# テストにモックを使用するか falseの場合は実際のHTML等を取得してテストする
TEST_USE_HTTP_MOCK=true
# テスト用のスナップショットを更新する場合はtrueにする (TEST_USE_HTTP_MOCKと重複させないよう注意)
TEST_UPDATE_SNAPSHOT=false
DB_CONNECTION=pgsql
DB_HOST=db
DB_PORT=5432

View File

@ -3,11 +3,14 @@
namespace Tests\Unit\MetadataResolver;
use App\MetadataResolver\Resolver;
use function Clue\StreamFilter\fun;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Monolog\Handler\AbstractHandler;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
trait CreateMockedResolver
{
@ -21,6 +24,18 @@ trait CreateMockedResolver
*/
protected $handler;
/**
* @var string
*/
protected $snapshotFilename;
protected function fetchSnapshot(string $filename): string
{
$this->snapshotFilename = $filename;
return file_get_contents($filename);
}
/**
* @param string $resolverClass
* @param string $responseText
@ -30,19 +45,27 @@ trait CreateMockedResolver
*/
protected function createResolver(string $resolverClass, string $responseText, array $headers = [], int $status = 200)
{
if (!$this->shouldUseMock()) {
if (!$this->shouldUseMock() && !$this->shouldUpdateSnapshot()) {
$this->resolver = app()->make($resolverClass);
return $this->resolver;
}
$headers += [
'content-type' => 'text/html',
];
if ($this->shouldUseMock()) {
$headers += [
'content-type' => 'text/html',
];
$mockResponse = new Response($status, $headers, $responseText);
$this->handler = new MockHandler([$mockResponse]);
}
$stack = HandlerStack::create($this->handler);
$client = new Client(['handler' => $stack]);
if ($this->shouldUpdateSnapshot()) {
$stack->push($this->makeUpdateSnapshotMiddleware());
}
$mockResponse = new Response($status, $headers, $responseText);
$this->handler = new MockHandler([$mockResponse]);
$client = new Client(['handler' => HandlerStack::create($this->handler)]);
$this->resolver = app()->make($resolverClass, ['client' => $client]);
return $this->resolver;
@ -52,4 +75,27 @@ trait CreateMockedResolver
{
return (bool) env('TEST_USE_HTTP_MOCK', true);
}
protected function shouldUpdateSnapshot(): bool
{
return (bool) env('TEST_UPDATE_SNAPSHOT', false);
}
protected function makeUpdateSnapshotMiddleware(): callable
{
return function (callable $next) {
return function (RequestInterface $request, array $options) use ($next) {
return $next($request, $options)->then(function (ResponseInterface $response) {
if (empty($this->snapshotFilename)) {
throw new \RuntimeException('スナップショットのファイル名が分かりません。file_get_contents()を使っている場合、fetchSnapshot()に置き換えてください。');
}
file_put_contents($this->snapshotFilename, (string) $response->getBody());
fwrite(STDERR, "Snapshot Updated: {$this->snapshotFilename}\n");
return $response;
});
};
};
}
}