Skip to content

[9.x] Handle requests in test (rather than separate server process) #1170

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,17 @@
"php": "^8.1",
"ext-json": "*",
"ext-zip": "*",
"ext-sockets": "*",
"guzzlehttp/guzzle": "^7.5",
"illuminate/console": "^10.0|^11.0|^12.0",
"illuminate/support": "^10.0|^11.0|^12.0",
"php-webdriver/webdriver": "^1.15.2",
"react/event-loop": "^1.5",
"react/http": "^1.10",
"symfony/console": "^6.2|^7.0",
"symfony/finder": "^6.2|^7.0",
"symfony/process": "^6.2|^7.0",
"symfony/psr-http-message-bridge": "^7.1",
"vlucas/phpdotenv": "^5.2"
},
"require-dev": {
Expand Down
17 changes: 16 additions & 1 deletion src/Browser.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
use Facebook\WebDriver\WebDriverPoint;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use Laravel\Dusk\Http\ProxyServer;
use Laravel\Dusk\Http\UrlGenerator;
use React\EventLoop\Loop;

class Browser
{
Expand Down Expand Up @@ -182,6 +185,9 @@ public function visit($url)
$url = static::$baseUrl.'/'.ltrim($url, '/');
}

// Pass the request through our proxy
$url = app(UrlGenerator::class)->proxy($url);

$this->driver->navigate()->to($url);

// If the page variable was set, we will call the "on" method which will set a
Expand Down Expand Up @@ -675,7 +681,16 @@ public function onComponent($component, $parentResolver)
*/
public function pause($milliseconds)
{
usleep($milliseconds * 1000);
$sleeping = true;

Loop::addTimer($milliseconds / 1000, function () use (&$sleeping) {
$sleeping = false;
Loop::stop();
});

while ($sleeping) {
Loop::run();
}

return $this;
}
Expand Down
27 changes: 27 additions & 0 deletions src/Concerns/ProvidesProxyServer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Laravel\Dusk\Concerns;

use Illuminate\Contracts\Routing\UrlGenerator as UrlGeneratorContract;
use Illuminate\Routing\UrlGenerator as BaseUrlGenerator;
use Laravel\Dusk\Http\ProxyServer;
use Laravel\Dusk\Http\UrlGenerator;
use PHPUnit\Framework\Attributes\Before;

trait ProvidesProxyServer
{
#[Before]
public function setUpProvidesProxyServer(): void
{
$this->afterApplicationCreated(function () {
$this->app->make(ProxyServer::class)->listen();
$this->app->instance('url', $this->app->make(UrlGenerator::class));
$this->app->instance(UrlGeneratorContract::class, $this->app->make(UrlGenerator::class));
$this->app->instance(BaseUrlGenerator::class, $this->app->make(UrlGenerator::class));
});

$this->beforeApplicationDestroyed(function () {
$this->app->make(ProxyServer::class)->flush();
});
}
}
190 changes: 190 additions & 0 deletions src/Driver/AsyncCommandExecutor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
<?php

namespace Laravel\Dusk\Driver;

use Facebook\WebDriver\Exception\Internal\LogicException;
use Facebook\WebDriver\Exception\WebDriverException;
use Facebook\WebDriver\Remote\HttpCommandExecutor;
use Facebook\WebDriver\Remote\WebDriverCommand;
use Facebook\WebDriver\Remote\WebDriverResponse;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use JsonException;
use Psr\Http\Message\ResponseInterface;
use React\EventLoop\Loop;
use React\Http\Browser as ReactHttpClient;
use React\Http\Message\ResponseException;
use React\Promise\PromiseInterface;
use Throwable;

class AsyncCommandExecutor extends HttpCommandExecutor
{
/**
* Execute a web driver command asynchronously.
*
* @param WebDriverCommand $command
* @return WebDriverResponse
*/
public function execute(WebDriverCommand $command): WebDriverResponse
{
$client = (new ReactHttpClient())->withRejectErrorResponse(false);

[$url, $method, $headers, $payload] = $this->extractRequestDataFromCommand($command);

return $this->sendRequestAndWaitForResponse(match ($method) {
'GET' => $client->get($url, $headers),
'POST' => $client->post($url, $headers, $this->encodePayload($payload)),
'DELETE' => $client->delete($url, $headers),
});
}

/**
* Run event loop until request is fulfilled.
*
* @param PromiseInterface $request
* @return WebDriverResponse
*
* @throws JsonException
* @throws WebDriverException
*/
protected function sendRequestAndWaitForResponse(PromiseInterface $request): WebDriverResponse
{
$resolved = null;

$request->then(function ($response) use (&$resolved) {
Loop::get()->futureTick(fn() => Loop::stop());
$resolved = $response;
});

$request->catch(function (Throwable $exception) use (&$resolved) {
if ($resolved instanceof ResponseException) {
$resolved = $exception->getResponse();
} else {
throw $exception;
}
});

while ($resolved === null) {
Loop::run();
}

return $this->mapAsyncResponseToWebDriverResponse($resolved);
}

/**
* Parse HTTP response and map to web driver response.
*
* @param ResponseInterface $response
* @return WebDriverResponse
*
* @throws JsonException
* @throws WebDriverException
*/
protected function mapAsyncResponseToWebDriverResponse(ResponseInterface $response): WebDriverResponse
{
$value = null;
$message = null;
$sessionId = null;
$status = 0;

$results = json_decode($response->getBody(), true, 512, JSON_THROW_ON_ERROR);

if (is_array($results)) {
$value = Arr::get($results, 'value');
$message = Arr::get($results, 'message');
$status = Arr::get($results, 'status', 0);

if (is_array($value) && array_key_exists('sessionId', $value)) {
$sessionId = $value['sessionId'];
} elseif (array_key_exists('sessionId', $results)) {
$sessionId = $results['sessionId'];
}
}

if (is_array($value) && isset($value['error'])) {
WebDriverException::throwException($value['error'], $message, $results);
}

if ($status !== 0) {
WebDriverException::throwException($status, $message, $results);
}

return (new WebDriverResponse($sessionId))->setStatus($status)->setValue($value);
}

/**
* Ensure that payload is always a JSON object.
*
* @param Collection $payload
* @return string
*/
protected function encodePayload(Collection $payload): string
{
// POST body must be valid JSON object, even if empty: https://www.w3.org/TR/webdriver/#processing-model
if ($payload->isEmpty()) {
return '{}';
}

return $payload->toJson();
}

/**
* Extract data necessary to make HTTP request for web driver command.
*
* @param WebDriverCommand $command
* @return array{0: string, 1: string, 2: array, 3: Collection}
*
* @throws LogicException
*/
protected function extractRequestDataFromCommand(WebDriverCommand $command): array
{
['url' => $path, 'method' => $method] = $this->getCommandHttpOptions($command);

// Keys that are prefixed with ":" are URL parameters. All others are JSON payload data.
[$parameters, $payload] = collect($command->getParameters() ?? [])
->put(':sessionId', (string) $command->getSessionID())
->partition(fn($value, $key) => str_starts_with($key, ':'));

if ($payload->isNotEmpty() && $method !== 'POST') {
throw LogicException::forInvalidHttpMethod($path, $method, $payload->all());
}

$url = $this->url.$this->applyParametersToPath($parameters, $path);
$method = strtoupper($method);
$headers = $this->defaultHeaders($method);

return [$url, $method, $headers, $payload];
}

/**
* Replace prefixed placeholders with request parameters.
*
* @param Collection $parameters
* @param string $path
* @return string
*/
protected function applyParametersToPath(Collection $parameters, string $path): string
{
return str_replace($parameters->keys()->all(), $parameters->values()->all(), $path);
}

/**
* Get the default HTTP headers for a given request method.
*
* @param string $method
* @return array
*/
protected function defaultHeaders(string $method): array
{
$headers = collect(static::DEFAULT_HTTP_HEADERS)->mapWithKeys(function ($header) {
[$key, $value] = explode(':', $header, 2);
return [$key => $value];
});

if (in_array($method, ['POST', 'PUT'], true)) {
$headers->put('Expect', '');
}

return $headers->all();
}
}
57 changes: 57 additions & 0 deletions src/Driver/AsyncWebDriver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace Laravel\Dusk\Driver;

use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\HttpCommandExecutor;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverCapabilities;

class AsyncWebDriver extends RemoteWebDriver
{
/**
* Create a new asynchronous web driver instance.
*
* @param string $selenium_server_url
* @param DesiredCapabilities|array|null $desired_capabilities
* @param int|null $connection_timeout_in_ms
* @param int|null $request_timeout_in_ms
* @param string|null $http_proxy
* @param int|null $http_proxy_port
* @param DesiredCapabilities|null $required_capabilities
* @return AsyncWebDriver
*/
public static function create(
$selenium_server_url = 'http://localhost:4444/wd/hub',
$desired_capabilities = null,
$connection_timeout_in_ms = null,
$request_timeout_in_ms = null,
$http_proxy = null,
$http_proxy_port = null,
DesiredCapabilities $required_capabilities = null,
): AsyncWebDriver {
$factory = new AsyncWebDriverFactory(
$selenium_server_url, $desired_capabilities, $connection_timeout_in_ms,
$request_timeout_in_ms, $http_proxy, $http_proxy_port, $required_capabilities,
);

return $factory();
}

/**
* Public constructor to allow for instantiation via factory.
*
* @param AsyncCommandExecutor $commandExecutor
* @param string $sessionId
* @param WebDriverCapabilities $capabilities
* @param bool $isW3cCompliant
*/
public function __construct(
AsyncCommandExecutor $commandExecutor,
string $sessionId,
WebDriverCapabilities $capabilities,
bool $isW3cCompliant = false,
) {
parent::__construct($commandExecutor, $sessionId, $capabilities, $isW3cCompliant);
}
}
Loading
Loading