X-Git-Url: http://source.bookstackapp.com/bookstack/blobdiff_plain/e15fcf5b50e1831a90a04ded09f24e0c7b31d02e..refs/pull/2515/head:/tests/SharedTestHelpers.php diff --git a/tests/SharedTestHelpers.php b/tests/SharedTestHelpers.php index f7b7d5edf..02f7caae1 100644 --- a/tests/SharedTestHelpers.php +++ b/tests/SharedTestHelpers.php @@ -1,11 +1,11 @@ users()->first(); - if (!empty($attributes)) $user->forceFill($attributes)->save(); + if (!empty($attributes)) { + $user->forceFill($attributes)->save(); + } return $user; } @@ -174,15 +179,13 @@ trait SharedTestHelpers /** * Give the given user some permissions. - * @param User $user - * @param array $permissions */ - protected function giveUserPermissions(User $user, $permissions = []) + protected function giveUserPermissions(User $user, array $permissions = []) { $newRole = $this->createNewRole($permissions); $user->attachRole($newRole); $user->load('roles'); - $user->permissions(false); + $user->clearPermissionCache(); } /** @@ -267,14 +270,43 @@ trait SharedTestHelpers */ protected function assertPermissionError($response) { - if ($response instanceof BrowserKitTest) { - $response = \Illuminate\Foundation\Testing\TestResponse::fromBaseResponse($response->response); - } + PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), "Failed asserting the response contains a permission error."); + } + + /** + * Assert a permission error has occurred. + */ + protected function assertNotPermissionError($response) + { + PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), "Failed asserting the response does not contain a permission error."); + } + + /** + * Check if the given response is a permission error. + */ + private function isPermissionError($response): bool + { + return $response->status() === 302 + && $response->headers->get('Location') === url('/') + && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0; + } + + /** + * Set a test handler as the logging interface for the application. + * Allows capture of logs for checking against during tests. + */ + protected function withTestLogger(): TestHandler + { + $monolog = new Logger('testing'); + $testHandler = new TestHandler(); + $monolog->pushHandler($testHandler); + + Log::extend('testing', function() use ($monolog) { + return $monolog; + }); + Log::setDefaultDriver('testing'); - $response->assertRedirect('/'); - $this->assertSessionHas('error'); - $error = session()->pull('error'); - $this->assertStringStartsWith('You do not have permission to access', $error); + return $testHandler; } } \ No newline at end of file