Skip to content

[HttpClient] Backport HAR files feature #18607

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

Merged
merged 2 commits into from
Jul 24, 2023
Merged
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
40 changes: 40 additions & 0 deletions http_client.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2196,6 +2196,45 @@ test it in a real application::
}
}

Testing using HAR files
~~~~~~~~~~~~~~~~~~~~~~~

The previous example can also be achieved using `HAR`_ files. You can export those files from all modern browsers (from the network tab) &
HTTP Clients. First, do the HTTP request(s) you want to test in your favorite HTTP Client / Browser, then store generated ``.har`` file somewhere in your application::

// ExternalArticleServiceTest.php
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;

final class ExternalArticleServiceTest extends TestCase
{
public function testSubmitData(): void
{
// Arrange
$fixtureDir = sprintf('%s/tests/fixtures/HTTP', static::getContainer()->getParameter('kernel.project_dir'));
$factory = new HarFileResponseFactory("$fixtureDir/example.com_archive.har");
$httpClient = new MockHttpClient($factory, 'https://example.com');
$service = new ExternalArticleService($httpClient);

// Act
$responseData = $service->createArticle($requestData);

// Assert
self::assertSame($responseData, 'the expected response');
}
}


If your service does multiple requests or if your `.har` file contains multiple request / response pairs,
the :class:`Symfony\\Component\\HttpClient\\Test\\HarFileResponseFactory` will find the associated response based on
the request method, url and body (if any). Note that **this doesn't work** if the request body or uri is random / always changing
(if it contains current date or random UUID(s) for example).

.. versionadded:: 6.4

The ``HarFileResponseFactory`` was introduced in Symfony 6.4.

Testing Network Transport Exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Expand Down Expand Up @@ -2262,3 +2301,4 @@ you to do so, by yielding the exception from its body::
.. _`idempotent method`: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Idempotent_methods
.. _`SSRF`: https://portswigger.net/web-security/ssrf
.. _`RFC 6570`: https://www.rfc-editor.org/rfc/rfc6570
.. _`HAR`: https://w3c.github.io/web-performance/specs/HAR/Overview.html