]> BookStack Code Mirror - bookstack/blob - tests/TestCase.php
ZIP Imports: Added API examples, finished testing
[bookstack] / tests / TestCase.php
1 <?php
2
3 namespace Tests;
4
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Http\HttpClientHistory;
7 use BookStack\Http\HttpRequestService;
8 use BookStack\Settings\SettingService;
9 use BookStack\Users\Models\User;
10 use Illuminate\Contracts\Console\Kernel;
11 use Illuminate\Foundation\Testing\DatabaseTransactions;
12 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
13 use Illuminate\Http\JsonResponse;
14 use Illuminate\Support\Env;
15 use Illuminate\Support\Facades\DB;
16 use Illuminate\Support\Facades\Log;
17 use Illuminate\Testing\Assert as PHPUnit;
18 use Monolog\Handler\TestHandler;
19 use Monolog\Logger;
20 use Ssddanbrown\AssertHtml\TestsHtml;
21 use Tests\Helpers\EntityProvider;
22 use Tests\Helpers\FileProvider;
23 use Tests\Helpers\PermissionsProvider;
24 use Tests\Helpers\TestServiceProvider;
25 use Tests\Helpers\UserRoleProvider;
26
27 abstract class TestCase extends BaseTestCase
28 {
29     use CreatesApplication;
30     use DatabaseTransactions;
31     use TestsHtml;
32
33     protected EntityProvider $entities;
34     protected UserRoleProvider $users;
35     protected PermissionsProvider $permissions;
36     protected FileProvider $files;
37
38     protected function setUp(): void
39     {
40         $this->entities = new EntityProvider();
41         $this->users = new UserRoleProvider();
42         $this->permissions = new PermissionsProvider($this->users);
43         $this->files = new FileProvider();
44
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->users->admin());
78     }
79
80     /**
81      * Set the current user context to be an editor.
82      */
83     public function asEditor()
84     {
85         return $this->actingAs($this->users->editor());
86     }
87
88     /**
89      * Set the current user context to be a viewer.
90      */
91     public function asViewer()
92     {
93         return $this->actingAs($this->users->viewer());
94     }
95
96     /**
97      * Quickly sets an array of settings.
98      */
99     protected function setSettings(array $settingsArray): void
100     {
101         $settings = app(SettingService::class);
102         foreach ($settingsArray as $key => $value) {
103             $settings->put($key, $value);
104         }
105     }
106
107     /**
108      * Mock the http client used in BookStack http calls.
109      */
110     protected function mockHttpClient(array $responses = []): HttpClientHistory
111     {
112         return $this->app->make(HttpRequestService::class)->mockClient($responses);
113     }
114
115     /**
116      * Run a set test with the given env variable.
117      * Remembers the original and resets the value after test.
118      * Database config is juggled so the value can be restored when
119      * parallel testing are used, where multiple databases exist.
120      */
121     protected function runWithEnv(array $valuesByKey, callable $callback, bool $handleDatabase = true): void
122     {
123         Env::disablePutenv();
124         $originals = [];
125         foreach ($valuesByKey as $key => $value) {
126             $originals[$key] = $_SERVER[$key] ?? null;
127
128             if (is_null($value)) {
129                 unset($_SERVER[$key]);
130             } else {
131                 $_SERVER[$key] = $value;
132             }
133         }
134
135         $database = config('database.connections.mysql_testing.database');
136         $this->refreshApplication();
137
138         if ($handleDatabase) {
139             DB::purge();
140             config()->set('database.connections.mysql_testing.database', $database);
141             DB::beginTransaction();
142         }
143
144         $callback();
145
146         if ($handleDatabase) {
147             DB::rollBack();
148         }
149
150         foreach ($originals as $key => $value) {
151             if (is_null($value)) {
152                 unset($_SERVER[$key]);
153             } else {
154                 $_SERVER[$key] = $value;
155             }
156         }
157     }
158
159     /**
160      * Check the keys and properties in the given map to include
161      * exist, albeit not exclusively, within the map to check.
162      */
163     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
164     {
165         $passed = true;
166
167         foreach ($mapToInclude as $key => $value) {
168             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
169                 $passed = false;
170             }
171         }
172
173         $toIncludeStr = print_r($mapToInclude, true);
174         $toCheckStr = print_r($mapToCheck, true);
175         self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
176     }
177
178     /**
179      * Assert a permission error has occurred.
180      */
181     protected function assertPermissionError($response)
182     {
183         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
184     }
185
186     /**
187      * Assert a permission error has occurred.
188      */
189     protected function assertNotPermissionError($response)
190     {
191         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
192     }
193
194     /**
195      * Check if the given response is a permission error.
196      */
197     private function isPermissionError($response): bool
198     {
199         if ($response->status() === 403 && $response instanceof JsonResponse) {
200             $errMessage = $response->getData(true)['error']['message'] ?? '';
201             return $errMessage === 'You do not have permission to perform the requested action.';
202         }
203
204         return $response->status() === 302
205             && $response->headers->get('Location') === url('/')
206             && str_starts_with(session()->pull('error', ''), 'You do not have permission to access');
207     }
208
209     /**
210      * Assert that the session has a particular error notification message set.
211      */
212     protected function assertSessionError(string $message)
213     {
214         $error = session()->get('error');
215         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
216     }
217
218     /**
219      * Assert the session contains a specific entry.
220      */
221     protected function assertSessionHas(string $key): self
222     {
223         $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
224
225         return $this;
226     }
227
228     protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
229     {
230         return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
231     }
232
233     /**
234      * Set a test handler as the logging interface for the application.
235      * Allows capture of logs for checking against during tests.
236      */
237     protected function withTestLogger(): TestHandler
238     {
239         $monolog = new Logger('testing');
240         $testHandler = new TestHandler();
241         $monolog->pushHandler($testHandler);
242
243         Log::extend('testing', function () use ($monolog) {
244             return $monolog;
245         });
246         Log::setDefaultDriver('testing');
247
248         return $testHandler;
249     }
250
251     /**
252      * Assert that an activity entry exists of the given key.
253      * Checks the activity belongs to the given entity if provided.
254      */
255     protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
256     {
257         $detailsToCheck = ['type' => $type];
258
259         if ($entity) {
260             $detailsToCheck['loggable_type'] = $entity->getMorphClass();
261             $detailsToCheck['loggable_id'] = $entity->id;
262         }
263
264         if ($detail) {
265             $detailsToCheck['detail'] = $detail;
266         }
267
268         $this->assertDatabaseHas('activities', $detailsToCheck);
269     }
270 }