]> BookStack Code Mirror - bookstack/blob - tests/SharedTestHelpers.php
Added testing to cover debug view
[bookstack] / tests / SharedTestHelpers.php
1 <?php
2
3 namespace Tests;
4
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;
25 use Mockery;
26 use Monolog\Handler\TestHandler;
27 use Monolog\Logger;
28
29 trait SharedTestHelpers
30 {
31     protected $admin;
32     protected $editor;
33
34     /**
35      * Set the current user context to be an admin.
36      */
37     public function asAdmin()
38     {
39         return $this->actingAs($this->getAdmin());
40     }
41
42     /**
43      * Get the current admin user.
44      */
45     public function getAdmin(): User
46     {
47         if (is_null($this->admin)) {
48             $adminRole = Role::getSystemRole('admin');
49             $this->admin = $adminRole->users->first();
50         }
51
52         return $this->admin;
53     }
54
55     /**
56      * Set the current user context to be an editor.
57      */
58     public function asEditor()
59     {
60         return $this->actingAs($this->getEditor());
61     }
62
63     /**
64      * Get a editor user.
65      */
66     protected function getEditor(): User
67     {
68         if ($this->editor === null) {
69             $editorRole = Role::getRole('editor');
70             $this->editor = $editorRole->users->first();
71         }
72
73         return $this->editor;
74     }
75
76     /**
77      * Get an instance of a user with 'viewer' permissions.
78      */
79     protected function getViewer(array $attributes = []): User
80     {
81         $user = Role::getRole('viewer')->users()->first();
82         if (!empty($attributes)) {
83             $user->forceFill($attributes)->save();
84         }
85
86         return $user;
87     }
88
89     /**
90      * Get a user that's not a system user such as the guest user.
91      */
92     public function getNormalUser(): User
93     {
94         return User::query()->where('system_name', '=', null)->get()->last();
95     }
96
97     /**
98      * Regenerate the permission for an entity.
99      */
100     protected function regenEntityPermissions(Entity $entity): void
101     {
102         $entity->rebuildPermissions();
103         $entity->load('jointPermissions');
104     }
105
106     /**
107      * Create and return a new bookshelf.
108      */
109     public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
110     {
111         return app(BookshelfRepo::class)->create($input, []);
112     }
113
114     /**
115      * Create and return a new book.
116      */
117     public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
118     {
119         return app(BookRepo::class)->create($input);
120     }
121
122     /**
123      * Create and return a new test chapter.
124      */
125     public function newChapter(array $input = ['name' => 'test chapter', 'description' => 'My new test chapter'], Book $book): Chapter
126     {
127         return app(ChapterRepo::class)->create($input, $book);
128     }
129
130     /**
131      * Create and return a new test page.
132      */
133     public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
134     {
135         $book = Book::query()->first();
136         $pageRepo = app(PageRepo::class);
137         $draftPage = $pageRepo->getNewDraftPage($book);
138
139         return $pageRepo->publishDraft($draftPage, $input);
140     }
141
142     /**
143      * Quickly sets an array of settings.
144      */
145     protected function setSettings(array $settingsArray): void
146     {
147         $settings = app(SettingService::class);
148         foreach ($settingsArray as $key => $value) {
149             $settings->put($key, $value);
150         }
151     }
152
153     /**
154      * Manually set some permissions on an entity.
155      */
156     protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
157     {
158         $entity->restricted = true;
159         $entity->permissions()->delete();
160
161         $permissions = [];
162         foreach ($actions as $action) {
163             foreach ($roles as $role) {
164                 $permissions[] = [
165                     'role_id' => $role->id,
166                     'action'  => strtolower($action),
167                 ];
168             }
169         }
170         $entity->permissions()->createMany($permissions);
171
172         $entity->save();
173         $entity->load('permissions');
174         $this->app[PermissionService::class]->buildJointPermissionsForEntity($entity);
175         $entity->load('jointPermissions');
176     }
177
178     /**
179      * Give the given user some permissions.
180      */
181     protected function giveUserPermissions(User $user, array $permissions = []): void
182     {
183         $newRole = $this->createNewRole($permissions);
184         $user->attachRole($newRole);
185         $user->load('roles');
186         $user->clearPermissionCache();
187     }
188
189     /**
190      * Completely remove the given permission name from the given user.
191      */
192     protected function removePermissionFromUser(User $user, string $permission)
193     {
194         $permission = RolePermission::query()->where('name', '=', $permission)->first();
195         /** @var Role $role */
196         foreach ($user->roles as $role) {
197             $role->detachPermission($permission);
198         }
199         $user->clearPermissionCache();
200     }
201
202     /**
203      * Create a new basic role for testing purposes.
204      */
205     protected function createNewRole(array $permissions = []): Role
206     {
207         $permissionRepo = app(PermissionsRepo::class);
208         $roleData = factory(Role::class)->make()->toArray();
209         $roleData['permissions'] = array_flip($permissions);
210
211         return $permissionRepo->saveNewRole($roleData);
212     }
213
214     /**
215      * Create a group of entities that belong to a specific user.
216      *
217      * @return array{book: Book, chapter: Chapter, page: Page}
218      */
219     protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
220     {
221         if (empty($updaterUser)) {
222             $updaterUser = $creatorUser;
223         }
224
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);
231
232         return compact('book', 'chapter', 'page');
233     }
234
235     /**
236      * Mock the HttpFetcher service and return the given data on fetch.
237      */
238     protected function mockHttpFetch($returnData, int $times = 1)
239     {
240         $mockHttp = Mockery::mock(HttpFetcher::class);
241         $this->app[HttpFetcher::class] = $mockHttp;
242         $mockHttp->shouldReceive('fetch')
243             ->times($times)
244             ->andReturn($returnData);
245     }
246
247     /**
248      * Run a set test with the given env variable.
249      * Remembers the original and resets the value after test.
250      */
251     protected function runWithEnv(string $name, $value, callable $callback)
252     {
253         Env::disablePutenv();
254         $originalVal = $_SERVER[$name] ?? null;
255
256         if (is_null($value)) {
257             unset($_SERVER[$name]);
258         } else {
259             $_SERVER[$name] = $value;
260         }
261
262         $this->refreshApplication();
263         $callback();
264
265         if (is_null($originalVal)) {
266             unset($_SERVER[$name]);
267         } else {
268             $_SERVER[$name] = $originalVal;
269         }
270     }
271
272     /**
273      * Check the keys and properties in the given map to include
274      * exist, albeit not exclusively, within the map to check.
275      */
276     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
277     {
278         $passed = true;
279
280         foreach ($mapToInclude as $key => $value) {
281             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
282                 $passed = false;
283             }
284         }
285
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}");
289     }
290
291     /**
292      * Assert a permission error has occurred.
293      */
294     protected function assertPermissionError($response)
295     {
296         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
297     }
298
299     /**
300      * Assert a permission error has occurred.
301      */
302     protected function assertNotPermissionError($response)
303     {
304         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
305     }
306
307     /**
308      * Check if the given response is a permission error.
309      */
310     private function isPermissionError($response): bool
311     {
312         return $response->status() === 302
313             && (
314                 (
315                     $response->headers->get('Location') === url('/')
316                     && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
317                 )
318                 ||
319                 (
320                     $response instanceof JsonResponse &&
321                     $response->json(['error' => 'You do not have permission to perform the requested action.'])
322                 )
323             );
324     }
325
326     /**
327      * Set a test handler as the logging interface for the application.
328      * Allows capture of logs for checking against during tests.
329      */
330     protected function withTestLogger(): TestHandler
331     {
332         $monolog = new Logger('testing');
333         $testHandler = new TestHandler();
334         $monolog->pushHandler($testHandler);
335
336         Log::extend('testing', function () use ($monolog) {
337             return $monolog;
338         });
339         Log::setDefaultDriver('testing');
340
341         return $testHandler;
342     }
343 }