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