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