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

[8.x] Fix display of validation errors occurred when asserting status #38088

Merged
merged 6 commits into from
Jul 21, 2021
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 47 additions & 22 deletions src/Illuminate/Testing/TestResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Contracts\View\View;
use Illuminate\Cookie\CookieValuePrefix;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
Expand Down Expand Up @@ -80,13 +81,10 @@ public static function fromBaseResponse($response)
*/
public function assertSuccessful()
{
$lastException = $this->exceptions->last();

$message = isset($lastException)
? $this->statusMessageWithException('>=200, <300', $this->getStatusCode(), $lastException)
: 'Response status code ['.$this->getStatusCode().'] is not a successful status code.';

PHPUnit::assertTrue($this->isSuccessful(), $message);
PHPUnit::assertTrue(
$this->isSuccessful(),
$this->statusMessageWithDetails('>=200, <300', $this->getStatusCode())
);

return $this;
}
Expand Down Expand Up @@ -164,21 +162,47 @@ public function assertUnauthorized()
*/
public function assertStatus($status)
{
$actual = $this->getStatusCode();

$lastException = $actual !== $status && in_array($actual, [422, 500])
? $this->exceptions->last()
: null;

$message = isset($lastException)
? $this->statusMessageWithException($status, $actual, $lastException)
: "Expected status code [{$status}] but received {$actual}.";
$message = $this->statusMessageWithDetails($status, $actual = $this->getStatusCode());

PHPUnit::assertSame($actual, $status, $message);

return $this;
}

/**
* Get an assertion message for a status assertion containing extra details when available.
*
* @param string|int $expected
* @param string|int $actual
* @return string
*/
protected function statusMessageWithDetails($expected, $actual)
{
$lastException = $this->exceptions->last();

if ($lastException) {
return $this->statusMessageWithException($expected, $actual, $lastException);
}

if ($this->baseResponse instanceof RedirectResponse) {
$session = $this->baseResponse->getSession();

if (! is_null($session) && $session->has('errors')) {
return $this->statusMessageWithErrors($expected, $actual, $session->get('errors')->all());
}
}

if ($this->baseResponse->headers->get('Content-Type') === 'application/json') {
$json = $this->json();

if (isset($json['errors'])) {
return $this->statusMessageWithErrors($expected, $actual, $json);
}
}

return "Expected response status code [{$expected}] but received {$actual}.";
}

/**
* Get an assertion message for a status assertion that has an unexpected exception.
*
Expand All @@ -205,25 +229,26 @@ protected function statusMessageWithException($expected, $actual, $exception)
}

/**
* Get an assertion message for a status assertion that has an unexpected validation exception.
* Get an assertion message for a status assertion that contained errors.
*
* @param string|int $expected
* @param string|int $actual
* @param \Illuminate\Validation\ValidationException $exception;
* @param array $errors;
* @return string
*/
protected function statusMessageWithValidationErrors($expected, $actual, $exception)
protected function statusMessageWithErrors($expected, $actual, $errors)
{
$errors = $this->baseResponse->headers->get('Content-Type') === 'application/json'
? json_encode($exception->errors(), JSON_PRETTY_PRINT)
: implode(PHP_EOL, Arr::flatten($exception->errors()));
? json_encode($errors, JSON_PRETTY_PRINT)
: implode(PHP_EOL, Arr::flatten($errors));

return <<<EOF
Expected response status code [$expected] but received $actual.

The following validation errors occurred during the request:
The following errors occurred during the request:

$errors

EOF;
}

Expand Down
68 changes: 31 additions & 37 deletions tests/Testing/TestResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Encryption\Encrypter;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\Session\ArraySessionHandler;
use Illuminate\Session\Store;
use Illuminate\Testing\Fluent\AssertableJson;
use Illuminate\Testing\TestResponse;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Factory as ValidationFactory;
use Illuminate\Validation\ValidationException;
use JsonSerializable;
use Mockery as m;
use PHPUnit\Framework\AssertionFailedError;
Expand Down Expand Up @@ -398,7 +397,7 @@ public function testAssertOk()

$this->expectException(AssertionFailedError::class);

$this->expectExceptionMessage('Expected status code');
$this->expectExceptionMessage('Expected response status code');

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
Expand All @@ -414,7 +413,7 @@ public function testAssertCreated()

$this->expectException(AssertionFailedError::class);

$this->expectExceptionMessage('Expected status code');
$this->expectExceptionMessage('Expected response status code');

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
Expand All @@ -429,7 +428,7 @@ public function testAssertNotFound()
$statusCode = 500;

$this->expectException(AssertionFailedError::class);
$this->expectExceptionMessage('Expected status code');
$this->expectExceptionMessage('Expected response status code');

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
Expand All @@ -445,7 +444,7 @@ public function testAssertForbidden()

$this->expectException(AssertionFailedError::class);

$this->expectExceptionMessage('Expected status code');
$this->expectExceptionMessage('Expected response status code');

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
Expand All @@ -461,7 +460,7 @@ public function testAssertUnauthorized()

$this->expectException(AssertionFailedError::class);

$this->expectExceptionMessage('Expected status code');
$this->expectExceptionMessage('Expected response status code');

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
Expand All @@ -477,7 +476,7 @@ public function testAssertNoContentAsserts204StatusCodeByDefault()

$this->expectException(AssertionFailedError::class);

$this->expectExceptionMessage('Expected status code');
$this->expectExceptionMessage('Expected response status code');

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
Expand All @@ -494,7 +493,7 @@ public function testAssertNoContentAssertsExpectedStatusCode()

$this->expectException(AssertionFailedError::class);

$this->expectExceptionMessage('Expected status code');
$this->expectExceptionMessage('Expected response status code');

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
Expand Down Expand Up @@ -526,7 +525,7 @@ public function testAssertStatus()

$this->expectException(AssertionFailedError::class);

$this->expectExceptionMessage('Expected status code');
$this->expectExceptionMessage('Expected response status code');

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
Expand Down Expand Up @@ -555,32 +554,28 @@ public function testAssertStatusShowsExceptionOnUnexpected500()
$response->assertStatus($expectedStatusCode);
}

public function testAssertStatusShowsValidationErrorsOnUnexpected422()
public function testAssertStatusShowsErrorsOnUnexpectedErrorRedirect()
{
$statusCode = 422;
$statusCode = 302;
$expectedStatusCode = 200;

$this->expectException(AssertionFailedError::class);

$this->expectExceptionMessage('The first name field is required.');

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
$baseResponse = tap(new RedirectResponse('/', $statusCode), function ($response) {
$response->setSession(new Store('test-session', new ArraySessionHandler(1)));
$response->withErrors([
'first_name' => 'The first name field is required.',
'last_name' => 'The last name field is required.',
]);
});
$translator = new Translator(new ArrayLoader, 'en');
$validator = (new ValidationFactory($translator))->make(
[],
['first_name' => 'required', 'last_name' => 'required'],
['required' => 'The :attribute field is required.']
);
$exceptions = collect([new ValidationException($validator)]);

$response = TestResponse::fromBaseResponse($baseResponse)
->withExceptions($exceptions);
$response = TestResponse::fromBaseResponse($baseResponse);
$response->assertStatus($expectedStatusCode);
}

public function testAssertStatusShowsJsonValidationErrorsOnUnexpected422()
public function testAssertStatusShowsJsonErrorsOnUnexpected422()
{
$statusCode = 422;
$expectedStatusCode = 200;
Expand All @@ -589,19 +584,18 @@ public function testAssertStatusShowsJsonValidationErrorsOnUnexpected422()

$this->expectExceptionMessage('"The first name field is required."');

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
$response->header('Content-Type', 'application/json');
});
$translator = new Translator(new ArrayLoader, 'en');
$validator = (new ValidationFactory($translator))->make(
[],
['first_name' => 'required', 'last_name' => 'required'],
['required' => 'The :attribute field is required.']
$baseResponse = new Response(
[
'message' => 'The given data was invalid.',
'errors' => [
'first_name' => 'The first name field is required.',
'last_name' => 'The last name field is required.',
],
],
$statusCode
);
$exceptions = collect([new ValidationException($validator)]);

$response = TestResponse::fromBaseResponse($baseResponse)->withExceptions($exceptions);
$response = TestResponse::fromBaseResponse($baseResponse);
$response->assertStatus($expectedStatusCode);
}

Expand Down