]> BookStack Code Mirror - bookstack/blob - tests/TestCase.php
Updated readme attribution and fixed eslint issues
[bookstack] / tests / TestCase.php
1 <?php
2
3 namespace Tests;
4
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Settings\SettingService;
7 use BookStack\Uploads\HttpFetcher;
8 use BookStack\Users\Models\User;
9 use GuzzleHttp\Client;
10 use GuzzleHttp\Handler\MockHandler;
11 use GuzzleHttp\HandlerStack;
12 use GuzzleHttp\Middleware;
13 use Illuminate\Contracts\Console\Kernel;
14 use Illuminate\Foundation\Testing\DatabaseTransactions;
15 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
16 use Illuminate\Http\JsonResponse;
17 use Illuminate\Support\Env;
18 use Illuminate\Support\Facades\DB;
19 use Illuminate\Support\Facades\Log;
20 use Illuminate\Testing\Assert as PHPUnit;
21 use Mockery;
22 use Monolog\Handler\TestHandler;
23 use Monolog\Logger;
24 use Psr\Http\Client\ClientInterface;
25 use Ssddanbrown\AssertHtml\TestsHtml;
26 use Tests\Helpers\EntityProvider;
27 use Tests\Helpers\FileProvider;
28 use Tests\Helpers\PermissionsProvider;
29 use Tests\Helpers\TestServiceProvider;
30 use Tests\Helpers\UserRoleProvider;
31
32 abstract class TestCase extends BaseTestCase
33 {
34     use CreatesApplication;
35     use DatabaseTransactions;
36     use TestsHtml;
37
38     protected EntityProvider $entities;
39     protected UserRoleProvider $users;
40     protected PermissionsProvider $permissions;
41     protected FileProvider $files;
42
43     protected function setUp(): void
44     {
45         $this->entities = new EntityProvider();
46         $this->users = new UserRoleProvider();
47         $this->permissions = new PermissionsProvider($this->users);
48         $this->files = new FileProvider();
49
50         User::clearDefault();
51         parent::setUp();
52
53         // We can uncomment the below to run tests with failings upon deprecations.
54         // Can't leave on since some deprecations can only be fixed upstream.
55          // $this->withoutDeprecationHandling();
56     }
57
58     /**
59      * The base URL to use while testing the application.
60      */
61     protected string $baseUrl = 'http://localhost';
62
63     /**
64      * Creates the application.
65      *
66      * @return \Illuminate\Foundation\Application
67      */
68     public function createApplication()
69     {
70         /** @var \Illuminate\Foundation\Application  $app */
71         $app = require __DIR__ . '/../bootstrap/app.php';
72         $app->register(TestServiceProvider::class);
73         $app->make(Kernel::class)->bootstrap();
74
75         return $app;
76     }
77
78     /**
79      * Set the current user context to be an admin.
80      */
81     public function asAdmin()
82     {
83         return $this->actingAs($this->users->admin());
84     }
85
86     /**
87      * Set the current user context to be an editor.
88      */
89     public function asEditor()
90     {
91         return $this->actingAs($this->users->editor());
92     }
93
94     /**
95      * Set the current user context to be a viewer.
96      */
97     public function asViewer()
98     {
99         return $this->actingAs($this->users->viewer());
100     }
101
102     /**
103      * Quickly sets an array of settings.
104      */
105     protected function setSettings(array $settingsArray): void
106     {
107         $settings = app(SettingService::class);
108         foreach ($settingsArray as $key => $value) {
109             $settings->put($key, $value);
110         }
111     }
112
113     /**
114      * Mock the HttpFetcher service and return the given data on fetch.
115      */
116     protected function mockHttpFetch($returnData, int $times = 1)
117     {
118         $mockHttp = Mockery::mock(HttpFetcher::class);
119         $this->app[HttpFetcher::class] = $mockHttp;
120         $mockHttp->shouldReceive('fetch')
121             ->times($times)
122             ->andReturn($returnData);
123     }
124
125     /**
126      * Mock the http client used in BookStack.
127      * Returns a reference to the container which holds all history of http transactions.
128      *
129      * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
130      */
131     protected function &mockHttpClient(array $responses = []): array
132     {
133         $container = [];
134         $history = Middleware::history($container);
135         $mock = new MockHandler($responses);
136         $handlerStack = new HandlerStack($mock);
137         $handlerStack->push($history);
138         $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
139
140         return $container;
141     }
142
143     /**
144      * Run a set test with the given env variable.
145      * Remembers the original and resets the value after test.
146      * Database config is juggled so the value can be restored when
147      * parallel testing are used, where multiple databases exist.
148      */
149     protected function runWithEnv(string $name, $value, callable $callback)
150     {
151         Env::disablePutenv();
152         $originalVal = $_SERVER[$name] ?? null;
153
154         if (is_null($value)) {
155             unset($_SERVER[$name]);
156         } else {
157             $_SERVER[$name] = $value;
158         }
159
160         $database = config('database.connections.mysql_testing.database');
161         $this->refreshApplication();
162
163         DB::purge();
164         config()->set('database.connections.mysql_testing.database', $database);
165         DB::beginTransaction();
166
167         $callback();
168
169         DB::rollBack();
170
171         if (is_null($originalVal)) {
172             unset($_SERVER[$name]);
173         } else {
174             $_SERVER[$name] = $originalVal;
175         }
176     }
177
178     /**
179      * Check the keys and properties in the given map to include
180      * exist, albeit not exclusively, within the map to check.
181      */
182     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
183     {
184         $passed = true;
185
186         foreach ($mapToInclude as $key => $value) {
187             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
188                 $passed = false;
189             }
190         }
191
192         $toIncludeStr = print_r($mapToInclude, true);
193         $toCheckStr = print_r($mapToCheck, true);
194         self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
195     }
196
197     /**
198      * Assert a permission error has occurred.
199      */
200     protected function assertPermissionError($response)
201     {
202         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
203     }
204
205     /**
206      * Assert a permission error has occurred.
207      */
208     protected function assertNotPermissionError($response)
209     {
210         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
211     }
212
213     /**
214      * Check if the given response is a permission error.
215      */
216     private function isPermissionError($response): bool
217     {
218         if ($response->status() === 403 && $response instanceof JsonResponse) {
219             $errMessage = $response->getData(true)['error']['message'] ?? '';
220             return $errMessage === 'You do not have permission to perform the requested action.';
221         }
222
223         return $response->status() === 302
224             && $response->headers->get('Location') === url('/')
225             && str_starts_with(session()->pull('error', ''), 'You do not have permission to access');
226     }
227
228     /**
229      * Assert that the session has a particular error notification message set.
230      */
231     protected function assertSessionError(string $message)
232     {
233         $error = session()->get('error');
234         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
235     }
236
237     /**
238      * Assert the session contains a specific entry.
239      */
240     protected function assertSessionHas(string $key): self
241     {
242         $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
243
244         return $this;
245     }
246
247     protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
248     {
249         return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
250     }
251
252     /**
253      * Set a test handler as the logging interface for the application.
254      * Allows capture of logs for checking against during tests.
255      */
256     protected function withTestLogger(): TestHandler
257     {
258         $monolog = new Logger('testing');
259         $testHandler = new TestHandler();
260         $monolog->pushHandler($testHandler);
261
262         Log::extend('testing', function () use ($monolog) {
263             return $monolog;
264         });
265         Log::setDefaultDriver('testing');
266
267         return $testHandler;
268     }
269
270     /**
271      * Assert that an activity entry exists of the given key.
272      * Checks the activity belongs to the given entity if provided.
273      */
274     protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
275     {
276         $detailsToCheck = ['type' => $type];
277
278         if ($entity) {
279             $detailsToCheck['entity_type'] = $entity->getMorphClass();
280             $detailsToCheck['entity_id'] = $entity->id;
281         }
282
283         if ($detail) {
284             $detailsToCheck['detail'] = $detail;
285         }
286
287         $this->assertDatabaseHas('activities', $detailsToCheck);
288     }
289 }