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