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