]> BookStack Code Mirror - bookstack/blob - tests/TestCase.php
Sorting: Updated sort set command, Changed sort timestamp handling
[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(string $name, $value, callable $callback)
122     {
123         Env::disablePutenv();
124         $originalVal = $_SERVER[$name] ?? null;
125
126         if (is_null($value)) {
127             unset($_SERVER[$name]);
128         } else {
129             $_SERVER[$name] = $value;
130         }
131
132         $database = config('database.connections.mysql_testing.database');
133         $this->refreshApplication();
134
135         DB::purge();
136         config()->set('database.connections.mysql_testing.database', $database);
137         DB::beginTransaction();
138
139         $callback();
140
141         DB::rollBack();
142
143         if (is_null($originalVal)) {
144             unset($_SERVER[$name]);
145         } else {
146             $_SERVER[$name] = $originalVal;
147         }
148     }
149
150     /**
151      * Check the keys and properties in the given map to include
152      * exist, albeit not exclusively, within the map to check.
153      */
154     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
155     {
156         $passed = true;
157
158         foreach ($mapToInclude as $key => $value) {
159             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
160                 $passed = false;
161             }
162         }
163
164         $toIncludeStr = print_r($mapToInclude, true);
165         $toCheckStr = print_r($mapToCheck, true);
166         self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
167     }
168
169     /**
170      * Assert a permission error has occurred.
171      */
172     protected function assertPermissionError($response)
173     {
174         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
175     }
176
177     /**
178      * Assert a permission error has occurred.
179      */
180     protected function assertNotPermissionError($response)
181     {
182         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
183     }
184
185     /**
186      * Check if the given response is a permission error.
187      */
188     private function isPermissionError($response): bool
189     {
190         if ($response->status() === 403 && $response instanceof JsonResponse) {
191             $errMessage = $response->getData(true)['error']['message'] ?? '';
192             return $errMessage === 'You do not have permission to perform the requested action.';
193         }
194
195         return $response->status() === 302
196             && $response->headers->get('Location') === url('/')
197             && str_starts_with(session()->pull('error', ''), 'You do not have permission to access');
198     }
199
200     /**
201      * Assert that the session has a particular error notification message set.
202      */
203     protected function assertSessionError(string $message)
204     {
205         $error = session()->get('error');
206         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
207     }
208
209     /**
210      * Assert the session contains a specific entry.
211      */
212     protected function assertSessionHas(string $key): self
213     {
214         $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
215
216         return $this;
217     }
218
219     protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
220     {
221         return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
222     }
223
224     /**
225      * Set a test handler as the logging interface for the application.
226      * Allows capture of logs for checking against during tests.
227      */
228     protected function withTestLogger(): TestHandler
229     {
230         $monolog = new Logger('testing');
231         $testHandler = new TestHandler();
232         $monolog->pushHandler($testHandler);
233
234         Log::extend('testing', function () use ($monolog) {
235             return $monolog;
236         });
237         Log::setDefaultDriver('testing');
238
239         return $testHandler;
240     }
241
242     /**
243      * Assert that an activity entry exists of the given key.
244      * Checks the activity belongs to the given entity if provided.
245      */
246     protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
247     {
248         $detailsToCheck = ['type' => $type];
249
250         if ($entity) {
251             $detailsToCheck['loggable_type'] = $entity->getMorphClass();
252             $detailsToCheck['loggable_id'] = $entity->id;
253         }
254
255         if ($detail) {
256             $detailsToCheck['detail'] = $detail;
257         }
258
259         $this->assertDatabaseHas('activities', $detailsToCheck);
260     }
261 }