]> BookStack Code Mirror - bookstack/blob - tests/TestCase.php
d0dd7d772084f9a6042e2902022854dfd0a7b21b
[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\Entity;
11 use BookStack\Settings\SettingService;
12 use BookStack\Uploads\HttpFetcher;
13 use GuzzleHttp\Client;
14 use GuzzleHttp\Handler\MockHandler;
15 use GuzzleHttp\HandlerStack;
16 use GuzzleHttp\Middleware;
17 use Illuminate\Contracts\Console\Kernel;
18 use Illuminate\Foundation\Testing\DatabaseTransactions;
19 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
20 use Illuminate\Http\JsonResponse;
21 use Illuminate\Support\Env;
22 use Illuminate\Support\Facades\DB;
23 use Illuminate\Support\Facades\Log;
24 use Illuminate\Testing\Assert as PHPUnit;
25 use Monolog\Handler\TestHandler;
26 use Monolog\Logger;
27 use Psr\Http\Client\ClientInterface;
28 use Ssddanbrown\AssertHtml\TestsHtml;
29 use Tests\Helpers\EntityProvider;
30 use Tests\Helpers\TestServiceProvider;
31
32 abstract class TestCase extends BaseTestCase
33 {
34     use CreatesApplication;
35     use DatabaseTransactions;
36     use TestsHtml;
37
38     protected ?User $admin = null;
39     protected ?User $editor = null;
40     protected EntityProvider $entities;
41
42     protected function setUp(): void
43     {
44         $this->entities = new EntityProvider();
45         parent::setUp();
46     }
47
48     /**
49      * The base URL to use while testing the application.
50      */
51     protected string $baseUrl = 'http://localhost';
52
53     /**
54      * Creates the application.
55      *
56      * @return \Illuminate\Foundation\Application
57      */
58     public function createApplication()
59     {
60         /** @var \Illuminate\Foundation\Application  $app */
61         $app = require __DIR__ . '/../bootstrap/app.php';
62         $app->register(TestServiceProvider::class);
63         $app->make(Kernel::class)->bootstrap();
64
65         return $app;
66     }
67
68     /**
69      * Set the current user context to be an admin.
70      */
71     public function asAdmin()
72     {
73         return $this->actingAs($this->getAdmin());
74     }
75
76     /**
77      * Get the current admin user.
78      */
79     public function getAdmin(): User
80     {
81         if (is_null($this->admin)) {
82             $adminRole = Role::getSystemRole('admin');
83             $this->admin = $adminRole->users->first();
84         }
85
86         return $this->admin;
87     }
88
89     /**
90      * Set the current user context to be an editor.
91      */
92     public function asEditor()
93     {
94         return $this->actingAs($this->getEditor());
95     }
96
97     /**
98      * Get a editor user.
99      */
100     protected function getEditor(): User
101     {
102         if ($this->editor === null) {
103             $editorRole = Role::getRole('editor');
104             $this->editor = $editorRole->users->first();
105         }
106
107         return $this->editor;
108     }
109
110     /**
111      * Set the current user context to be a viewer.
112      */
113     public function asViewer()
114     {
115         return $this->actingAs($this->getViewer());
116     }
117
118     /**
119      * Get an instance of a user with 'viewer' permissions.
120      */
121     protected function getViewer(array $attributes = []): User
122     {
123         $user = Role::getRole('viewer')->users()->first();
124         if (!empty($attributes)) {
125             $user->forceFill($attributes)->save();
126         }
127
128         return $user;
129     }
130
131     /**
132      * Get a user that's not a system user such as the guest user.
133      */
134     public function getNormalUser(): User
135     {
136         return User::query()->where('system_name', '=', null)->get()->last();
137     }
138
139     /**
140      * Quickly sets an array of settings.
141      */
142     protected function setSettings(array $settingsArray): void
143     {
144         $settings = app(SettingService::class);
145         foreach ($settingsArray as $key => $value) {
146             $settings->put($key, $value);
147         }
148     }
149
150     /**
151      * Give the given user some permissions.
152      */
153     protected function giveUserPermissions(User $user, array $permissions = []): void
154     {
155         $newRole = $this->createNewRole($permissions);
156         $user->attachRole($newRole);
157         $user->load('roles');
158         $user->clearPermissionCache();
159     }
160
161     /**
162      * Completely remove the given permission name from the given user.
163      */
164     protected function removePermissionFromUser(User $user, string $permissionName)
165     {
166         $permissionBuilder = app()->make(JointPermissionBuilder::class);
167
168         /** @var RolePermission $permission */
169         $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
170
171         $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
172             $query->where('id', '=', $permission->id);
173         })->get();
174
175         /** @var Role $role */
176         foreach ($roles as $role) {
177             $role->detachPermission($permission);
178             $permissionBuilder->rebuildForRole($role);
179         }
180
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 = Role::factory()->make()->toArray();
191         $roleData['permissions'] = array_flip($permissions);
192
193         return $permissionRepo->saveNewRole($roleData);
194     }
195
196     /**
197      * Mock the HttpFetcher service and return the given data on fetch.
198      */
199     protected function mockHttpFetch($returnData, int $times = 1)
200     {
201         $mockHttp = Mockery::mock(HttpFetcher::class);
202         $this->app[HttpFetcher::class] = $mockHttp;
203         $mockHttp->shouldReceive('fetch')
204             ->times($times)
205             ->andReturn($returnData);
206     }
207
208     /**
209      * Mock the http client used in BookStack.
210      * Returns a reference to the container which holds all history of http transactions.
211      *
212      * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
213      */
214     protected function &mockHttpClient(array $responses = []): array
215     {
216         $container = [];
217         $history = Middleware::history($container);
218         $mock = new MockHandler($responses);
219         $handlerStack = new HandlerStack($mock);
220         $handlerStack->push($history);
221         $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
222
223         return $container;
224     }
225
226     /**
227      * Run a set test with the given env variable.
228      * Remembers the original and resets the value after test.
229      * Database config is juggled so the value can be restored when
230      * parallel testing are used, where multiple databases exist.
231      */
232     protected function runWithEnv(string $name, $value, callable $callback)
233     {
234         Env::disablePutenv();
235         $originalVal = $_SERVER[$name] ?? null;
236
237         if (is_null($value)) {
238             unset($_SERVER[$name]);
239         } else {
240             $_SERVER[$name] = $value;
241         }
242
243         $database = config('database.connections.mysql_testing.database');
244         $this->refreshApplication();
245
246         DB::purge();
247         config()->set('database.connections.mysql_testing.database', $database);
248
249         $callback();
250
251         if (is_null($originalVal)) {
252             unset($_SERVER[$name]);
253         } else {
254             $_SERVER[$name] = $originalVal;
255         }
256     }
257
258     /**
259      * Check the keys and properties in the given map to include
260      * exist, albeit not exclusively, within the map to check.
261      */
262     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
263     {
264         $passed = true;
265
266         foreach ($mapToInclude as $key => $value) {
267             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
268                 $passed = false;
269             }
270         }
271
272         $toIncludeStr = print_r($mapToInclude, true);
273         $toCheckStr = print_r($mapToCheck, true);
274         self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
275     }
276
277     /**
278      * Assert a permission error has occurred.
279      */
280     protected function assertPermissionError($response)
281     {
282         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
283     }
284
285     /**
286      * Assert a permission error has occurred.
287      */
288     protected function assertNotPermissionError($response)
289     {
290         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
291     }
292
293     /**
294      * Check if the given response is a permission error.
295      */
296     private function isPermissionError($response): bool
297     {
298         return $response->status() === 302
299             && (
300                 (
301                     $response->headers->get('Location') === url('/')
302                     && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
303                 )
304                 ||
305                 (
306                     $response instanceof JsonResponse &&
307                     $response->json(['error' => 'You do not have permission to perform the requested action.'])
308                 )
309             );
310     }
311
312     /**
313      * Assert that the session has a particular error notification message set.
314      */
315     protected function assertSessionError(string $message)
316     {
317         $error = session()->get('error');
318         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
319     }
320
321     /**
322      * Assert the session contains a specific entry.
323      */
324     protected function assertSessionHas(string $key): self
325     {
326         $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
327
328         return $this;
329     }
330
331     protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
332     {
333         return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
334     }
335
336     /**
337      * Set a test handler as the logging interface for the application.
338      * Allows capture of logs for checking against during tests.
339      */
340     protected function withTestLogger(): TestHandler
341     {
342         $monolog = new Logger('testing');
343         $testHandler = new TestHandler();
344         $monolog->pushHandler($testHandler);
345
346         Log::extend('testing', function () use ($monolog) {
347             return $monolog;
348         });
349         Log::setDefaultDriver('testing');
350
351         return $testHandler;
352     }
353
354     /**
355      * Assert that an activity entry exists of the given key.
356      * Checks the activity belongs to the given entity if provided.
357      */
358     protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
359     {
360         $detailsToCheck = ['type' => $type];
361
362         if ($entity) {
363             $detailsToCheck['entity_type'] = $entity->getMorphClass();
364             $detailsToCheck['entity_id'] = $entity->id;
365         }
366
367         if ($detail) {
368             $detailsToCheck['detail'] = $detail;
369         }
370
371         $this->assertDatabaseHas('activities', $detailsToCheck);
372     }
373 }