]> BookStack Code Mirror - bookstack/blob - tests/TestCase.php
Updated readme for phpcs usage, aligned gh action workflows
[bookstack] / tests / TestCase.php
1 <?php
2
3 namespace Tests;
4
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\Foundation\Testing\DatabaseTransactions;
26 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
27 use Illuminate\Http\JsonResponse;
28 use Illuminate\Support\Env;
29 use Illuminate\Support\Facades\Log;
30 use Illuminate\Testing\Assert as PHPUnit;
31 use Monolog\Handler\TestHandler;
32 use Monolog\Logger;
33 use Psr\Http\Client\ClientInterface;
34 use Ssddanbrown\AssertHtml\TestsHtml;
35
36 abstract class TestCase extends BaseTestCase
37 {
38     use CreatesApplication;
39     use DatabaseTransactions;
40     use TestsHtml;
41
42     protected ?User $admin = null;
43     protected ?User $editor = null;
44
45     /**
46      * The base URL to use while testing the application.
47      */
48     protected string $baseUrl = 'http://localhost';
49
50     /**
51      * Set the current user context to be an admin.
52      */
53     public function asAdmin()
54     {
55         return $this->actingAs($this->getAdmin());
56     }
57
58     /**
59      * Get the current admin user.
60      */
61     public function getAdmin(): User
62     {
63         if (is_null($this->admin)) {
64             $adminRole = Role::getSystemRole('admin');
65             $this->admin = $adminRole->users->first();
66         }
67
68         return $this->admin;
69     }
70
71     /**
72      * Set the current user context to be an editor.
73      */
74     public function asEditor()
75     {
76         return $this->actingAs($this->getEditor());
77     }
78
79     /**
80      * Get a editor user.
81      */
82     protected function getEditor(): User
83     {
84         if ($this->editor === null) {
85             $editorRole = Role::getRole('editor');
86             $this->editor = $editorRole->users->first();
87         }
88
89         return $this->editor;
90     }
91
92     /**
93      * Set the current user context to be a viewer.
94      */
95     public function asViewer()
96     {
97         return $this->actingAs($this->getViewer());
98     }
99
100     /**
101      * Get an instance of a user with 'viewer' permissions.
102      */
103     protected function getViewer(array $attributes = []): User
104     {
105         $user = Role::getRole('viewer')->users()->first();
106         if (!empty($attributes)) {
107             $user->forceFill($attributes)->save();
108         }
109
110         return $user;
111     }
112
113     /**
114      * Get a user that's not a system user such as the guest user.
115      */
116     public function getNormalUser(): User
117     {
118         return User::query()->where('system_name', '=', null)->get()->last();
119     }
120
121     /**
122      * Regenerate the permission for an entity.
123      */
124     protected function regenEntityPermissions(Entity $entity): void
125     {
126         $entity->rebuildPermissions();
127         $entity->load('jointPermissions');
128     }
129
130     /**
131      * Create and return a new bookshelf.
132      */
133     public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
134     {
135         return app(BookshelfRepo::class)->create($input, []);
136     }
137
138     /**
139      * Create and return a new book.
140      */
141     public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
142     {
143         return app(BookRepo::class)->create($input);
144     }
145
146     /**
147      * Create and return a new test chapter.
148      */
149     public function newChapter(array $input, Book $book): Chapter
150     {
151         return app(ChapterRepo::class)->create($input, $book);
152     }
153
154     /**
155      * Create and return a new test page.
156      */
157     public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
158     {
159         $book = Book::query()->first();
160         $pageRepo = app(PageRepo::class);
161         $draftPage = $pageRepo->getNewDraftPage($book);
162
163         return $pageRepo->publishDraft($draftPage, $input);
164     }
165
166     /**
167      * Quickly sets an array of settings.
168      */
169     protected function setSettings(array $settingsArray): void
170     {
171         $settings = app(SettingService::class);
172         foreach ($settingsArray as $key => $value) {
173             $settings->put($key, $value);
174         }
175     }
176
177     /**
178      * Manually set some permissions on an entity.
179      */
180     protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
181     {
182         $entity->restricted = true;
183         $entity->permissions()->delete();
184
185         $permissions = [];
186         foreach ($actions as $action) {
187             foreach ($roles as $role) {
188                 $permissions[] = [
189                     'role_id' => $role->id,
190                     'action'  => strtolower($action),
191                 ];
192             }
193         }
194         $entity->permissions()->createMany($permissions);
195
196         $entity->save();
197         $entity->load('permissions');
198         $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($entity);
199         $entity->load('jointPermissions');
200     }
201
202     /**
203      * Give the given user some permissions.
204      */
205     protected function giveUserPermissions(User $user, array $permissions = []): void
206     {
207         $newRole = $this->createNewRole($permissions);
208         $user->attachRole($newRole);
209         $user->load('roles');
210         $user->clearPermissionCache();
211     }
212
213     /**
214      * Completely remove the given permission name from the given user.
215      */
216     protected function removePermissionFromUser(User $user, string $permissionName)
217     {
218         $permissionBuilder = app()->make(JointPermissionBuilder::class);
219
220         /** @var RolePermission $permission */
221         $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
222
223         $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
224             $query->where('id', '=', $permission->id);
225         })->get();
226
227         /** @var Role $role */
228         foreach ($roles as $role) {
229             $role->detachPermission($permission);
230             $permissionBuilder->rebuildForRole($role);
231         }
232
233         $user->clearPermissionCache();
234     }
235
236     /**
237      * Create a new basic role for testing purposes.
238      */
239     protected function createNewRole(array $permissions = []): Role
240     {
241         $permissionRepo = app(PermissionsRepo::class);
242         $roleData = Role::factory()->make()->toArray();
243         $roleData['permissions'] = array_flip($permissions);
244
245         return $permissionRepo->saveNewRole($roleData);
246     }
247
248     /**
249      * Create a group of entities that belong to a specific user.
250      *
251      * @return array{book: Book, chapter: Chapter, page: Page}
252      */
253     protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
254     {
255         if (empty($updaterUser)) {
256             $updaterUser = $creatorUser;
257         }
258
259         $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
260         $book = Book::factory()->create($userAttrs);
261         $chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs));
262         $page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
263
264         $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($book);
265
266         return compact('book', 'chapter', 'page');
267     }
268
269     /**
270      * Mock the HttpFetcher service and return the given data on fetch.
271      */
272     protected function mockHttpFetch($returnData, int $times = 1)
273     {
274         $mockHttp = Mockery::mock(HttpFetcher::class);
275         $this->app[HttpFetcher::class] = $mockHttp;
276         $mockHttp->shouldReceive('fetch')
277             ->times($times)
278             ->andReturn($returnData);
279     }
280
281     /**
282      * Mock the http client used in BookStack.
283      * Returns a reference to the container which holds all history of http transactions.
284      *
285      * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
286      */
287     protected function &mockHttpClient(array $responses = []): array
288     {
289         $container = [];
290         $history = Middleware::history($container);
291         $mock = new MockHandler($responses);
292         $handlerStack = new HandlerStack($mock);
293         $handlerStack->push($history);
294         $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
295
296         return $container;
297     }
298
299     /**
300      * Run a set test with the given env variable.
301      * Remembers the original and resets the value after test.
302      */
303     protected function runWithEnv(string $name, $value, callable $callback)
304     {
305         Env::disablePutenv();
306         $originalVal = $_SERVER[$name] ?? null;
307
308         if (is_null($value)) {
309             unset($_SERVER[$name]);
310         } else {
311             $_SERVER[$name] = $value;
312         }
313
314         $this->refreshApplication();
315         $callback();
316
317         if (is_null($originalVal)) {
318             unset($_SERVER[$name]);
319         } else {
320             $_SERVER[$name] = $originalVal;
321         }
322     }
323
324     /**
325      * Check the keys and properties in the given map to include
326      * exist, albeit not exclusively, within the map to check.
327      */
328     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
329     {
330         $passed = true;
331
332         foreach ($mapToInclude as $key => $value) {
333             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
334                 $passed = false;
335             }
336         }
337
338         $toIncludeStr = print_r($mapToInclude, true);
339         $toCheckStr = print_r($mapToCheck, true);
340         self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
341     }
342
343     /**
344      * Assert a permission error has occurred.
345      */
346     protected function assertPermissionError($response)
347     {
348         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
349     }
350
351     /**
352      * Assert a permission error has occurred.
353      */
354     protected function assertNotPermissionError($response)
355     {
356         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
357     }
358
359     /**
360      * Check if the given response is a permission error.
361      */
362     private function isPermissionError($response): bool
363     {
364         return $response->status() === 302
365             && (
366                 (
367                     $response->headers->get('Location') === url('/')
368                     && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
369                 )
370                 ||
371                 (
372                     $response instanceof JsonResponse &&
373                     $response->json(['error' => 'You do not have permission to perform the requested action.'])
374                 )
375             );
376     }
377
378     /**
379      * Assert that the session has a particular error notification message set.
380      */
381     protected function assertSessionError(string $message)
382     {
383         $error = session()->get('error');
384         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
385     }
386
387     /**
388      * Assert the session contains a specific entry.
389      */
390     protected function assertSessionHas(string $key): self
391     {
392         $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
393
394         return $this;
395     }
396
397     protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
398     {
399         return $this->withHtml($resp)->assertElementContains('[notification]', $text);
400     }
401
402     /**
403      * Set a test handler as the logging interface for the application.
404      * Allows capture of logs for checking against during tests.
405      */
406     protected function withTestLogger(): TestHandler
407     {
408         $monolog = new Logger('testing');
409         $testHandler = new TestHandler();
410         $monolog->pushHandler($testHandler);
411
412         Log::extend('testing', function () use ($monolog) {
413             return $monolog;
414         });
415         Log::setDefaultDriver('testing');
416
417         return $testHandler;
418     }
419
420     /**
421      * Assert that an activity entry exists of the given key.
422      * Checks the activity belongs to the given entity if provided.
423      */
424     protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
425     {
426         $detailsToCheck = ['type' => $type];
427
428         if ($entity) {
429             $detailsToCheck['entity_type'] = $entity->getMorphClass();
430             $detailsToCheck['entity_id'] = $entity->id;
431         }
432
433         if ($detail) {
434             $detailsToCheck['detail'] = $detail;
435         }
436
437         $this->assertDatabaseHas('activities', $detailsToCheck);
438     }
439
440     /**
441      * @return array{page: Page, chapter: Chapter, book: Book, bookshelf: Bookshelf}
442      */
443     protected function getEachEntityType(): array
444     {
445         return [
446             'page'      => Page::query()->first(),
447             'chapter'   => Chapter::query()->first(),
448             'book'      => Book::query()->first(),
449             'bookshelf' => Bookshelf::query()->first(),
450         ];
451     }
452 }