Skip to content
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

[BrowserKit] Add jsonRequest function to the browser-kit client #38596

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Symfony/Component/BrowserKit/AbstractBrowser.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,24 @@ public function xmlHttpRequest(string $method, string $uri, array $parameters =
}
}

/**
* Converts the request parameters into a JSON string and uses it as request content.
*/
public function jsonRequest(string $method, string $uri, array $parameters = [], array $server = [], bool $changeHistory = true): Crawler
{
$content = json_encode($parameters);

$this->setServerParameter('CONTENT_TYPE', 'application/json');
$this->setServerParameter('HTTP_ACCEPT', 'application/json');

try {
return $this->request($method, $uri, [], [], $server, $content, $changeHistory);
} finally {
unset($this->server['CONTENT_TYPE']);
unset($this->server['HTTP_ACCEPT']);
}
}

/**
* Returns the History instance.
*
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/BrowserKit/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.3.0
-----

* Added `jsonRequest` method to `AbstractBrowser`

4.3.0
-----

Expand Down
11 changes: 11 additions & 0 deletions src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,17 @@ public function testXmlHttpRequest()
$this->assertFalse($client->getServerParameter('HTTP_X_REQUESTED_WITH', false));
}

public function testJsonRequest()
{
$client = $this->getBrowser();
$client->jsonRequest('GET', 'http://example.com/', ['param' => 1], [], true);
$this->assertSame('application/json', $client->getRequest()->getServer()['CONTENT_TYPE']);
$this->assertSame('application/json', $client->getRequest()->getServer()['HTTP_ACCEPT']);
$this->assertFalse($client->getServerParameter('CONTENT_TYPE', false));
$this->assertFalse($client->getServerParameter('HTTP_ACCEPT', false));
$this->assertSame('{"param":1}', $client->getRequest()->getContent());
}

public function testGetRequestWithIpAsHttpHost()
{
$client = $this->getBrowser();
Expand Down