5 use BookStack\Auth\Permissions\PermissionService;
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 Illuminate\Foundation\Testing\Assert as PHPUnit;
22 use Illuminate\Http\JsonResponse;
23 use Illuminate\Support\Env;
24 use Illuminate\Support\Facades\Log;
26 use Monolog\Handler\TestHandler;
29 trait SharedTestHelpers
35 * Set the current user context to be an admin.
37 public function asAdmin()
39 return $this->actingAs($this->getAdmin());
43 * Get the current admin user.
45 public function getAdmin(): User
47 if (is_null($this->admin)) {
48 $adminRole = Role::getSystemRole('admin');
49 $this->admin = $adminRole->users->first();
56 * Set the current user context to be an editor.
58 public function asEditor()
60 return $this->actingAs($this->getEditor());
66 protected function getEditor(): User
68 if ($this->editor === null) {
69 $editorRole = Role::getRole('editor');
70 $this->editor = $editorRole->users->first();
77 * Get an instance of a user with 'viewer' permissions.
79 protected function getViewer(array $attributes = []): User
81 $user = Role::getRole('viewer')->users()->first();
82 if (!empty($attributes)) {
83 $user->forceFill($attributes)->save();
90 * Get a user that's not a system user such as the guest user.
92 public function getNormalUser(): User
94 return User::query()->where('system_name', '=', null)->get()->last();
98 * Regenerate the permission for an entity.
100 protected function regenEntityPermissions(Entity $entity): void
102 $entity->rebuildPermissions();
103 $entity->load('jointPermissions');
107 * Create and return a new bookshelf.
109 public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
111 return app(BookshelfRepo::class)->create($input, []);
115 * Create and return a new book.
117 public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
119 return app(BookRepo::class)->create($input);
123 * Create and return a new test chapter.
125 public function newChapter(array $input = ['name' => 'test chapter', 'description' => 'My new test chapter'], Book $book): Chapter
127 return app(ChapterRepo::class)->create($input, $book);
131 * Create and return a new test page.
133 public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
135 $book = Book::query()->first();
136 $pageRepo = app(PageRepo::class);
137 $draftPage = $pageRepo->getNewDraftPage($book);
139 return $pageRepo->publishDraft($draftPage, $input);
143 * Quickly sets an array of settings.
145 protected function setSettings(array $settingsArray): void
147 $settings = app(SettingService::class);
148 foreach ($settingsArray as $key => $value) {
149 $settings->put($key, $value);
154 * Manually set some permissions on an entity.
156 protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
158 $entity->restricted = true;
159 $entity->permissions()->delete();
162 foreach ($actions as $action) {
163 foreach ($roles as $role) {
165 'role_id' => $role->id,
166 'action' => strtolower($action),
170 $entity->permissions()->createMany($permissions);
173 $entity->load('permissions');
174 $this->app[PermissionService::class]->buildJointPermissionsForEntity($entity);
175 $entity->load('jointPermissions');
179 * Give the given user some permissions.
181 protected function giveUserPermissions(User $user, array $permissions = []): void
183 $newRole = $this->createNewRole($permissions);
184 $user->attachRole($newRole);
185 $user->load('roles');
186 $user->clearPermissionCache();
190 * Completely remove the given permission name from the given user.
192 protected function removePermissionFromUser(User $user, string $permission)
194 $permission = RolePermission::query()->where('name', '=', $permission)->first();
195 /** @var Role $role */
196 foreach ($user->roles as $role) {
197 $role->detachPermission($permission);
199 $user->clearPermissionCache();
203 * Create a new basic role for testing purposes.
205 protected function createNewRole(array $permissions = []): Role
207 $permissionRepo = app(PermissionsRepo::class);
208 $roleData = factory(Role::class)->make()->toArray();
209 $roleData['permissions'] = array_flip($permissions);
211 return $permissionRepo->saveNewRole($roleData);
215 * Create a group of entities that belong to a specific user.
217 * @return array{book: Book, chapter: Chapter, page: Page}
219 protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
221 if (empty($updaterUser)) {
222 $updaterUser = $creatorUser;
225 $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
226 $book = factory(Book::class)->create($userAttrs);
227 $chapter = factory(Chapter::class)->create(array_merge(['book_id' => $book->id], $userAttrs));
228 $page = factory(Page::class)->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
229 $restrictionService = $this->app[PermissionService::class];
230 $restrictionService->buildJointPermissionsForEntity($book);
232 return compact('book', 'chapter', 'page');
236 * Mock the HttpFetcher service and return the given data on fetch.
238 protected function mockHttpFetch($returnData, int $times = 1)
240 $mockHttp = Mockery::mock(HttpFetcher::class);
241 $this->app[HttpFetcher::class] = $mockHttp;
242 $mockHttp->shouldReceive('fetch')
244 ->andReturn($returnData);
248 * Run a set test with the given env variable.
249 * Remembers the original and resets the value after test.
251 protected function runWithEnv(string $name, $value, callable $callback)
253 Env::disablePutenv();
254 $originalVal = $_SERVER[$name] ?? null;
256 if (is_null($value)) {
257 unset($_SERVER[$name]);
259 $_SERVER[$name] = $value;
262 $this->refreshApplication();
265 if (is_null($originalVal)) {
266 unset($_SERVER[$name]);
268 $_SERVER[$name] = $originalVal;
273 * Check the keys and properties in the given map to include
274 * exist, albeit not exclusively, within the map to check.
276 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
280 foreach ($mapToInclude as $key => $value) {
281 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
286 $toIncludeStr = print_r($mapToInclude, true);
287 $toCheckStr = print_r($mapToCheck, true);
288 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
292 * Assert a permission error has occurred.
294 protected function assertPermissionError($response)
296 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
300 * Assert a permission error has occurred.
302 protected function assertNotPermissionError($response)
304 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
308 * Check if the given response is a permission error.
310 private function isPermissionError($response): bool
312 return $response->status() === 302
315 $response->headers->get('Location') === url('/')
316 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
320 $response instanceof JsonResponse &&
321 $response->json(['error' => 'You do not have permission to perform the requested action.'])
327 * Set a test handler as the logging interface for the application.
328 * Allows capture of logs for checking against during tests.
330 protected function withTestLogger(): TestHandler
332 $monolog = new Logger('testing');
333 $testHandler = new TestHandler();
334 $monolog->pushHandler($testHandler);
336 Log::extend('testing', function () use ($monolog) {
339 Log::setDefaultDriver('testing');