5 use BookStack\Auth\Permissions\JointPermissionBuilder;
6 use BookStack\Auth\Permissions\PermissionsRepo;
7 use BookStack\Auth\Permissions\RolePermission;
8 use BookStack\Auth\Role;
9 use BookStack\Auth\User;
10 use BookStack\Entities\Models\Book;
11 use BookStack\Entities\Models\Bookshelf;
12 use BookStack\Entities\Models\Chapter;
13 use BookStack\Entities\Models\Entity;
14 use BookStack\Entities\Models\Page;
15 use BookStack\Entities\Repos\BookRepo;
16 use BookStack\Entities\Repos\BookshelfRepo;
17 use BookStack\Entities\Repos\ChapterRepo;
18 use BookStack\Entities\Repos\PageRepo;
19 use BookStack\Settings\SettingService;
20 use BookStack\Uploads\HttpFetcher;
21 use GuzzleHttp\Client;
22 use GuzzleHttp\Handler\MockHandler;
23 use GuzzleHttp\HandlerStack;
24 use GuzzleHttp\Middleware;
25 use Illuminate\Http\JsonResponse;
26 use Illuminate\Support\Env;
27 use Illuminate\Support\Facades\Log;
28 use Illuminate\Testing\Assert as PHPUnit;
30 use Monolog\Handler\TestHandler;
32 use Psr\Http\Client\ClientInterface;
34 trait SharedTestHelpers
40 * Set the current user context to be an admin.
42 public function asAdmin()
44 return $this->actingAs($this->getAdmin());
48 * Get the current admin user.
50 public function getAdmin(): User
52 if (is_null($this->admin)) {
53 $adminRole = Role::getSystemRole('admin');
54 $this->admin = $adminRole->users->first();
61 * Set the current user context to be an editor.
63 public function asEditor()
65 return $this->actingAs($this->getEditor());
71 protected function getEditor(): User
73 if ($this->editor === null) {
74 $editorRole = Role::getRole('editor');
75 $this->editor = $editorRole->users->first();
82 * Get an instance of a user with 'viewer' permissions.
84 protected function getViewer(array $attributes = []): User
86 $user = Role::getRole('viewer')->users()->first();
87 if (!empty($attributes)) {
88 $user->forceFill($attributes)->save();
95 * Get a user that's not a system user such as the guest user.
97 public function getNormalUser(): User
99 return User::query()->where('system_name', '=', null)->get()->last();
103 * Regenerate the permission for an entity.
105 protected function regenEntityPermissions(Entity $entity): void
107 $entity->rebuildPermissions();
108 $entity->load('jointPermissions');
112 * Create and return a new bookshelf.
114 public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
116 return app(BookshelfRepo::class)->create($input, []);
120 * Create and return a new book.
122 public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
124 return app(BookRepo::class)->create($input);
128 * Create and return a new test chapter.
130 public function newChapter(array $input, Book $book): Chapter
132 return app(ChapterRepo::class)->create($input, $book);
136 * Create and return a new test page.
138 public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
140 $book = Book::query()->first();
141 $pageRepo = app(PageRepo::class);
142 $draftPage = $pageRepo->getNewDraftPage($book);
144 return $pageRepo->publishDraft($draftPage, $input);
148 * Quickly sets an array of settings.
150 protected function setSettings(array $settingsArray): void
152 $settings = app(SettingService::class);
153 foreach ($settingsArray as $key => $value) {
154 $settings->put($key, $value);
159 * Manually set some permissions on an entity.
161 protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
163 $entity->restricted = true;
164 $entity->permissions()->delete();
167 foreach ($actions as $action) {
168 foreach ($roles as $role) {
170 'role_id' => $role->id,
171 'action' => strtolower($action),
175 $entity->permissions()->createMany($permissions);
178 $entity->load('permissions');
179 $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($entity);
180 $entity->load('jointPermissions');
184 * Give the given user some permissions.
186 protected function giveUserPermissions(User $user, array $permissions = []): void
188 $newRole = $this->createNewRole($permissions);
189 $user->attachRole($newRole);
190 $user->load('roles');
191 $user->clearPermissionCache();
195 * Completely remove the given permission name from the given user.
197 protected function removePermissionFromUser(User $user, string $permissionName)
199 $permissionBuilder = app()->make(JointPermissionBuilder::class);
201 /** @var RolePermission $permission */
202 $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
204 $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
205 $query->where('id', '=', $permission->id);
208 /** @var Role $role */
209 foreach ($roles as $role) {
210 $role->detachPermission($permission);
211 $permissionBuilder->rebuildForRole($role);
214 $user->clearPermissionCache();
218 * Create a new basic role for testing purposes.
220 protected function createNewRole(array $permissions = []): Role
222 $permissionRepo = app(PermissionsRepo::class);
223 $roleData = Role::factory()->make()->toArray();
224 $roleData['permissions'] = array_flip($permissions);
226 return $permissionRepo->saveNewRole($roleData);
230 * Create a group of entities that belong to a specific user.
232 * @return array{book: Book, chapter: Chapter, page: Page}
234 protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
236 if (empty($updaterUser)) {
237 $updaterUser = $creatorUser;
240 $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
241 $book = Book::factory()->create($userAttrs);
242 $chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs));
243 $page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
245 $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($book);
247 return compact('book', 'chapter', 'page');
251 * Mock the HttpFetcher service and return the given data on fetch.
253 protected function mockHttpFetch($returnData, int $times = 1)
255 $mockHttp = Mockery::mock(HttpFetcher::class);
256 $this->app[HttpFetcher::class] = $mockHttp;
257 $mockHttp->shouldReceive('fetch')
259 ->andReturn($returnData);
263 * Mock the http client used in BookStack.
264 * Returns a reference to the container which holds all history of http transactions.
266 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
268 protected function &mockHttpClient(array $responses = []): array
271 $history = Middleware::history($container);
272 $mock = new MockHandler($responses);
273 $handlerStack = new HandlerStack($mock);
274 $handlerStack->push($history);
275 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
281 * Run a set test with the given env variable.
282 * Remembers the original and resets the value after test.
284 protected function runWithEnv(string $name, $value, callable $callback)
286 Env::disablePutenv();
287 $originalVal = $_SERVER[$name] ?? null;
289 if (is_null($value)) {
290 unset($_SERVER[$name]);
292 $_SERVER[$name] = $value;
295 $this->refreshApplication();
298 if (is_null($originalVal)) {
299 unset($_SERVER[$name]);
301 $_SERVER[$name] = $originalVal;
306 * Check the keys and properties in the given map to include
307 * exist, albeit not exclusively, within the map to check.
309 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
313 foreach ($mapToInclude as $key => $value) {
314 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
319 $toIncludeStr = print_r($mapToInclude, true);
320 $toCheckStr = print_r($mapToCheck, true);
321 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
325 * Assert a permission error has occurred.
327 protected function assertPermissionError($response)
329 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
333 * Assert a permission error has occurred.
335 protected function assertNotPermissionError($response)
337 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
341 * Check if the given response is a permission error.
343 private function isPermissionError($response): bool
345 return $response->status() === 302
348 $response->headers->get('Location') === url('/')
349 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
353 $response instanceof JsonResponse &&
354 $response->json(['error' => 'You do not have permission to perform the requested action.'])
360 * Assert that the session has a particular error notification message set.
362 protected function assertSessionError(string $message)
364 $error = session()->get('error');
365 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
369 * Set a test handler as the logging interface for the application.
370 * Allows capture of logs for checking against during tests.
372 protected function withTestLogger(): TestHandler
374 $monolog = new Logger('testing');
375 $testHandler = new TestHandler();
376 $monolog->pushHandler($testHandler);
378 Log::extend('testing', function () use ($monolog) {
381 Log::setDefaultDriver('testing');