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