5 use BookStack\Auth\Permissions\PermissionService;
6 use BookStack\Auth\Permissions\PermissionsRepo;
7 use BookStack\Auth\Role;
8 use BookStack\Auth\User;
9 use BookStack\Entities\Models\Book;
10 use BookStack\Entities\Models\Bookshelf;
11 use BookStack\Entities\Models\Chapter;
12 use BookStack\Entities\Models\Entity;
13 use BookStack\Entities\Models\Page;
14 use BookStack\Entities\Repos\BookRepo;
15 use BookStack\Entities\Repos\BookshelfRepo;
16 use BookStack\Entities\Repos\ChapterRepo;
17 use BookStack\Entities\Repos\PageRepo;
18 use BookStack\Settings\SettingService;
19 use BookStack\Uploads\HttpFetcher;
20 use Illuminate\Foundation\Testing\Assert as PHPUnit;
21 use Illuminate\Support\Env;
22 use Illuminate\Support\Facades\Log;
24 use Monolog\Handler\TestHandler;
27 trait SharedTestHelpers
33 * Set the current user context to be an admin.
35 public function asAdmin()
37 return $this->actingAs($this->getAdmin());
41 * Get the current admin user.
43 public function getAdmin(): User
45 if (is_null($this->admin)) {
46 $adminRole = Role::getSystemRole('admin');
47 $this->admin = $adminRole->users->first();
54 * Set the current user context to be an editor.
56 public function asEditor()
58 return $this->actingAs($this->getEditor());
64 protected function getEditor(): User
66 if ($this->editor === null) {
67 $editorRole = Role::getRole('editor');
68 $this->editor = $editorRole->users->first();
75 * Get an instance of a user with 'viewer' permissions.
77 protected function getViewer(array $attributes = []): User
79 $user = Role::getRole('viewer')->users()->first();
80 if (!empty($attributes)) {
81 $user->forceFill($attributes)->save();
88 * Get a user that's not a system user such as the guest user.
90 public function getNormalUser()
92 return User::query()->where('system_name', '=', null)->get()->last();
96 * Regenerate the permission for an entity.
98 protected function regenEntityPermissions(Entity $entity): void
100 $entity->rebuildPermissions();
101 $entity->load('jointPermissions');
105 * Create and return a new bookshelf.
107 public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
109 return app(BookshelfRepo::class)->create($input, []);
113 * Create and return a new book.
115 public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
117 return app(BookRepo::class)->create($input);
121 * Create and return a new test chapter.
123 public function newChapter(array $input = ['name' => 'test chapter', 'description' => 'My new test chapter'], Book $book): Chapter
125 return app(ChapterRepo::class)->create($input, $book);
129 * Create and return a new test page.
131 public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
133 $book = Book::query()->first();
134 $pageRepo = app(PageRepo::class);
135 $draftPage = $pageRepo->getNewDraftPage($book);
137 return $pageRepo->publishDraft($draftPage, $input);
141 * Quickly sets an array of settings.
143 protected function setSettings(array $settingsArray): void
145 $settings = app(SettingService::class);
146 foreach ($settingsArray as $key => $value) {
147 $settings->put($key, $value);
152 * Manually set some permissions on an entity.
154 protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
156 $entity->restricted = true;
157 $entity->permissions()->delete();
160 foreach ($actions as $action) {
161 foreach ($roles as $role) {
163 'role_id' => $role->id,
164 'action' => strtolower($action),
168 $entity->permissions()->createMany($permissions);
171 $entity->load('permissions');
172 $this->app[PermissionService::class]->buildJointPermissionsForEntity($entity);
173 $entity->load('jointPermissions');
177 * Give the given user some permissions.
179 protected function giveUserPermissions(User $user, array $permissions = []): void
181 $newRole = $this->createNewRole($permissions);
182 $user->attachRole($newRole);
183 $user->load('roles');
184 $user->clearPermissionCache();
188 * Create a new basic role for testing purposes.
190 protected function createNewRole(array $permissions = []): Role
192 $permissionRepo = app(PermissionsRepo::class);
193 $roleData = factory(Role::class)->make()->toArray();
194 $roleData['permissions'] = array_flip($permissions);
196 return $permissionRepo->saveNewRole($roleData);
200 * Mock the HttpFetcher service and return the given data on fetch.
202 protected function mockHttpFetch($returnData, int $times = 1)
204 $mockHttp = Mockery::mock(HttpFetcher::class);
205 $this->app[HttpFetcher::class] = $mockHttp;
206 $mockHttp->shouldReceive('fetch')
208 ->andReturn($returnData);
212 * Run a set test with the given env variable.
213 * Remembers the original and resets the value after test.
215 protected function runWithEnv(string $name, $value, callable $callback)
217 Env::disablePutenv();
218 $originalVal = $_SERVER[$name] ?? null;
220 if (is_null($value)) {
221 unset($_SERVER[$name]);
223 $_SERVER[$name] = $value;
226 $this->refreshApplication();
229 if (is_null($originalVal)) {
230 unset($_SERVER[$name]);
232 $_SERVER[$name] = $originalVal;
237 * Check the keys and properties in the given map to include
238 * exist, albeit not exclusively, within the map to check.
240 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
244 foreach ($mapToInclude as $key => $value) {
245 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
250 $toIncludeStr = print_r($mapToInclude, true);
251 $toCheckStr = print_r($mapToCheck, true);
252 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
256 * Assert a permission error has occurred.
258 protected function assertPermissionError($response)
260 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
264 * Assert a permission error has occurred.
266 protected function assertNotPermissionError($response)
268 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
272 * Check if the given response is a permission error.
274 private function isPermissionError($response): bool
276 return $response->status() === 302
277 && $response->headers->get('Location') === url('/')
278 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0;
282 * Set a test handler as the logging interface for the application.
283 * Allows capture of logs for checking against during tests.
285 protected function withTestLogger(): TestHandler
287 $monolog = new Logger('testing');
288 $testHandler = new TestHandler();
289 $monolog->pushHandler($testHandler);
291 Log::extend('testing', function () use ($monolog) {
294 Log::setDefaultDriver('testing');