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