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