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