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