3 use BookStack\Auth\User;
4 use BookStack\Entities\Models\Book;
5 use BookStack\Entities\Models\Bookshelf;
6 use BookStack\Entities\Models\Chapter;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\Models\Page;
9 use BookStack\Entities\Repos\BookRepo;
10 use BookStack\Entities\Repos\BookshelfRepo;
11 use BookStack\Entities\Repos\ChapterRepo;
12 use BookStack\Auth\Permissions\PermissionsRepo;
13 use BookStack\Auth\Role;
14 use BookStack\Auth\Permissions\PermissionService;
15 use BookStack\Entities\Repos\PageRepo;
16 use BookStack\Settings\SettingService;
17 use BookStack\Uploads\HttpFetcher;
18 use Illuminate\Support\Env;
19 use Illuminate\Support\Facades\Log;
21 use Monolog\Handler\TestHandler;
23 use Illuminate\Foundation\Testing\Assert as PHPUnit;
25 trait SharedTestHelpers
32 * Set the current user context to be an admin.
34 public function asAdmin()
36 return $this->actingAs($this->getAdmin());
40 * Get the current admin user.
42 public function getAdmin(): User
44 if (is_null($this->admin)) {
45 $adminRole = Role::getSystemRole('admin');
46 $this->admin = $adminRole->users->first();
53 * Set the current user context to be an editor.
55 public function asEditor()
57 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();
74 * Get an instance of a user with 'viewer' permissions.
76 protected function getViewer(array $attributes = []): User
78 $user = Role::getRole('viewer')->users()->first();
79 if (!empty($attributes)) {
80 $user->forceFill($attributes)->save();
86 * Regenerate the permission for an entity.
88 protected function regenEntityPermissions(Entity $entity): void
90 $entity->rebuildPermissions();
91 $entity->load('jointPermissions');
95 * Create and return a new bookshelf.
97 public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
99 return app(BookshelfRepo::class)->create($input, []);
103 * Create and return a new book.
105 public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
107 return app(BookRepo::class)->create($input);
111 * Create and return a new test chapter
113 public function newChapter(array $input = ['name' => 'test chapter', 'description' => 'My new test chapter'], Book $book): Chapter
115 return app(ChapterRepo::class)->create($input, $book);
119 * Create and return a new test page
121 public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
123 $book = Book::query()->first();
124 $pageRepo = app(PageRepo::class);
125 $draftPage = $pageRepo->getNewDraftPage($book);
126 return $pageRepo->publishDraft($draftPage, $input);
130 * Quickly sets an array of settings.
132 protected function setSettings(array $settingsArray): void
134 $settings = app(SettingService::class);
135 foreach ($settingsArray as $key => $value) {
136 $settings->put($key, $value);
141 * Manually set some permissions on an entity.
143 protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
145 $entity->restricted = true;
146 $entity->permissions()->delete();
149 foreach ($actions as $action) {
150 foreach ($roles as $role) {
152 'role_id' => $role->id,
153 'action' => strtolower($action)
157 $entity->permissions()->createMany($permissions);
160 $entity->load('permissions');
161 $this->app[PermissionService::class]->buildJointPermissionsForEntity($entity);
162 $entity->load('jointPermissions');
166 * Give the given user some permissions.
168 protected function giveUserPermissions(User $user, array $permissions = []): void
170 $newRole = $this->createNewRole($permissions);
171 $user->attachRole($newRole);
172 $user->load('roles');
173 $user->clearPermissionCache();
177 * Create a new basic role for testing purposes.
179 protected function createNewRole(array $permissions = []): Role
181 $permissionRepo = app(PermissionsRepo::class);
182 $roleData = factory(Role::class)->make()->toArray();
183 $roleData['permissions'] = array_flip($permissions);
184 return $permissionRepo->saveNewRole($roleData);
188 * Mock the HttpFetcher service and return the given data on fetch.
190 protected function mockHttpFetch($returnData, int $times = 1)
192 $mockHttp = Mockery::mock(HttpFetcher::class);
193 $this->app[HttpFetcher::class] = $mockHttp;
194 $mockHttp->shouldReceive('fetch')
196 ->andReturn($returnData);
200 * Run a set test with the given env variable.
201 * Remembers the original and resets the value after test.
203 protected function runWithEnv(string $name, $value, callable $callback)
205 Env::disablePutenv();
206 $originalVal = $_SERVER[$name] ?? null;
208 if (is_null($value)) {
209 unset($_SERVER[$name]);
211 $_SERVER[$name] = $value;
214 $this->refreshApplication();
217 if (is_null($originalVal)) {
218 unset($_SERVER[$name]);
220 $_SERVER[$name] = $originalVal;
225 * Check the keys and properties in the given map to include
226 * exist, albeit not exclusively, within the map to check.
228 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
232 foreach ($mapToInclude as $key => $value) {
233 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
238 $toIncludeStr = print_r($mapToInclude, true);
239 $toCheckStr = print_r($mapToCheck, true);
240 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
244 * Assert a permission error has occurred.
246 protected function assertPermissionError($response)
248 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), "Failed asserting the response contains a permission error.");
252 * Assert a permission error has occurred.
254 protected function assertNotPermissionError($response)
256 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), "Failed asserting the response does not contain a permission error.");
260 * Check if the given response is a permission error.
262 private function isPermissionError($response): bool
264 return $response->status() === 302
265 && $response->headers->get('Location') === url('/')
266 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0;
270 * Set a test handler as the logging interface for the application.
271 * Allows capture of logs for checking against during tests.
273 protected function withTestLogger(): TestHandler
275 $monolog = new Logger('testing');
276 $testHandler = new TestHandler();
277 $monolog->pushHandler($testHandler);
279 Log::extend('testing', function () use ($monolog) {
282 Log::setDefaultDriver('testing');